|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package org.elasticsearch.search.suggest.completion; |
| 20 | + |
| 21 | +import org.apache.lucene.analysis.CharArraySet; |
| 22 | +import org.apache.lucene.index.LeafReaderContext; |
| 23 | +import org.apache.lucene.search.CollectionTerminatedException; |
| 24 | +import org.apache.lucene.search.TotalHits; |
| 25 | +import org.apache.lucene.search.suggest.Lookup; |
| 26 | +import org.apache.lucene.search.suggest.document.TopSuggestDocs; |
| 27 | +import org.apache.lucene.search.suggest.document.TopSuggestDocsCollector; |
| 28 | +import org.apache.lucene.util.PriorityQueue; |
| 29 | + |
| 30 | +import java.io.IOException; |
| 31 | +import java.util.ArrayList; |
| 32 | +import java.util.Collections; |
| 33 | +import java.util.HashMap; |
| 34 | +import java.util.List; |
| 35 | +import java.util.Map; |
| 36 | + |
| 37 | +/** |
| 38 | + * |
| 39 | + * Custom {@link TopSuggestDocsCollector} that returns top documents from the completion suggester. |
| 40 | + * <p> |
| 41 | + * TODO: this should be refactored when https://issues.apache.org/jira/browse/LUCENE-8529 is fixed. |
| 42 | + * Unlike the parent class, this collector uses the surface form to tie-break suggestions with identical |
| 43 | + * scores. |
| 44 | + * <p> |
| 45 | + * This collector groups suggestions coming from the same document but matching different contexts |
| 46 | + * or surface form together. When different contexts or surface forms match the same suggestion form only |
| 47 | + * the best one per document (sorted by weight) is kept. |
| 48 | + * <p> |
| 49 | + * This collector is also able to filter duplicate suggestion coming from different documents. |
| 50 | + * In order to keep this feature fast, the de-duplication of suggestions with different contexts is done |
| 51 | + * only on the top N*num_contexts (where N is the number of documents to return) suggestions per segment. |
| 52 | + * This means that skip_duplicates will visit at most N*num_contexts suggestions per segment to find unique suggestions |
| 53 | + * that match the input. If more than N*num_contexts suggestions are duplicated with different contexts this collector |
| 54 | + * will not be able to return more than one suggestion even when N is greater than 1. |
| 55 | + **/ |
| 56 | +class TopSuggestGroupDocsCollector extends TopSuggestDocsCollector { |
| 57 | + private final class SuggestScoreDocPriorityQueue extends PriorityQueue<TopSuggestDocs.SuggestScoreDoc> { |
| 58 | + /** |
| 59 | + * Creates a new priority queue of the specified size. |
| 60 | + */ |
| 61 | + private SuggestScoreDocPriorityQueue(int size) { |
| 62 | + super(size); |
| 63 | + } |
| 64 | + |
| 65 | + @Override |
| 66 | + protected boolean lessThan(TopSuggestDocs.SuggestScoreDoc a, TopSuggestDocs.SuggestScoreDoc b) { |
| 67 | + if (a.score == b.score) { |
| 68 | + // tie break by completion key |
| 69 | + int cmp = Lookup.CHARSEQUENCE_COMPARATOR.compare(a.key, b.key); |
| 70 | + // prefer smaller doc id, in case of a tie |
| 71 | + return cmp != 0 ? cmp > 0 : a.doc > b.doc; |
| 72 | + } |
| 73 | + return a.score < b.score; |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Returns the top N results in descending order. |
| 78 | + */ |
| 79 | + public TopSuggestDocs.SuggestScoreDoc[] getResults() { |
| 80 | + int size = size(); |
| 81 | + TopSuggestDocs.SuggestScoreDoc[] res = new TopSuggestDocs.SuggestScoreDoc[size]; |
| 82 | + for (int i = size - 1; i >= 0; i--) { |
| 83 | + res[i] = pop(); |
| 84 | + } |
| 85 | + return res; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + |
| 90 | + private final SuggestScoreDocPriorityQueue priorityQueue; |
| 91 | + private final int num; |
| 92 | + |
| 93 | + /** Only set if we are deduplicating hits: holds all per-segment hits until the end, when we dedup them */ |
| 94 | + private final List<TopSuggestDocs.SuggestScoreDoc> pendingResults; |
| 95 | + |
| 96 | + /** Only set if we are deduplicating hits: holds all surface forms seen so far in the current segment */ |
| 97 | + final CharArraySet seenSurfaceForms; |
| 98 | + |
| 99 | + /** Document base offset for the current Leaf */ |
| 100 | + protected int docBase; |
| 101 | + |
| 102 | + private Map<Integer, List<CharSequence>> docContexts = new HashMap<>(); |
| 103 | + |
| 104 | + /** |
| 105 | + * Sole constructor |
| 106 | + * |
| 107 | + * Collects at most <code>num</code> completions |
| 108 | + * with corresponding document and weight |
| 109 | + */ |
| 110 | + TopSuggestGroupDocsCollector(int num, boolean skipDuplicates) { |
| 111 | + super(1, skipDuplicates); |
| 112 | + if (num <= 0) { |
| 113 | + throw new IllegalArgumentException("'num' must be > 0"); |
| 114 | + } |
| 115 | + this.num = num; |
| 116 | + this.priorityQueue = new SuggestScoreDocPriorityQueue(num); |
| 117 | + if (skipDuplicates) { |
| 118 | + seenSurfaceForms = new CharArraySet(num, false); |
| 119 | + pendingResults = new ArrayList<>(); |
| 120 | + } else { |
| 121 | + seenSurfaceForms = null; |
| 122 | + pendingResults = null; |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Returns the contexts associated with the provided <code>doc</code>. |
| 128 | + */ |
| 129 | + public List<CharSequence> getContexts(int doc) { |
| 130 | + return docContexts.getOrDefault(doc, Collections.emptyList()); |
| 131 | + } |
| 132 | + |
| 133 | + @Override |
| 134 | + protected boolean doSkipDuplicates() { |
| 135 | + return seenSurfaceForms != null; |
| 136 | + } |
| 137 | + |
| 138 | + @Override |
| 139 | + public int getCountToCollect() { |
| 140 | + return num; |
| 141 | + } |
| 142 | + |
| 143 | + @Override |
| 144 | + protected void doSetNextReader(LeafReaderContext context) throws IOException { |
| 145 | + docBase = context.docBase; |
| 146 | + if (seenSurfaceForms != null) { |
| 147 | + seenSurfaceForms.clear(); |
| 148 | + // NOTE: this also clears the priorityQueue: |
| 149 | + for (TopSuggestDocs.SuggestScoreDoc hit : priorityQueue.getResults()) { |
| 150 | + pendingResults.add(hit); |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + @Override |
| 156 | + public void collect(int docID, CharSequence key, CharSequence context, float score) throws IOException { |
| 157 | + int globalDoc = docID + docBase; |
| 158 | + boolean isDuplicate = docContexts.containsKey(globalDoc); |
| 159 | + List<CharSequence> contexts = docContexts.computeIfAbsent(globalDoc, k -> new ArrayList<>()); |
| 160 | + if (context != null) { |
| 161 | + contexts.add(context); |
| 162 | + } |
| 163 | + if (isDuplicate) { |
| 164 | + return; |
| 165 | + } |
| 166 | + TopSuggestDocs.SuggestScoreDoc current = new TopSuggestDocs.SuggestScoreDoc(globalDoc, key, context, score); |
| 167 | + if (current == priorityQueue.insertWithOverflow(current)) { |
| 168 | + // if the current SuggestScoreDoc has overflown from pq, |
| 169 | + // we can assume all of the successive collections from |
| 170 | + // this leaf will be overflown as well |
| 171 | + // TODO: reuse the overflow instance? |
| 172 | + throw new CollectionTerminatedException(); |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + @Override |
| 177 | + public TopSuggestDocs get() throws IOException { |
| 178 | + |
| 179 | + TopSuggestDocs.SuggestScoreDoc[] suggestScoreDocs; |
| 180 | + |
| 181 | + if (seenSurfaceForms != null) { |
| 182 | + // NOTE: this also clears the priorityQueue: |
| 183 | + for (TopSuggestDocs.SuggestScoreDoc hit : priorityQueue.getResults()) { |
| 184 | + pendingResults.add(hit); |
| 185 | + } |
| 186 | + |
| 187 | + // Deduplicate all hits: we already dedup'd efficiently within each segment by |
| 188 | + // truncating the FST top paths search, but across segments there may still be dups: |
| 189 | + seenSurfaceForms.clear(); |
| 190 | + |
| 191 | + // TODO: we could use a priority queue here to make cost O(N * log(num)) instead of O(N * log(N)), where N = O(num * |
| 192 | + // numSegments), but typically numSegments is smallish and num is smallish so this won't matter much in practice: |
| 193 | + |
| 194 | + Collections.sort(pendingResults, |
| 195 | + (a, b) -> { |
| 196 | + // sort by higher score |
| 197 | + int cmp = Float.compare(b.score, a.score); |
| 198 | + if (cmp == 0) { |
| 199 | + // tie break by completion key |
| 200 | + cmp = Lookup.CHARSEQUENCE_COMPARATOR.compare(a.key, b.key); |
| 201 | + if (cmp == 0) { |
| 202 | + // prefer smaller doc id, in case of a tie |
| 203 | + cmp = Integer.compare(a.doc, b.doc); |
| 204 | + } |
| 205 | + } |
| 206 | + return cmp; |
| 207 | + }); |
| 208 | + |
| 209 | + List<TopSuggestDocs.SuggestScoreDoc> hits = new ArrayList<>(); |
| 210 | + |
| 211 | + for (TopSuggestDocs.SuggestScoreDoc hit : pendingResults) { |
| 212 | + if (seenSurfaceForms.contains(hit.key) == false) { |
| 213 | + seenSurfaceForms.add(hit.key); |
| 214 | + hits.add(hit); |
| 215 | + if (hits.size() == num) { |
| 216 | + break; |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + suggestScoreDocs = hits.toArray(new TopSuggestDocs.SuggestScoreDoc[0]); |
| 221 | + } else { |
| 222 | + suggestScoreDocs = priorityQueue.getResults(); |
| 223 | + } |
| 224 | + |
| 225 | + if (suggestScoreDocs.length > 0) { |
| 226 | + return new TopSuggestDocs(new TotalHits(suggestScoreDocs.length, TotalHits.Relation.EQUAL_TO), suggestScoreDocs); |
| 227 | + } else { |
| 228 | + return TopSuggestDocs.EMPTY; |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | +} |
0 commit comments