jbellis commented on code in PR #2673:
URL: https://github.com/apache/cassandra/pull/2673#discussion_r1357119265


##########
src/java/org/apache/cassandra/index/sai/disk/v1/segment/VectorIndexSegmentSearcher.java:
##########
@@ -0,0 +1,288 @@
+/*
+ * 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.cassandra.index.sai.disk.v1.segment;
+
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import javax.annotation.Nullable;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.github.jbellis.jvector.util.Bits;
+import io.github.jbellis.jvector.util.SparseFixedBitSet;
+import org.agrona.collections.IntArrayList;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.db.marshal.VectorType;
+import org.apache.cassandra.dht.AbstractBounds;
+import org.apache.cassandra.index.sai.IndexContext;
+import org.apache.cassandra.index.sai.QueryContext;
+import org.apache.cassandra.index.sai.VectorQueryContext;
+import org.apache.cassandra.index.sai.disk.PrimaryKeyMap;
+import org.apache.cassandra.index.sai.disk.v1.PerColumnIndexFiles;
+import org.apache.cassandra.index.sai.disk.v1.postings.ReorderingPostingList;
+import org.apache.cassandra.index.sai.disk.v1.vector.DiskAnn;
+import org.apache.cassandra.index.sai.iterators.KeyRangeIterator;
+import org.apache.cassandra.index.sai.plan.Expression;
+import org.apache.cassandra.index.sai.postings.IntArrayPostingList;
+import org.apache.cassandra.index.sai.postings.PeekablePostingList;
+import org.apache.cassandra.index.sai.postings.PostingList;
+import org.apache.cassandra.index.sai.utils.RangeUtil;
+import org.apache.cassandra.index.sai.utils.TypeUtil;
+
+/**
+ * Executes ANN search against a vector graph for an individual index segment.
+ */
+public class VectorIndexSegmentSearcher extends IndexSegmentSearcher
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+    private final DiskAnn graph;
+    private final VectorType<float[]> type;
+    private final int maxBruteForceRows;
+    private final ThreadLocal<SparseFixedBitSet> cachedBitSets;
+
+    @SuppressWarnings("unchecked")
+    VectorIndexSegmentSearcher(PrimaryKeyMap.Factory primaryKeyMapFactory,
+                               PerColumnIndexFiles perIndexFiles,
+                               SegmentMetadata segmentMetadata,
+                               IndexContext indexContext) throws IOException
+    {
+        super(primaryKeyMapFactory, perIndexFiles, segmentMetadata, 
indexContext);
+        graph = new DiskAnn(segmentMetadata.componentMetadatas, perIndexFiles, 
indexContext);
+        type = (VectorType<float[]>) indexContext.getValidator();
+        cachedBitSets = ThreadLocal.withInitial(() -> new 
SparseFixedBitSet(graph.size()));
+
+        // estimate the number of comparisons that a search would require; use 
brute force if we have
+        // fewer rows involved than that
+        maxBruteForceRows = 
(int)(indexContext.getIndexWriterConfig().getMaximumNodeConnections() * 
Math.log(graph.size()));
+    }
+
+    @Override
+    public long indexFileCacheSize()
+    {
+        return graph.ramBytesUsed();
+    }
+
+    @Override
+    public PostingList search(Expression exp, 
AbstractBounds<PartitionPosition> keyRange, QueryContext context) throws 
IOException
+    {
+        return toRangePostingList(searchPosting(context.vectorContext(), exp, 
keyRange), context);
+    }
+
+    private PostingList searchPosting(VectorQueryContext context, Expression 
exp, AbstractBounds<PartitionPosition> keyRange) throws IOException
+    {
+        if (logger.isTraceEnabled())
+            logger.trace(indexContext.logMessage("Searching on expression 
'{}'..."), exp);
+
+        if (exp.getOp() != Expression.IndexOperator.ANN)
+            throw new 
IllegalArgumentException(indexContext.logMessage("Unsupported expression during 
ANN index query: " + exp));
+
+        BitsOrPostingList bitsOrPostingList = 
bitsOrPostingListForKeyRange(context, keyRange);
+        if (bitsOrPostingList.skipANN())
+            return bitsOrPostingList.postingList();
+
+        ByteBuffer buffer = exp.lower.value.raw;
+        float[] queryVector = TypeUtil.decomposeVector(indexContext, 
buffer.duplicate());
+        return graph.search(queryVector, context.limit(), 
bitsOrPostingList.getBits());
+    }
+
+    /**
+     * Return bit set we need to search the graph; otherwise return posting 
list to bypass the graph
+     */
+    private BitsOrPostingList bitsOrPostingListForKeyRange(VectorQueryContext 
context, AbstractBounds<PartitionPosition> keyRange) throws IOException
+    {
+        // create a bitset of ordinals corresponding to the rows in the given 
key range
+        SparseFixedBitSet bits = bitSetForSearch();
+        boolean hasMatches = false;
+
+        try (PrimaryKeyMap primaryKeyMap = 
primaryKeyMapFactory.newPerSSTablePrimaryKeyMap())
+        {
+            // not restricted
+            if (RangeUtil.coversFullRing(keyRange))
+                return new 
BitsOrPostingList(context.bitsetForShadowedPrimaryKeys(metadata, primaryKeyMap, 
graph));
+
+            // it will return the next row id if given key is not found.
+            long minSSTableRowId = primaryKeyMap.firstRowIdForRange(keyRange);
+            long maxSSTableRowId = primaryKeyMap.lastRowIdForRange(keyRange);
+
+            if (minSSTableRowId > maxSSTableRowId)
+                return new BitsOrPostingList(PostingList.EMPTY);
+
+            // if it covers entire segment, skip bit set
+            if (minSSTableRowId <= metadata.minSSTableRowId && maxSSTableRowId 
>= metadata.maxSSTableRowId)
+                return new 
BitsOrPostingList(context.bitsetForShadowedPrimaryKeys(metadata, primaryKeyMap, 
graph));
+
+            minSSTableRowId = Math.max(minSSTableRowId, 
metadata.minSSTableRowId);
+            maxSSTableRowId = Math.min(maxSSTableRowId, 
metadata.maxSSTableRowId);
+
+            // if num of matches are not bigger than limit, skip ANN
+            var nRows = maxSSTableRowId - minSSTableRowId + 1;

Review Comment:
   this is a bad estimate for nRows.  also fixed in vsearch



-- 
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