forked from opensearch-project/k-NN
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Heemin Kim <[email protected]>
- Loading branch information
Showing
3 changed files
with
209 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 24 additions & 0 deletions
24
src/main/java/org/opensearch/knn/index/query/nativelib/LuceneEngineExactVectorQuery.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/* | ||
* Copyright OpenSearch Contributors | ||
* SPDX-License-Identifier: Apache-2.0 | ||
*/ | ||
|
||
package org.opensearch.knn.index.query.nativelib; | ||
|
||
import org.apache.lucene.index.LeafReaderContext; | ||
import org.apache.lucene.index.QueryTimeout; | ||
import org.apache.lucene.search.DocIdSetIterator; | ||
import org.apache.lucene.search.KnnFloatVectorQuery; | ||
import org.apache.lucene.search.TopDocs; | ||
|
||
import java.io.IOException; | ||
|
||
public class LuceneEngineExactVectorQuery extends KnnFloatVectorQuery { | ||
public LuceneEngineExactVectorQuery(final String field, final float[] target, final int k) { | ||
super(field, target, k); | ||
} | ||
|
||
public TopDocs exactSearch(LeafReaderContext context, DocIdSetIterator acceptIterator, QueryTimeout queryTimeout) throws IOException { | ||
return super.exactSearch(context, acceptIterator, queryTimeout); | ||
} | ||
} |
181 changes: 181 additions & 0 deletions
181
src/main/java/org/opensearch/knn/index/query/nativelib/LuceneEngineKNNVectorQuery.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
/* | ||
* Copyright OpenSearch Contributors | ||
* SPDX-License-Identifier: Apache-2.0 | ||
*/ | ||
|
||
package org.opensearch.knn.index.query.nativelib; | ||
|
||
import lombok.AllArgsConstructor; | ||
import org.apache.lucene.index.IndexReader; | ||
import org.apache.lucene.index.LeafReaderContext; | ||
import org.apache.lucene.search.DocIdSetIterator; | ||
import org.apache.lucene.search.IndexSearcher; | ||
import org.apache.lucene.search.MatchNoDocsQuery; | ||
import org.apache.lucene.search.Query; | ||
import org.apache.lucene.search.QueryVisitor; | ||
import org.apache.lucene.search.ScoreMode; | ||
import org.apache.lucene.search.Scorer; | ||
import org.apache.lucene.search.TopDocs; | ||
import org.apache.lucene.search.Weight; | ||
import org.apache.lucene.search.join.BitSetProducer; | ||
import org.apache.lucene.util.BitSet; | ||
import org.apache.lucene.util.DocIdSetBuilder; | ||
import org.opensearch.knn.index.query.KNNQuery; | ||
import org.opensearch.knn.index.query.ResultUtil; | ||
|
||
import java.io.IOException; | ||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.Collections; | ||
import java.util.Comparator; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.concurrent.Callable; | ||
|
||
@AllArgsConstructor | ||
public class LuceneEngineKNNVectorQuery extends Query { | ||
private Query luceneQuery; | ||
private int k; | ||
final BitSetProducer parentFilter; | ||
|
||
@Override | ||
public Weight createWeight(IndexSearcher indexSearcher, ScoreMode scoreMode, float boost) throws IOException { | ||
final IndexReader reader = indexSearcher.getIndexReader(); | ||
Query docAndScoreQuery = indexSearcher.rewrite(luceneQuery); | ||
Weight weight = docAndScoreQuery.createWeight(indexSearcher, scoreMode, boost); | ||
List<LeafReaderContext> leafReaderContexts = reader.leaves(); | ||
List<Map<Integer, Float>> perLeafResults; | ||
perLeafResults = doSearch(indexSearcher, leafReaderContexts, weight, k); | ||
ResultUtil.reduceToTopK(perLeafResults, k); | ||
TopDocs[] topDocs = retrieveAll(indexSearcher, leafReaderContexts, weight, perLeafResults); | ||
long sum = 0; | ||
for (TopDocs topDoc : topDocs) { | ||
sum += topDoc.totalHits.value; | ||
} | ||
TopDocs topK = TopDocs.merge((int)sum, topDocs); | ||
if (topK.scoreDocs.length == 0) { | ||
return new MatchNoDocsQuery().createWeight(indexSearcher, scoreMode, boost); | ||
} | ||
|
||
return createDocAndScoreQuery(reader, topK).createWeight(indexSearcher, scoreMode, boost); | ||
} | ||
|
||
private TopDocs[] retrieveAll(final IndexSearcher indexSearcher, final List<LeafReaderContext> leafReaderContexts, final Weight weight, final List<Map<Integer, Float>> perLeafResults) throws IOException { | ||
// Construct query | ||
KNNQuery knnQuery = new KNNQuery("nested_field.my_vector", new float[]{3, 3, 3}, 1000,"my-knn-index-1",null); | ||
List<Callable<TopDocs>> rescoreTasks = new ArrayList<>(leafReaderContexts.size()); | ||
for (int i = 0; i < perLeafResults.size(); i++) { | ||
LeafReaderContext leafReaderContext = leafReaderContexts.get(i); | ||
int finalI = i; | ||
rescoreTasks.add(() -> { | ||
// Here, it should be bitset of parent doc id. | ||
DocIdSetIterator iterator = getAllSiblings(leafReaderContext, perLeafResults.get(finalI)); | ||
LuceneEngineExactVectorQuery exactVectorQuery = new LuceneEngineExactVectorQuery("nested_field.my_vector", new float[] {3, 3, 3}, 1000); | ||
return exactVectorQuery.exactSearch(leafReaderContext, iterator, null); | ||
}); | ||
} | ||
return indexSearcher.getTaskExecutor().invokeAll(rescoreTasks).toArray(TopDocs[]::new); | ||
} | ||
|
||
private DocIdSetIterator getAllSiblings(final LeafReaderContext leafReaderContext, final Map<Integer, Float> integerFloatMap) throws IOException { | ||
if (integerFloatMap.isEmpty()) { | ||
return DocIdSetIterator.empty(); | ||
} | ||
final int maxDoc = Collections.max(integerFloatMap.keySet()); | ||
BitSet parentBitSet = parentFilter.getBitSet(leafReaderContext); | ||
final int maxParentDoc = parentBitSet.nextSetBit(maxDoc) + 1; | ||
return resultMapToDocIds(leafReaderContext, integerFloatMap, maxParentDoc); | ||
} | ||
|
||
public DocIdSetIterator resultMapToDocIds(final LeafReaderContext leafReaderContext, Map<Integer, Float> resultMap, final int maxDoc) throws IOException { | ||
if (resultMap.isEmpty()) { | ||
return DocIdSetIterator.empty(); | ||
} | ||
final DocIdSetBuilder docIdSetBuilder = new DocIdSetBuilder(maxDoc); | ||
final DocIdSetBuilder.BulkAdder setAdder = docIdSetBuilder.grow(maxDoc - resultMap.size()); | ||
BitSet parentBitSet = parentFilter.getBitSet(leafReaderContext); | ||
resultMap.keySet().forEach(key -> { | ||
for (int i = parentBitSet.prevSetBit(key) + 1; i < parentBitSet.nextSetBit(key); i++) { | ||
setAdder.add(i); | ||
} | ||
}); | ||
return docIdSetBuilder.build().iterator(); | ||
} | ||
|
||
private Query createDocAndScoreQuery(IndexReader reader, TopDocs topK) { | ||
int len = topK.scoreDocs.length; | ||
Arrays.sort(topK.scoreDocs, Comparator.comparingInt(a -> a.doc)); | ||
int[] docs = new int[len]; | ||
float[] scores = new float[len]; | ||
for (int i = 0; i < len; i++) { | ||
docs[i] = topK.scoreDocs[i].doc; | ||
scores[i] = topK.scoreDocs[i].score; | ||
} | ||
int[] segmentStarts = findSegmentStarts(reader, docs); | ||
return new DocAndScoreQuery(k, docs, scores, segmentStarts, reader.getContext().id()); | ||
} | ||
|
||
private List<Map<Integer, Float>> doSearch( | ||
final IndexSearcher indexSearcher, | ||
List<LeafReaderContext> leafReaderContexts, | ||
Weight weight, | ||
int k | ||
) throws IOException { | ||
List<Callable<Map<Integer, Float>>> tasks = new ArrayList<>(leafReaderContexts.size()); | ||
for (LeafReaderContext leafReaderContext : leafReaderContexts) { | ||
tasks.add(() -> searchLeaf(leafReaderContext, weight, k)); | ||
} | ||
return indexSearcher.getTaskExecutor().invokeAll(tasks); | ||
} | ||
|
||
static int[] findSegmentStarts(IndexReader reader, int[] docs) { | ||
int[] starts = new int[reader.leaves().size() + 1]; | ||
starts[starts.length - 1] = docs.length; | ||
if (starts.length == 2) { | ||
return starts; | ||
} | ||
int resultIndex = 0; | ||
for (int i = 1; i < starts.length - 1; i++) { | ||
int upper = reader.leaves().get(i).docBase; | ||
resultIndex = Arrays.binarySearch(docs, resultIndex, docs.length, upper); | ||
if (resultIndex < 0) { | ||
resultIndex = -1 - resultIndex; | ||
} | ||
starts[i] = resultIndex; | ||
} | ||
return starts; | ||
} | ||
|
||
private Map<Integer, Float> searchLeaf(LeafReaderContext ctx, Weight weight, int k) throws IOException { | ||
final Map<Integer, Float> leafDocScores = new HashMap<>(); | ||
Scorer scorer = weight.scorer(ctx); | ||
DocIdSetIterator iterator = scorer.iterator(); | ||
iterator.nextDoc(); | ||
while (iterator.docID() != DocIdSetIterator.NO_MORE_DOCS) { | ||
leafDocScores.put(scorer.docID(), scorer.score()); | ||
iterator.nextDoc(); | ||
} | ||
return leafDocScores; | ||
} | ||
|
||
@Override | ||
public String toString(final String s) { | ||
return ""; | ||
} | ||
|
||
@Override | ||
public void visit(final QueryVisitor queryVisitor) { | ||
|
||
} | ||
|
||
@Override | ||
public boolean equals(final Object o) { | ||
return false; | ||
} | ||
|
||
@Override | ||
public int hashCode() { | ||
return 0; | ||
} | ||
} |