RKSPD commented on code in PR #16709:
URL: https://github.com/apache/lucene/pull/16709#discussion_r4637088784


##########
lucene/sandbox/src/java/org/apache/lucene/sandbox/codecs/segmentivf/SegmentIVFKnnQuery.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.sandbox.codecs.segmentivf;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.Callable;
+import org.apache.lucene.codecs.KnnVectorsReader;
+import org.apache.lucene.index.CodecReader;
+import org.apache.lucene.index.FilterLeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import 
org.apache.lucene.sandbox.codecs.segmentivf.SegmentIVFVectorsFormat.SearchStrategy;
+import 
org.apache.lucene.sandbox.codecs.segmentivf.SegmentIVFVectorsReader.Candidates;
+import org.apache.lucene.search.AcceptDocs;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BulkScorer;
+import org.apache.lucene.search.FieldExistsQuery;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.KnnFloatVectorQuery;
+import org.apache.lucene.search.LeafCollector;
+import org.apache.lucene.search.MatchNoDocsQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Scorable;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.TimeLimitingKnnCollectorManager;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.search.TopDocsCollector;
+import org.apache.lucene.search.TopKnnCollector;
+import org.apache.lucene.search.Weight;
+import org.apache.lucene.search.knn.KnnCollectorManager;
+import org.apache.lucene.util.BitSetIterator;
+import org.apache.lucene.util.FixedBitSet;
+
+/**
+ * A {@link KnnFloatVectorQuery} for SegmentIVF fields.
+ *
+ * <p>Every segment contributes its deduplicated coarse shortlist; these are 
merged into one
+ * index-wide shortlist of {@value SegmentIVFVectorsReader#RERANK_PER_K} 
candidates per requested
+ * neighbor (at least {@value SegmentIVFVectorsReader#MIN_RERANK}), and only 
those fine records are
+ * read and scored, so fine reads stay constant as the segment count grows. A 
dense filter reaches
+ * the codec as a per-segment bit set; a filter that rewrites to a single 
clause falls back to a
+ * plain {@link KnnFloatVectorQuery}, and segments with at most {@code k} 
matches are searched
+ * exactly.
+ *
+ * @lucene.experimental
+ */
+public final class SegmentIVFKnnQuery extends KnnFloatVectorQuery {
+  private final Query denseFilter;
+  private final Weight filterWeight;
+  private final Map<Integer, TopDocs> reranked;
+
+  /** Creates a query probing {@code numProbes} cells, with an optional 
(possibly null) filter. */
+  public SegmentIVFKnnQuery(String field, float[] target, int k, Query filter, 
int numProbes) {
+    this(field, target, k, filter, new SearchStrategy(numProbes));
+  }
+
+  /** Creates a query with an explicit probe strategy and an optional 
(possibly null) filter. */
+  public SegmentIVFKnnQuery(
+      String field, float[] target, int k, Query filter, SearchStrategy 
strategy) {
+    super(field, target, k, null, Objects.requireNonNull(strategy));
+    this.denseFilter = filter;
+    this.filterWeight = null;
+    this.reranked = null;
+  }
+
+  private SegmentIVFKnnQuery(
+      SegmentIVFKnnQuery query, Weight filterWeight, Map<Integer, TopDocs> 
reranked) {
+    super(query.field, query.target, query.k, null, query.searchStrategy);
+    this.denseFilter = query.denseFilter;
+    this.filterWeight = filterWeight;
+    this.reranked = reranked;
+  }
+
+  /** Intersects the filter with the field and pre-creates its weight for 
segment search. */
+  @Override
+  public Query rewrite(IndexSearcher searcher) throws IOException {
+    if (reranked != null || filterWeight != null) return 
super.rewrite(searcher);
+    Weight filter = null;
+    if (denseFilter != null) {
+      var both = new BooleanQuery.Builder();
+      both.add(denseFilter, Occur.FILTER).add(new FieldExistsQuery(field), 
Occur.FILTER);
+      Query rewritten = searcher.rewrite(both.build());
+      if (rewritten.getClass() == MatchNoDocsQuery.class) return rewritten;
+      filter = rewritten.createWeight(searcher, ScoreMode.COMPLETE_NO_SCORES, 
1f);
+    }
+    Map<Integer, TopDocs> global = globalRerank(searcher, filter);
+    if (global != null) return new SegmentIVFKnnQuery(this, null, 
global).rewrite(searcher);
+    // Some segment is not SegmentIVF: search every segment on its own.
+    return filter == null
+        ? super.rewrite(searcher)
+        : new SegmentIVFKnnQuery(this, filter, null).rewrite(searcher);
+  }
+
+  /** Returns a segment's share of the finished global rerank, when there is 
one. */
+  @Override
+  protected TopDocs searchLeaf(
+      LeafReaderContext context, Weight filter, 
TimeLimitingKnnCollectorManager manager)
+      throws IOException {
+    if (reranked == null) return super.searchLeaf(context, filter, manager);
+    return reranked.getOrDefault(context.ord, TopDocsCollector.EMPTY_TOPDOCS);
+  }
+
+  /**
+   * Merges every segment's coarse shortlist into one index-wide shortlist and 
fine-reranks only
+   * that, returning each segment's top hits with global doc IDs, or null when 
some segment is not
+   * searched by SegmentIVF.
+   */
+  private Map<Integer, TopDocs> globalRerank(IndexSearcher searcher, Weight 
filter)
+      throws IOException {
+    SearchStrategy strategy = (SearchStrategy) searchStrategy;
+    List<LeafReaderContext> leaves = new ArrayList<>();
+    List<SegmentIVFVectorsReader> readers = new ArrayList<>();
+    List<Callable<Candidates>> scans = new ArrayList<>();
+    for (LeafReaderContext context : searcher.getIndexReader().leaves()) {
+      if (context.reader().getFieldInfos().fieldInfo(field) == null) continue;
+      if (FilterLeafReader.unwrap(context.reader()) instanceof CodecReader 
codec
+          && codec.getVectorReader() instanceof KnnVectorsReader vectors
+          && vectors.unwrapReaderForField(field) instanceof 
SegmentIVFVectorsReader sivf) {
+        leaves.add(context);
+        readers.add(sivf);
+        scans.add(
+            () -> {
+              AcceptDocs accept = accepted(context, filter);
+              return accept == null
+                  ? Candidates.EMPTY
+                  : sivf.candidates(field, target, k, strategy, accept);
+            });
+      } else {
+        return null; // Some segment is not SegmentIVF.

Review Comment:
   I don't think this would happen in reality. There would be different formats 
across segments, but in the off chance they don't.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to