This is an automated email from the ASF dual-hosted git repository.
xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new 1b1094b34f5 Serve cosineDistance from the HNSW search when paired with
VECTOR_SIMILARITY (#20073)
1b1094b34f5 is described below
commit 1b1094b34f5e9d86d5f808ad813673fafa09c9fd
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Sat Nov 21 19:56:20 2026 -0800
Serve cosineDistance from the HNSW search when paired with
VECTOR_SIMILARITY (#20073)
* Add VECTOR_DISTANCE transform that reads distances from the HNSW search
* Test VECTOR_DISTANCE against cosineDistance and the distances the HNSW
index serves
* Accept integer vector literals in VECTOR_DISTANCE, as VECTOR_SIMILARITY
does
* Scope VECTOR_DISTANCE to the query and follow the column's distance
function
The HNSW reader no longer keeps a segment-lifetime cache of recent search
distances. getDocDistances is now a stateless search that returns the same
top-k documents as getDocIds with their distances. VECTOR_DISTANCE requests
the distances of its column and vector in the query's VectorSearchDistances
while the query is planned, and the VECTOR_SIMILARITY filter fills the
request from its own search. Nothing outlives the query, and queries that do
not project VECTOR_DISTANCE collect no distances.
VECTOR_DISTANCE now returns the distance under the column's configured
distance function, the same distance VECTOR_SIMILARITY ranks by and
vectorDistanceThreshold applies to. The index returns distances only for
COSINE; other functions are computed from the forward index.
* Test VECTOR_DISTANCE with VECTOR_SIMILARITY on both query engines
* Drop the unused k argument from VECTOR_DISTANCE
The distances come from the paired VECTOR_SIMILARITY search whatever its k,
so VECTOR_DISTANCE takes only the column
and the query vector.
* Serve cosineDistance from the vector index search instead of adding
VECTOR_DISTANCE
cosineDistance(column, ARRAY[...]) on a column with a COSINE vector index
now takes
the distances the paired VECTOR_SIMILARITY search computed, through the
query's
VectorSearchDistances, instead of re-reading the matched rows' vectors from
the
forward index. The VECTOR_DISTANCE function is removed, so no new SQL
function is
added. Rows the search did not return fall back to the forward index.
* Add vectorExactDistance query option to keep cosineDistance on the exact
path
With vectorExactDistance=true, cosineDistance does not take distances from
a paired
VECTOR_SIMILARITY search and computes them from the forward index, for
queries that
need exact parity with the unindexed result.
* Serve cosine distances only from a COSINE index and fall back on
non-finite ones
* Do not hand over index distances when exact rerank or a threshold selects
rows
Exact rerank and the distance threshold select rows by the exact
forward-index
distance, but cosineDistance projected the index's approximate score, so the
projected and sorted value could differ from the one that selected the row.
Skip the handoff in those modes; the projection computes the exact distance.
* Preserve scalar cosine semantics unless approximate scores are requested
---------
Co-authored-by: Xiang Fu <[email protected]>
---
.../common/utils/config/QueryOptionsUtils.java | 5 +
.../operator/filter/VectorSearchDistances.java | 109 ++++++++
.../filter/VectorSimilarityFilterOperator.java | 41 ++-
.../function/ArrayLiteralTransformFunction.java | 71 +++---
.../function/VectorTransformFunctions.java | 90 +++++++
.../org/apache/pinot/core/plan/FilterPlanNode.java | 9 +-
.../filter/VectorSimilarityFilterOperatorTest.java | 116 +++++++++
.../CosineDistanceIndexTransformFunctionTest.java | 282 +++++++++++++++++++++
.../pinot/integration/tests/custom/VectorTest.java | 28 +-
.../readers/vector/HnswVectorIndexReader.java | 60 +++++
.../index/creator/HnswVectorIndexCreatorTest.java | 109 ++++++++
.../index/reader/FilterAwareVectorIndexReader.java | 14 +
.../spi/index/reader/VectorIndexReader.java | 10 +
.../apache/pinot/spi/utils/CommonConstants.java | 4 +
14 files changed, 910 insertions(+), 38 deletions(-)
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
index 5ca41c0810e..3a4ab0cb61f 100644
---
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
+++
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/QueryOptionsUtils.java
@@ -1056,6 +1056,11 @@ public class QueryOptionsUtils {
return
Boolean.parseBoolean(queryOptions.get(QueryOptionKey.VECTOR_EXACT_RERANK));
}
+ /// Returns whether `cosineDistance` may reuse approximate distances from a
paired vector index search.
+ public static boolean isVectorApproximateDistance(Map<String, String>
queryOptions) {
+ return
Boolean.parseBoolean(queryOptions.get(QueryOptionKey.VECTOR_APPROXIMATE_DISTANCE));
+ }
+
@Nullable
public static Boolean getVectorExactRerank(Map<String, String> queryOptions)
{
String exactRerank = queryOptions.get(QueryOptionKey.VECTOR_EXACT_RERANK);
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSearchDistances.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSearchDistances.java
new file mode 100644
index 00000000000..83055d8e930
--- /dev/null
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSearchDistances.java
@@ -0,0 +1,109 @@
+/**
+ * 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.pinot.core.operator.filter;
+
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
+import java.util.Arrays;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.utils.config.QueryOptionsUtils;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.index.reader.VectorIndexReader;
+
+
+/// Hands the distances computed by a vector index search from
[VectorSimilarityFilterOperator] to `cosineDistance`
+/// on the same segment, column and query vector, so the projection does not
recompute them from the forward index.
+///
+/// One instance lives in the [QueryContext] of each query, so the distances
are released with the query and never
+/// shared across queries. `cosineDistance` requests distances while the query
is planned; the filter fills a request
+/// only when one exists, so queries that do not project it collect nothing.
+public final class VectorSearchDistances {
+ private final ConcurrentHashMap<Key, Request> _requests = new
ConcurrentHashMap<>();
+
+ /// A query with a row-level security filter always uses scalar distances.
Its policy and user filters are
+ /// evaluated independently and must not share search results.
+ public static boolean isEnabled(QueryContext queryContext) {
+ return queryContext.getRowFilter() == null &&
QueryOptionsUtils.isVectorApproximateDistance(
+ queryContext.getQueryOptions());
+ }
+
+ /// Returns the instance of the given query.
+ public static VectorSearchDistances of(QueryContext queryContext) {
+ return queryContext.getOrComputeSharedValue(VectorSearchDistances.class,
VectorSearchDistances.class,
+ k -> new VectorSearchDistances());
+ }
+
+ /// Requests the distances of the next search of `reader` for `vector`.
Called while the query is planned.
+ public Request request(VectorIndexReader reader, float[] vector) {
+ return _requests.computeIfAbsent(new Key(reader, vector), k -> new
Request());
+ }
+
+ /// Returns the request for the distances of a search of `reader` for
`vector`, or `null` when none was made.
+ @Nullable
+ public Request getRequest(VectorIndexReader reader, float[] vector) {
+ return _requests.get(new Key(reader, vector));
+ }
+
+ /// Distances of one search, keyed by doc id. The filter sets them before
the projection reads them, both on the
+ /// thread that processes the segment.
+ public static final class Request {
+ @Nullable
+ private volatile Int2FloatMap _distances;
+
+ public void setDistances(Int2FloatMap distances) {
+ _distances = distances;
+ }
+
+ /// Returns the distances of the search, or `null` when the search has not
run or the index returned none.
+ @Nullable
+ public Int2FloatMap getDistances() {
+ return _distances;
+ }
+ }
+
+ /// Identifies a search by the reader instance (one per segment and column)
and the query vector.
+ private static final class Key {
+ private final VectorIndexReader _reader;
+ private final float[] _vector;
+ private final int _hashCode;
+
+ Key(VectorIndexReader reader, float[] vector) {
+ _reader = reader;
+ _vector = vector;
+ _hashCode = 31 * System.identityHashCode(reader) +
Arrays.hashCode(vector);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof Key)) {
+ return false;
+ }
+ Key key = (Key) o;
+ return _reader == key._reader && Arrays.equals(_vector, key._vector);
+ }
+
+ @Override
+ public int hashCode() {
+ return _hashCode;
+ }
+ }
+}
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperator.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperator.java
index 07f12a1bccc..c9698a76629 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperator.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperator.java
@@ -20,6 +20,8 @@ package org.apache.pinot.core.operator.filter;
import com.google.common.base.CaseFormat;
import com.google.common.base.Preconditions;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
+import it.unimi.dsi.fastutil.ints.IntIterator;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -106,6 +108,8 @@ public class VectorSimilarityFilterOperator extends
BaseFilterOperator {
private volatile ImmutableRoaringBitmap _effectiveAllowedDocIds;
private volatile VectorSearchMode _vectorSearchMode;
private volatile boolean _candidateGenerationSkipped;
+ @Nullable
+ private VectorSearchDistances _searchDistances;
/// Backward-compatible constructor that uses default search params and no
forward index.
/// Existing callers that do not pass query options continue to work
unchanged.
@@ -220,6 +224,14 @@ public class VectorSimilarityFilterOperator extends
BaseFilterOperator {
refreshExplainContext();
}
+ /// Sets the query's [VectorSearchDistances]. When a projection has
requested the distances of this search, the
+ /// operator asks the index for them and hands them over instead of only
collecting the matching doc ids.
+ ///
+ /// This method must be called before any search execution (getTrues,
getBitmaps, etc.).
+ public void setSearchDistances(@Nullable VectorSearchDistances
searchDistances) {
+ _searchDistances = searchDistances;
+ }
+
@Override
protected BlockDocIdSet getTrues() {
if (_matches == null) {
@@ -385,17 +397,33 @@ public class VectorSimilarityFilterOperator extends
BaseFilterOperator {
// 3. Execute ANN search (with pre-filter if available)
ImmutableRoaringBitmap preFilter = effectiveAllowedDocIds;
ImmutableRoaringBitmap annResults;
+ // A cosineDistance projection on this search asked for its distances:
get them along with the doc ids. Not with
+ // exact rerank or a distance threshold, which select rows by the exact
distance: the projection computes that.
+ boolean exactRefinement = explainContext.isEffectiveExactRerank() ||
_hasThresholdPredicate;
+ VectorSearchDistances.Request distancesRequest = _searchDistances !=
null && !exactRefinement
+ ? _searchDistances.getRequest(_vectorIndexReader, queryVector) :
null;
+ Int2FloatMap distances = null;
searchExecuted = true;
if (preFilter != null && _readerSupportsPreFilter) {
FilterAwareVectorIndexReader filterAwareReader =
(FilterAwareVectorIndexReader) _vectorIndexReader;
_vectorSearchMode = VectorSearchMode.FILTER_THEN_ANN;
- annResults = filterAwareReader.getDocIds(queryVector, searchCount,
preFilter);
+ if (distancesRequest != null) {
+ distances = filterAwareReader.getCosineDistances(queryVector,
searchCount, preFilter);
+ }
+ annResults = distances != null ? toBitmap(distances)
+ : filterAwareReader.getDocIds(queryVector, searchCount, preFilter);
LOGGER.debug("Pre-filter ANN search on column: {}, filterCardinality:
{}, filterSelectivity: {}",
column, preFilter.getCardinality(),
_numDocs > 0 ? (double) preFilter.getCardinality() / _numDocs :
0.0);
} else {
_vectorSearchMode = VectorSearchMode.POST_FILTER_ANN;
- annResults = _vectorIndexReader.getDocIds(queryVector, searchCount);
+ if (distancesRequest != null) {
+ distances = _vectorIndexReader.getCosineDistances(queryVector,
searchCount);
+ }
+ annResults = distances != null ? toBitmap(distances) :
_vectorIndexReader.getDocIds(queryVector, searchCount);
+ }
+ if (distances != null) {
+ distancesRequest.setDistances(distances);
}
int annCandidateCount = annResults.getCardinality();
_annCandidateCount = annCandidateCount;
@@ -575,6 +603,15 @@ public class VectorSimilarityFilterOperator extends
BaseFilterOperator {
}
+ private static MutableRoaringBitmap toBitmap(Int2FloatMap distances) {
+ MutableRoaringBitmap docIds = new MutableRoaringBitmap();
+ IntIterator iterator = distances.keySet().iterator();
+ while (iterator.hasNext()) {
+ docIds.add(iterator.nextInt());
+ }
+ return docIds;
+ }
+
/// Returns a human-readable name for the backend (for logging).
private String getBackendName() {
return _backendType.name();
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ArrayLiteralTransformFunction.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ArrayLiteralTransformFunction.java
index 7b9d7d2b8b4..a0ba5852567 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ArrayLiteralTransformFunction.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ArrayLiteralTransformFunction.java
@@ -404,44 +404,49 @@ public class ArrayLiteralTransformFunction implements
TransformFunction {
float[][] floatArrayResult = _floatArrayResult;
if (floatArrayResult == null || floatArrayResult.length < numDocs) {
floatArrayResult = new float[numDocs][];
- float[] floatArrayLiteral = _floatArrayLiteral;
- if (floatArrayLiteral == null) {
- switch (_dataType) {
- case BOOLEAN:
- case INT:
- floatArrayLiteral = new float[_intArrayLiteral.length];
- for (int i = 0; i < _intArrayLiteral.length; i++) {
- floatArrayLiteral[i] = _intArrayLiteral[i];
- }
- break;
- case LONG:
- floatArrayLiteral = new float[_longArrayLiteral.length];
- for (int i = 0; i < _longArrayLiteral.length; i++) {
- floatArrayLiteral[i] = _longArrayLiteral[i];
- }
- break;
- case DOUBLE:
- floatArrayLiteral = new float[_doubleArrayLiteral.length];
- for (int i = 0; i < _doubleArrayLiteral.length; i++) {
- floatArrayLiteral[i] = (float) _doubleArrayLiteral[i];
- }
- break;
- case STRING:
- floatArrayLiteral = new float[_stringArrayLiteral.length];
- for (int i = 0; i < _stringArrayLiteral.length; i++) {
- floatArrayLiteral[i] = Float.parseFloat(_stringArrayLiteral[i]);
- }
- break;
- default:
- throw new IllegalStateException("Unable to convert data type: " +
_dataType + " to float array");
- }
- }
- Arrays.fill(floatArrayResult, floatArrayLiteral);
+ Arrays.fill(floatArrayResult, getFloatArrayValue());
_floatArrayResult = floatArrayResult;
}
return floatArrayResult;
}
+ /// Returns the literal with the same float conversion used by the
multi-value transform.
+ float[] getFloatArrayValue() {
+ float[] floatArrayLiteral = _floatArrayLiteral;
+ if (floatArrayLiteral == null) {
+ switch (_dataType) {
+ case BOOLEAN:
+ case INT:
+ floatArrayLiteral = new float[_intArrayLiteral.length];
+ for (int i = 0; i < _intArrayLiteral.length; i++) {
+ floatArrayLiteral[i] = _intArrayLiteral[i];
+ }
+ break;
+ case LONG:
+ floatArrayLiteral = new float[_longArrayLiteral.length];
+ for (int i = 0; i < _longArrayLiteral.length; i++) {
+ floatArrayLiteral[i] = _longArrayLiteral[i];
+ }
+ break;
+ case DOUBLE:
+ floatArrayLiteral = new float[_doubleArrayLiteral.length];
+ for (int i = 0; i < _doubleArrayLiteral.length; i++) {
+ floatArrayLiteral[i] = (float) _doubleArrayLiteral[i];
+ }
+ break;
+ case STRING:
+ floatArrayLiteral = new float[_stringArrayLiteral.length];
+ for (int i = 0; i < _stringArrayLiteral.length; i++) {
+ floatArrayLiteral[i] = Float.parseFloat(_stringArrayLiteral[i]);
+ }
+ break;
+ default:
+ throw new IllegalStateException("Unable to convert data type: " +
_dataType + " to float array");
+ }
+ }
+ return floatArrayLiteral;
+ }
+
@Override
public double[][] transformToDoubleValuesMV(ValueBlock valueBlock) {
int numDocs = valueBlock.getNumDocs();
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/VectorTransformFunctions.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/VectorTransformFunctions.java
index d5d7508b0cd..cd5ce2ccb4d 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/VectorTransformFunctions.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/VectorTransformFunctions.java
@@ -19,18 +19,33 @@
package org.apache.pinot.core.operator.transform.function;
import com.google.common.base.Preconditions;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
import java.util.List;
import java.util.Map;
+import javax.annotation.Nullable;
import org.apache.pinot.common.function.scalar.VectorFunctions;
import org.apache.pinot.core.operator.ColumnContext;
import org.apache.pinot.core.operator.blocks.ValueBlock;
+import org.apache.pinot.core.operator.filter.VectorSearchDistances;
import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.datasource.DataSource;
+import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
+import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig;
+import org.apache.pinot.segment.spi.index.reader.VectorIndexReader;
public class VectorTransformFunctions {
+ /// Implements `cosineDistance(left, right[, defaultValue])`.
+ ///
+ /// With `vectorApproximateDistance=true`, a paired `VECTOR_SIMILARITY`
search on the same column and vector
+ /// can supply approximate COSINE distances. The index scores can change
both the values and their ordering.
+ /// Documents with missing or non-finite distances use the scalar
computation from the forward index.
public static class CosineDistanceTransformFunction extends
VectorDistanceTransformFunction {
public static final String FUNCTION_NAME = "cosineDistance";
private Double _defaultValue = null;
+ @Nullable
+ private VectorSearchDistances.Request _distancesRequest;
@Override
protected void checkArgumentSize(List<TransformFunction> arguments) {
@@ -48,11 +63,86 @@ public class VectorTransformFunctions {
}
}
+ @Override
+ public void init(List<TransformFunction> arguments, Map<String,
ColumnContext> columnContextMap,
+ QueryContext queryContext) {
+ super.init(arguments, columnContextMap, queryContext);
+ if (_leftTransformFunction instanceof IdentifierTransformFunction
+ && _rightTransformFunction instanceof ArrayLiteralTransformFunction)
{
+ _distancesRequest =
requestIndexDistances((IdentifierTransformFunction) _leftTransformFunction,
+ (ArrayLiteralTransformFunction) _rightTransformFunction,
columnContextMap, queryContext);
+ } else if (_rightTransformFunction instanceof IdentifierTransformFunction
+ && _leftTransformFunction instanceof ArrayLiteralTransformFunction) {
+ _distancesRequest =
requestIndexDistances((IdentifierTransformFunction) _rightTransformFunction,
+ (ArrayLiteralTransformFunction) _leftTransformFunction,
columnContextMap, queryContext);
+ }
+ }
+
+ /// Asks a `VECTOR_SIMILARITY` filter on the column and vector to hand
over the distances of its search, when the
+ /// column has a COSINE vector index (whose distances are cosine
distances).
+ @Nullable
+ private static VectorSearchDistances.Request
requestIndexDistances(IdentifierTransformFunction column,
+ ArrayLiteralTransformFunction vector, Map<String, ColumnContext>
columnContextMap, QueryContext queryContext) {
+ if (!VectorSearchDistances.isEnabled(queryContext)) {
+ return null;
+ }
+ ColumnContext columnContext =
columnContextMap.get(column.getColumnName());
+ DataSource dataSource = columnContext != null ?
columnContext.getDataSource() : null;
+ if (dataSource == null) {
+ return null;
+ }
+ VectorIndexReader vectorIndexReader = dataSource.getVectorIndex();
+ VectorIndexConfig vectorIndexConfig = dataSource.getVectorIndexConfig();
+ if (vectorIndexReader == null || vectorIndexConfig == null
+ || vectorIndexConfig.getVectorDistanceFunction() !=
VectorIndexConfig.VectorDistanceFunction.COSINE) {
+ return null;
+ }
+ if (!vector.getResultMetadata().getDataType().isNumeric()) {
+ return null;
+ }
+ float[] queryVector = vector.getFloatArrayValue();
+ DataSourceMetadata metadata = dataSource.getDataSourceMetadata();
+ // HNSW ingestion can zero-pad a short row. Only reuse scores when every
forward-index row has the query width,
+ // so a cached score cannot hide the scalar function's dimension check.
+ if (metadata.getMaxNumValuesPerMVEntry() != queryVector.length
+ || metadata.getNumValues() != (long) metadata.getNumDocs() *
queryVector.length) {
+ return null;
+ }
+ return VectorSearchDistances.of(queryContext).request(vectorIndexReader,
queryVector);
+ }
+
@Override
public String getName() {
return FUNCTION_NAME;
}
+ @Override
+ public double[] transformToDoubleValuesSV(ValueBlock valueBlock) {
+ Int2FloatMap distances = _distancesRequest != null ?
_distancesRequest.getDistances() : null;
+ int[] docIds = distances != null ? valueBlock.getDocIds() : null;
+ if (docIds == null) {
+ return super.transformToDoubleValuesSV(valueBlock);
+ }
+ int length = valueBlock.getNumDocs();
+ initDoubleValuesSV(length);
+ float[][] leftValues = null;
+ float[][] rightValues = null;
+ for (int i = 0; i < length; i++) {
+ float distance = distances.getOrDefault(docIds[i], Float.NaN);
+ if (Float.isFinite(distance)) {
+ _doubleValuesSV[i] = distance;
+ } else {
+ // Fetch the vectors on the first miss. Other hits in this block
still use their index scores.
+ if (leftValues == null) {
+ leftValues =
_leftTransformFunction.transformToFloatValuesMV(valueBlock);
+ rightValues =
_rightTransformFunction.transformToFloatValuesMV(valueBlock);
+ }
+ _doubleValuesSV[i] = computeDistance(leftValues[i], rightValues[i]);
+ }
+ }
+ return _doubleValuesSV;
+ }
+
@Override
protected double computeDistance(float[] vector1, float[] vector2) {
if (_defaultValue != null) {
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/plan/FilterPlanNode.java
b/pinot-core/src/main/java/org/apache/pinot/core/plan/FilterPlanNode.java
index 48233c4549a..44a28be0045 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/plan/FilterPlanNode.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/plan/FilterPlanNode.java
@@ -50,6 +50,7 @@ import
org.apache.pinot.core.operator.filter.RowLevelSecurityFilterOperator;
import org.apache.pinot.core.operator.filter.TextMatchFilterOperator;
import org.apache.pinot.core.operator.filter.VectorDistanceUtils;
import org.apache.pinot.core.operator.filter.VectorRadiusFilterOperator;
+import org.apache.pinot.core.operator.filter.VectorSearchDistances;
import org.apache.pinot.core.operator.filter.VectorSearchMode;
import org.apache.pinot.core.operator.filter.VectorSearchParams;
import org.apache.pinot.core.operator.filter.VectorSearchStrategy;
@@ -475,8 +476,12 @@ public class FilterPlanNode implements PlanNode {
"Cannot apply vectorDistanceThreshold on column: %s -- forward
index required for threshold refinement",
column);
}
- return new VectorSimilarityFilterOperator(vectorIndex, predicate,
numDocs, searchParams, forwardIndexReader,
- vectorIndexConfig, hasMetadataFilter, _requiredVectorDocIds);
+ VectorSimilarityFilterOperator operator = new
VectorSimilarityFilterOperator(vectorIndex, predicate, numDocs,
+ searchParams, forwardIndexReader, vectorIndexConfig,
hasMetadataFilter, _requiredVectorDocIds);
+ if (VectorSearchDistances.isEnabled(_queryContext)) {
+ operator.setSearchDistances(VectorSearchDistances.of(_queryContext));
+ }
+ return operator;
}
// Exact scan fallback: no vector index on this segment
diff --git
a/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperatorTest.java
b/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperatorTest.java
index 357d7d4a764..cba4f5ff7d6 100644
---
a/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperatorTest.java
+++
b/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperatorTest.java
@@ -18,11 +18,14 @@
*/
package org.apache.pinot.core.operator.filter;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
+import it.unimi.dsi.fastutil.ints.Int2FloatOpenHashMap;
import java.util.Map;
import org.apache.pinot.common.request.context.ExpressionContext;
import
org.apache.pinot.common.request.context.predicate.VectorSimilarityPredicate;
import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig;
import org.apache.pinot.segment.spi.index.reader.EfSearchAware;
+import org.apache.pinot.segment.spi.index.reader.FilterAwareVectorIndexReader;
import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext;
import org.apache.pinot.segment.spi.index.reader.NprobeAware;
@@ -34,6 +37,8 @@ import org.roaringbitmap.buffer.MutableRoaringBitmap;
import org.testng.Assert;
import org.testng.annotations.Test;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -629,4 +634,115 @@ public class VectorSimilarityFilterOperatorTest {
return new VectorIndexConfig(false, backendType, 2, 1, distanceFunction,
Map.of("nlist", "4", "pqM", "2", "pqNbits", "8", "trainSampleSize",
"16"));
}
+
+ /// When cosineDistance requested the distances of this search, the operator
asks the index for them, matches the
+ /// documents they cover and hands them over through the query's
[VectorSearchDistances].
+ @Test
+ public void testHandsOverDistancesWhenRequested() {
+ float[] queryVector = {1.0f, 2.0f, 3.0f};
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ Int2FloatMap distances = distances(1, 3, 5);
+ when(reader.getCosineDistances(queryVector, 3)).thenReturn(distances);
+ VectorSearchDistances searchDistances = new VectorSearchDistances();
+ VectorSearchDistances.Request request = searchDistances.request(reader,
queryVector.clone());
+
+ VectorSimilarityFilterOperator operator = newOperator(reader, queryVector,
null);
+ operator.setSearchDistances(searchDistances);
+
+ Assert.assertEquals(operator.getBitmaps().reduce().toArray(), new int[]{1,
3, 5});
+ Assert.assertSame(request.getDistances(), distances);
+ verify(reader, never()).getDocIds(any(float[].class), anyInt());
+ }
+
+ /// Exact rerank selects rows by the exact forward-index distance, so the
index's approximate distances are not handed
+ /// over: the projection computes the exact ones.
+ @Test
+ public void testDoesNotHandOverDistancesWithExactRerank() {
+ float[] queryVector = {1.0f, 0.0f};
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ when(reader.getDocIds(Mockito.eq(queryVector),
Mockito.anyInt())).thenReturn(MutableRoaringBitmap.bitmapOf(0, 1));
+ VectorSearchDistances searchDistances = new VectorSearchDistances();
+ VectorSearchDistances.Request request = searchDistances.request(reader,
queryVector.clone());
+ ForwardIndexReader<?> forward = createMockForwardIndexReader(new
float[][]{{0.9f, 0.1f}, {0.0f, 1.0f}});
+ VectorSearchParams params = new VectorSearchParams(null, true, null, null,
null, null, null);
+
+ VectorSimilarityFilterOperator operator = new
VectorSimilarityFilterOperator(reader,
+ new
VectorSimilarityPredicate(ExpressionContext.forIdentifier("embedding"),
queryVector, 1), 10, params,
+ forward);
+ operator.setSearchDistances(searchDistances);
+
+ Assert.assertEquals(operator.getBitmaps().reduce().toArray(), new
int[]{0});
+ Assert.assertNull(request.getDistances());
+ verify(reader, never()).getCosineDistances(any(float[].class), anyInt());
+ }
+
+ /// Without a request, a search collects only doc ids, so queries that do
not project cosineDistance pay nothing.
+ @Test
+ public void testDoesNotAskForDistancesWithoutRequest() {
+ float[] queryVector = {1.0f, 2.0f, 3.0f};
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ when(reader.getDocIds(queryVector,
3)).thenReturn(MutableRoaringBitmap.bitmapOf(1, 3, 5));
+ VectorSearchDistances searchDistances = new VectorSearchDistances();
+ searchDistances.request(reader, new float[]{9.0f, 9.0f, 9.0f});
+
+ VectorSimilarityFilterOperator operator = newOperator(reader, queryVector,
null);
+ operator.setSearchDistances(searchDistances);
+
+ Assert.assertEquals(operator.getBitmaps().reduce().toArray(), new int[]{1,
3, 5});
+ verify(reader, never()).getCosineDistances(any(float[].class), anyInt());
+ }
+
+ /// An index that returns no distances still answers the filter through
`getDocIds`.
+ @Test
+ public void testFallsBackToDocIdsWhenIndexReturnsNoDistances() {
+ float[] queryVector = {1.0f, 2.0f, 3.0f};
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ when(reader.getCosineDistances(queryVector, 3)).thenReturn(null);
+ when(reader.getDocIds(queryVector,
3)).thenReturn(MutableRoaringBitmap.bitmapOf(1, 3, 5));
+ VectorSearchDistances searchDistances = new VectorSearchDistances();
+ VectorSearchDistances.Request request = searchDistances.request(reader,
queryVector);
+
+ VectorSimilarityFilterOperator operator = newOperator(reader, queryVector,
null);
+ operator.setSearchDistances(searchDistances);
+
+ Assert.assertEquals(operator.getBitmaps().reduce().toArray(), new int[]{1,
3, 5});
+ Assert.assertNull(request.getDistances());
+ }
+
+ /// A filtered search hands over the distances of the filtered search.
+ @Test
+ public void testHandsOverDistancesOfFilteredSearch() {
+ float[] queryVector = {1.0f, 2.0f, 3.0f};
+ MutableRoaringBitmap requiredDocIds = MutableRoaringBitmap.bitmapOf(2, 4,
6, 8);
+ FilterAwareVectorIndexReader reader =
mock(FilterAwareVectorIndexReader.class);
+ when(reader.supportsPreFilter()).thenReturn(true);
+ Int2FloatMap distances = distances(4, 8);
+ when(reader.getCosineDistances(any(float[].class), anyInt(),
any(ImmutableRoaringBitmap.class)))
+ .thenReturn(distances);
+ VectorSearchDistances searchDistances = new VectorSearchDistances();
+ VectorSearchDistances.Request request = searchDistances.request(reader,
queryVector);
+
+ VectorSimilarityFilterOperator operator = newOperator(reader, queryVector,
requiredDocIds);
+ operator.setSearchDistances(searchDistances);
+
+ Assert.assertEquals(operator.getBitmaps().reduce().toArray(), new int[]{4,
8});
+ Assert.assertSame(request.getDistances(), distances);
+ verify(reader, never()).getDocIds(any(float[].class), anyInt(),
any(ImmutableRoaringBitmap.class));
+ }
+
+ private static VectorSimilarityFilterOperator newOperator(VectorIndexReader
reader, float[] queryVector,
+ MutableRoaringBitmap requiredDocIds) {
+ VectorSimilarityPredicate predicate =
+ new
VectorSimilarityPredicate(ExpressionContext.forIdentifier("embedding"),
queryVector, 3);
+ return new VectorSimilarityFilterOperator(reader, predicate, 100,
VectorSearchParams.DEFAULT, null, null, false,
+ requiredDocIds);
+ }
+
+ private static Int2FloatMap distances(int... docIds) {
+ Int2FloatOpenHashMap distances = new Int2FloatOpenHashMap();
+ for (int docId : docIds) {
+ distances.put(docId, docId / 10f);
+ }
+ return distances;
+ }
}
diff --git
a/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/CosineDistanceIndexTransformFunctionTest.java
b/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/CosineDistanceIndexTransformFunctionTest.java
new file mode 100644
index 00000000000..d84f739aee1
--- /dev/null
+++
b/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/CosineDistanceIndexTransformFunctionTest.java
@@ -0,0 +1,282 @@
+/**
+ * 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.pinot.core.operator.transform.function;
+
+import it.unimi.dsi.fastutil.ints.Int2FloatOpenHashMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.pinot.common.function.scalar.VectorFunctions;
+import org.apache.pinot.common.request.context.RequestContextUtils;
+import org.apache.pinot.core.operator.ColumnContext;
+import org.apache.pinot.core.operator.filter.VectorSearchDistances;
+import
org.apache.pinot.core.operator.transform.function.VectorTransformFunctions.CosineDistanceTransformFunction;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import
org.apache.pinot.core.query.request.context.utils.QueryContextConverterUtils;
+import org.apache.pinot.segment.spi.datasource.DataSource;
+import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig;
+import
org.apache.pinot.segment.spi.index.creator.VectorIndexConfig.VectorDistanceFunction;
+import org.apache.pinot.segment.spi.index.reader.VectorIndexReader;
+import org.apache.pinot.sql.parsers.CalciteSqlParser;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// `cosineDistance` on a column with a COSINE vector index returns the
distances a `VECTOR_SIMILARITY` search hands
+/// over through the query, and otherwise computes them from the forward index.
+public class CosineDistanceIndexTransformFunctionTest extends
BaseTransformFunctionTest {
+
+ @Test
+ public void testComputesDistancesWithoutVectorIndex() {
+ float[] query = _vector2Values[0];
+ QueryContext queryContext = approximateQueryContext();
+ double[] actual = transform(_dataSourceMap, "cosineDistance(vector1, " +
toLiteral(query) + ")", queryContext);
+ for (int i = 0; i < NUM_ROWS; i++) {
+ assertEquals(actual[i],
VectorFunctions.cosineDistance(_vector1Values[i], query), 1e-9);
+ }
+ }
+
+ /// Distances handed over by the filter's search are used as they are,
without searching the index again, with the
+ /// column on either side and with a default value.
+ @Test
+ public void testUsesDistancesHandedOverByTheSearch() {
+ float[] query = _vector2Values[0];
+ String literal = toLiteral(query);
+ for (String expression : new String[]{
+ "cosineDistance(vector1, " + literal + ")",
+ "cosineDistance(" + literal + ", vector1)",
+ "cosineDistance(vector1, " + literal + ", 0.5)"}) {
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ TransformFunction function =
+ create(withVectorIndex(reader, VectorDistanceFunction.COSINE),
expression, queryContext);
+ VectorSearchDistances.Request request =
VectorSearchDistances.of(queryContext).getRequest(reader, query.clone());
+ assertNotNull(request, expression + " must request the distances of the
search while it is planned");
+ Int2FloatOpenHashMap served = new Int2FloatOpenHashMap();
+ for (int i = 0; i < NUM_ROWS; i++) {
+ served.put(i, -i);
+ }
+ request.setDistances(served);
+ double[] actual = function.transformToDoubleValuesSV(_projectionBlock);
+ for (int i = 0; i < NUM_ROWS; i++) {
+ assertEquals(actual[i], -i, 0.0, expression);
+ }
+ verify(reader, never()).getCosineDistances(any(float[].class), anyInt());
+ verify(reader, never()).getDocIds(any(float[].class), anyInt());
+ }
+ }
+
+ /// Only a COSINE index serves cosine distances: other distance functions
request nothing.
+ @Test
+ public void testRequestsNothingFromNonCosineIndex() {
+ float[] query = _vector2Values[0];
+ for (VectorDistanceFunction distanceFunction :
VectorDistanceFunction.values()) {
+ if (distanceFunction == VectorDistanceFunction.COSINE) {
+ continue;
+ }
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ double[] actual = transform(withVectorIndex(reader, distanceFunction),
+ "cosineDistance(vector1, " + toLiteral(query) + ")", queryContext);
+ assertNull(VectorSearchDistances.of(queryContext).getRequest(reader,
query), distanceFunction.name());
+ for (int i = 0; i < NUM_ROWS; i++) {
+ assertEquals(actual[i],
VectorFunctions.cosineDistance(_vector1Values[i], query), 1e-9);
+ }
+ }
+ }
+
+ /// Without a search to take distances from, they are computed rather than
searched for.
+ @Test
+ public void testComputesDistancesWhenNoSearchHandsThemOver() {
+ float[] query = _vector2Values[0];
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ double[] actual = transform(withVectorIndex(reader,
VectorDistanceFunction.COSINE),
+ "cosineDistance(vector1, " + toLiteral(query) + ")",
approximateQueryContext());
+ for (int i = 0; i < NUM_ROWS; i++) {
+ assertEquals(actual[i],
VectorFunctions.cosineDistance(_vector1Values[i], query), 1e-9);
+ }
+ verify(reader, never()).getCosineDistances(any(float[].class), anyInt());
+ }
+
+ @Test
+ public void testExactDistanceByDefaultAndWithRowFilter() {
+ float[] query = _vector2Values[0];
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext defaultContext = QueryContextConverterUtils.getQueryContext(
+ CalciteSqlParser.compileToPinotQuery("SELECT * FROM testTable"));
+ QueryContext policyContext = approximateQueryContext();
+
policyContext.setRowFilter(RequestContextUtils.getFilter(CalciteSqlParser.compileToExpression("intSV
= 1")));
+ for (QueryContext queryContext : List.of(defaultContext, policyContext)) {
+ double[] actual = transform(withVectorIndex(reader,
VectorDistanceFunction.COSINE),
+ "cosineDistance(vector1, " + toLiteral(query) + ")", queryContext);
+ assertNull(VectorSearchDistances.of(queryContext).getRequest(reader,
query));
+ for (int i = 0; i < NUM_ROWS; i++) {
+ assertEquals(actual[i],
VectorFunctions.cosineDistance(_vector1Values[i], query), 0.0);
+ }
+ }
+ }
+
+ /// Distances are matched by query vector: a search for another vector hands
nothing over.
+ @Test
+ public void testIgnoresSearchForAnotherVector() {
+ float[] query = _vector2Values[0];
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ create(withVectorIndex(reader, VectorDistanceFunction.COSINE),
"cosineDistance(vector1, " + toLiteral(query) + ")",
+ queryContext);
+ assertNull(VectorSearchDistances.of(queryContext).getRequest(reader,
_vector2Values[1]));
+ }
+
+ @Test
+ public void testComputesOnlyMissingDocuments() {
+ float[] query = _vector2Values[0];
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ TransformFunction function = create(withVectorIndex(reader,
VectorDistanceFunction.COSINE),
+ "cosineDistance(vector1, " + toLiteral(query) + ")", queryContext);
+ Int2FloatOpenHashMap served = new Int2FloatOpenHashMap();
+ int[] docIds = _projectionBlock.getDocIds();
+ served.put(docIds[1], 0.25f);
+ VectorSearchDistances.of(queryContext).getRequest(reader,
query).setDistances(served);
+ double[] actual = function.transformToDoubleValuesSV(_projectionBlock);
+ for (int i = 0; i < NUM_ROWS; i++) {
+ assertEquals(actual[i], i == 1 ? 0.25 :
VectorFunctions.cosineDistance(_vector1Values[docIds[i]], query), 0.0);
+ }
+ }
+
+ /// A non-finite distance from the search (a zero vector, or a norm that
underflows in float) is computed exactly
+ /// instead, which applies the default value where one is given.
+ @Test
+ public void testComputesDistancesWhenSearchReturnsNonFinite() {
+ for (float[] query : new float[][]{new float[VECTOR_DIM_SIZE],
_vector2Values[0]}) {
+ for (String defaultValue : new String[]{"", ", 7"}) {
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ TransformFunction function = create(withVectorIndex(reader,
VectorDistanceFunction.COSINE),
+ "cosineDistance(vector1, " + toLiteral(query) + defaultValue +
")", queryContext);
+ Int2FloatOpenHashMap served = new Int2FloatOpenHashMap();
+ int[] docIds = _projectionBlock.getDocIds();
+ served.put(docIds[0], Float.NaN);
+ served.put(docIds[1], Float.POSITIVE_INFINITY);
+ for (int i = 2; i < NUM_ROWS; i++) {
+ served.put(docIds[i], 0.25f);
+ }
+ VectorSearchDistances.of(queryContext).getRequest(reader,
query).setDistances(served);
+ double[] actual = function.transformToDoubleValuesSV(_projectionBlock);
+ for (int i = 0; i < NUM_ROWS; i++) {
+ double expected = 0.25;
+ if (i < 2) {
+ float[] row = _vector1Values[docIds[i]];
+ expected = defaultValue.isEmpty() ?
VectorFunctions.cosineDistance(row, query)
+ : VectorFunctions.cosineDistance(row, query, 7);
+ }
+ assertEquals(actual[i], expected, 1e-9);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testVariableWidthColumnKeepsScalarDimensionCheck() {
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ Map<String, DataSource> dataSources = withVectorIndex(FLOAT_MV_COLUMN,
reader, VectorDistanceFunction.COSINE);
+ // The literal matches the longest row. Shorter rows in this column would
be padded by HNSW ingestion.
+ int maxWidth =
dataSources.get(FLOAT_MV_COLUMN).getDataSourceMetadata().getMaxNumValuesPerMVEntry();
+ float[] query = new float[maxWidth];
+ TransformFunction function = create(dataSources, "cosineDistance(" +
FLOAT_MV_COLUMN + ", " + toLiteral(query)
+ + ")", queryContext);
+ assertNull(VectorSearchDistances.of(queryContext).getRequest(reader,
query));
+ IllegalArgumentException exception =
+ expectThrows(IllegalArgumentException.class, () ->
function.transformToDoubleValuesSV(_projectionBlock));
+ assertEquals(exception.getMessage(), "Vector lengths do not match");
+ }
+
+ /// An integer projection literal matches a search for the equivalent float
vector.
+ @Test
+ public void testIntegerVectorLiteralMatchesTheSearch() {
+ StringBuilder literal = new StringBuilder("ARRAY[");
+ float[] query = new float[VECTOR_DIM_SIZE];
+ for (int i = 0; i < VECTOR_DIM_SIZE; i++) {
+ query[i] = i % 3 + 1;
+ literal.append(i == 0 ? "" : ",").append(i % 3 + 1);
+ }
+ VectorIndexReader reader = mock(VectorIndexReader.class);
+ QueryContext queryContext = approximateQueryContext();
+ create(withVectorIndex(reader, VectorDistanceFunction.COSINE),
"cosineDistance(vector1, " + literal + "])",
+ queryContext);
+ assertNotNull(VectorSearchDistances.of(queryContext).getRequest(reader,
query));
+ }
+
+ private double[] transform(Map<String, DataSource> dataSourceMap, String
expression, QueryContext queryContext) {
+ return create(dataSourceMap, expression,
queryContext).transformToDoubleValuesSV(_projectionBlock);
+ }
+
+ private static TransformFunction create(Map<String, DataSource>
dataSourceMap, String expression,
+ QueryContext queryContext) {
+ Map<String, ColumnContext> columnContextMap = new HashMap<>();
+ dataSourceMap.forEach(
+ (column, dataSource) -> columnContextMap.put(column,
ColumnContext.fromDataSource(dataSource)));
+ TransformFunction function =
+
TransformFunctionFactory.get(RequestContextUtils.getExpression(expression),
columnContextMap, queryContext);
+ assertTrue(function instanceof CosineDistanceTransformFunction);
+ return function;
+ }
+
+ private static QueryContext approximateQueryContext() {
+ return QueryContextConverterUtils.getQueryContext(
+ CalciteSqlParser.compileToPinotQuery("SET vectorApproximateDistance =
true; SELECT * FROM testTable"));
+ }
+
+ private Map<String, DataSource> withVectorIndex(VectorIndexReader reader,
VectorDistanceFunction function) {
+ return withVectorIndex(VECTOR_1_COLUMN, reader, function);
+ }
+
+ private Map<String, DataSource> withVectorIndex(String column,
VectorIndexReader reader,
+ VectorDistanceFunction function) {
+ VectorIndexConfig config = mock(VectorIndexConfig.class);
+ when(config.getVectorDistanceFunction()).thenReturn(function);
+ DataSource dataSource = spy(_dataSourceMap.get(column));
+ when(dataSource.getVectorIndex()).thenReturn(reader);
+ when(dataSource.getVectorIndexConfig()).thenReturn(config);
+ Map<String, DataSource> dataSourceMap = new HashMap<>(_dataSourceMap);
+ dataSourceMap.put(column, dataSource);
+ return dataSourceMap;
+ }
+
+ private static String toLiteral(float[] vector) {
+ StringBuilder literal = new StringBuilder("ARRAY[");
+ for (int i = 0; i < vector.length; i++) {
+ literal.append(i == 0 ? "" : ",").append(vector[i]);
+ }
+ return literal.append(']').toString();
+ }
+}
diff --git
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/VectorTest.java
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/VectorTest.java
index b4d0d02afc0..fc1af77c16a 100644
---
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/VectorTest.java
+++
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/VectorTest.java
@@ -211,6 +211,28 @@ public class VectorTest extends
CustomDataQueryClusterIntegrationTest {
}
}
+ @Test(dataProvider = "useBothQueryEngines")
+ public void testApproximateCosineDistance(boolean useMultiStageQueryEngine)
+ throws Exception {
+ setUseMultiStageQueryEngine(useMultiStageQueryEngine);
+ String queryVector = "ARRAY[1.0" + StringUtils.repeat(", 0.0",
VECTOR_DIM_SIZE - 1) + "]";
+ String distance = "cosineDistance(" + VECTOR_1 + ", " + queryVector + ")";
+ String query = "SELECT " + distance + " AS dist FROM " + getTableName()
+ + " WHERE vectorSimilarity(" + VECTOR_1 + ", " + queryVector + ", " +
getCountStarResult() + ")";
+ String orderBy = " ORDER BY dist LIMIT 1";
+
+ // The nearly parallel fixture row has positive scalar distance, but
Lucene rounds its score to 1.
+ double expected = VectorFunctions.cosineDistance(new float[]{1, 0.0001f},
new float[]{1, 0});
+ JsonNode exact = postQuery(query + " AND " + distance + " > 0" + orderBy);
+ assertTrue(exact.has("resultTable"), exact.toString());
+
assertEquals(exact.get("resultTable").get("rows").get(0).get(0).asDouble(),
expected);
+ if (!useMultiStageQueryEngine) {
+ JsonNode approximate = postQuery("SET vectorApproximateDistance=true; "
+ query + orderBy);
+ assertTrue(approximate.has("resultTable"), approximate.toString());
+
assertEquals(approximate.get("resultTable").get("rows").get(0).get(0).asDouble(),
0.0);
+ }
+ }
+
/// Tests filtered ANN: VECTOR_SIMILARITY combined with a metadata filter.
/// All returned rows must match the filter predicate and be ordered by
distance.
@Test(dataProvider = "useBothQueryEngines")
@@ -490,7 +512,11 @@ public class VectorTest extends
CustomDataQueryClusterIntegrationTest {
// create avro record
GenericData.Record record = new GenericData.Record(avroSchema);
- float[] vector1 = createRandomVector(VECTOR_DIM_SIZE);
+ float[] vector1 = i == 0 ? new float[VECTOR_DIM_SIZE] :
createRandomVector(VECTOR_DIM_SIZE);
+ if (i == 0) {
+ vector1[0] = 1;
+ vector1[1] = 0.0001f;
+ }
float[] vector2 = createRandomVector(VECTOR_DIM_SIZE);
float[] zeroVector = createZeroVector(VECTOR_DIM_SIZE);
diff --git
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/HnswVectorIndexReader.java
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/HnswVectorIndexReader.java
index 5c731fe917d..95683b8b121 100644
---
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/HnswVectorIndexReader.java
+++
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/HnswVectorIndexReader.java
@@ -19,6 +19,8 @@
package org.apache.pinot.segment.local.segment.index.readers.vector;
import com.google.common.base.Preconditions;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
+import it.unimi.dsi.fastutil.ints.Int2FloatOpenHashMap;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
@@ -29,8 +31,10 @@ import java.util.Map;
import javax.annotation.Nullable;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.KnnFloatVectorQuery;
@@ -64,6 +68,8 @@ public class HnswVectorIndexReader implements
FilterAwareVectorIndexReader, EfSe
private final ThreadLocal<Integer> _efSearchOverride = new ThreadLocal<>();
private final ThreadLocal<Boolean> _useRelativeDistanceOverride = new
ThreadLocal<>();
private final ThreadLocal<Boolean> _useBoundedQueueOverride = new
ThreadLocal<>();
+ /// Whether the loaded index scores hits using cosine similarity.
+ private final boolean _isCosineIndex;
/// File-backed constructor: opens a [FSDirectory] from the Lucene HNSW
index directory
/// found under `indexDir`.
@@ -74,6 +80,7 @@ public class HnswVectorIndexReader implements
FilterAwareVectorIndexReader, EfSe
_indexDirectory = FSDirectory.open(indexFile.toPath());
_indexReader = DirectoryReader.open(_indexDirectory);
_indexSearcher = new IndexSearcher(_indexReader);
+ _isCosineIndex = isCosineIndex(_indexReader, column);
// TODO: consider using a threshold of num docs per segment to decide
between building
// mapping file upfront on segment load v/s on-the-fly during query
processing
@@ -102,6 +109,7 @@ public class HnswVectorIndexReader implements
FilterAwareVectorIndexReader, EfSe
_indexDirectory =
HnswVectorIndexBufferReader.createLuceneDirectory(indexBuffer, column);
_indexReader = DirectoryReader.open(_indexDirectory);
_indexSearcher = new IndexSearcher(_indexReader);
+ _isCosineIndex = isCosineIndex(_indexReader, column);
// Try to extract the mapping from the packed buffer first; build from
the Lucene index if absent.
PinotDataBuffer mappingBuffer =
HnswVectorIndexBufferReader.extractDocIdMappingBuffer(indexBuffer, column);
@@ -112,6 +120,18 @@ public class HnswVectorIndexReader implements
FilterAwareVectorIndexReader, EfSe
}
}
+ /// Whether the loaded index was built with COSINE similarity. The table
config can name another function than the
+ /// one persisted in Lucene (changing it does not rebuild the index on
reload), so the persisted one decides.
+ private static boolean isCosineIndex(IndexReader indexReader, String column)
{
+ for (LeafReaderContext leaf : indexReader.leaves()) {
+ FieldInfo fieldInfo = leaf.reader().getFieldInfos().fieldInfo(column);
+ if (fieldInfo != null && fieldInfo.getVectorDimension() > 0) {
+ return fieldInfo.getVectorSimilarityFunction() ==
VectorSimilarityFunction.COSINE;
+ }
+ }
+ return false;
+ }
+
/// CASE 1: If IndexLoadingConfig specifies a segment version to load and if
it is different then the on-disk version
/// of the segment, then
[org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader]
will
/// take care of up-converting the on-disk segment to v3 before load. The
converter already has support for converting
@@ -258,6 +278,46 @@ public class HnswVectorIndexReader implements
FilterAwareVectorIndexReader, EfSe
return docIds;
}
+ @Nullable
+ @Override
+ public Int2FloatMap getCosineDistances(float[] vector, int topK) {
+ if (!_isCosineIndex) {
+ return null;
+ }
+ try {
+ return toCosineDistances(search(vector, topK, null));
+ } catch (IOException e) {
+ throw new RuntimeException("Caught exception while searching the HNSW
index for column: " + _column, e);
+ }
+ }
+
+ @Nullable
+ @Override
+ public Int2FloatMap getCosineDistances(float[] vector, int topK,
ImmutableRoaringBitmap preFilterBitmap) {
+ Preconditions.checkNotNull(preFilterBitmap, "Pre-filter bitmap must not be
null for filtered vector search");
+ if (!_isCosineIndex) {
+ return null;
+ }
+ if (preFilterBitmap.isEmpty()) {
+ return new Int2FloatOpenHashMap();
+ }
+ try {
+ return toCosineDistances(search(vector, topK, new
RoaringBitmapFilterQuery(preFilterBitmap, _docIdTranslator)));
+ } catch (IOException e) {
+ throw new RuntimeException(
+ "Caught exception while searching the HNSW index with pre-filter for
column: " + _column, e);
+ }
+ }
+
+ /// Converts Lucene COSINE scores (`(1 + cos) / 2`) to cosine distances (`1
- cos`), keyed by Pinot doc id.
+ private Int2FloatMap toCosineDistances(TopDocs topDocs) {
+ Int2FloatOpenHashMap distances = new
Int2FloatOpenHashMap(topDocs.scoreDocs.length);
+ for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
+ distances.put(_docIdTranslator.getPinotDocId(scoreDoc.doc), 2 - 2 *
scoreDoc.score);
+ }
+ return distances;
+ }
+
/// Lucene docIDs are not same as pinot docIDs. The internal implementation
/// of Lucene can change the docIds and they are not guaranteed to be the
/// same as how we expect -- strictly increasing docIDs as the documents
diff --git
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
index 056f3da39d3..ed9d17011eb 100644
---
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
+++
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
@@ -19,6 +19,7 @@
package org.apache.pinot.segment.local.segment.index.creator;
import com.google.common.base.Throwables;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -52,6 +53,7 @@ import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.Version;
import org.apache.lucene.util.hnsw.HnswGraph;
+import org.apache.pinot.common.function.scalar.VectorFunctions;
import
org.apache.pinot.segment.local.segment.creator.impl.vector.HnswVectorIndexCreator;
import
org.apache.pinot.segment.local.segment.creator.impl.vector.lucene99.HnswCodec;
import
org.apache.pinot.segment.local.segment.creator.impl.vector.lucene99.HnswVectorsFormat;
@@ -431,4 +433,111 @@ public class HnswVectorIndexCreatorTest {
}
}
}
+
+ /// A COSINE index returns the cosine distances of the documents each search
returns, the same documents as
+ /// `getDocIds`, and keeps nothing between searches; other distance
functions return none.
+ @Test
+ public void testServesCosineDistances()
+ throws IOException {
+ File indexDir = new File(INDEX_DIR, "cosine");
+ FileUtils.forceMkdir(indexDir);
+ float[][] vectors = new float[200][8];
+ Random random = new Random(7);
+ for (float[] vector : vectors) {
+ for (int d = 0; d < vector.length; d++) {
+ vector[d] = random.nextFloat() - 0.5f;
+ }
+ }
+ for (String distanceFunction : new String[]{"COSINE", "EUCLIDEAN"}) {
+ Map<String, String> properties = new HashMap<>();
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "8");
+ properties.put("vectorDistanceFunction", distanceFunction);
+ properties.put("buildThreads", "4");
+ properties.put("forceMerge", "false");
+ VectorIndexConfig config = new VectorIndexConfig(properties);
+ FileUtils.cleanDirectory(indexDir);
+ try (HnswVectorIndexCreator creator = new HnswVectorIndexCreator("baz",
indexDir, config)) {
+ for (float[] vector : vectors) {
+ creator.add(vector);
+ }
+ creator.seal();
+ }
+ try (HnswVectorIndexReader reader = new HnswVectorIndexReader("baz",
indexDir, vectors.length, config)) {
+ float[] query = vectors[3];
+ MutableRoaringBitmap allowed = new MutableRoaringBitmap();
+ allowed.add(10L, 60L);
+ if (distanceFunction.equals("EUCLIDEAN")) {
+ Assert.assertNull(reader.getCosineDistances(query, 5));
+ Assert.assertNull(reader.getCosineDistances(query, 5, allowed));
+ continue;
+ }
+ Int2FloatMap distances = reader.getCosineDistances(query, 20);
+ Assert.assertEquals(sortedDocIds(distances), reader.getDocIds(query,
20).toArray());
+ assertCosineDistances(distances, vectors, query);
+
+ Int2FloatMap filtered = reader.getCosineDistances(query, 5, allowed);
+ Assert.assertEquals(sortedDocIds(filtered), reader.getDocIds(query, 5,
allowed).toArray());
+ for (int docId : filtered.keySet()) {
+ Assert.assertTrue(allowed.contains(docId), "Filtered search returned
doc outside the filter: " + docId);
+ }
+ assertCosineDistances(filtered, vectors, query);
+ Assert.assertTrue(reader.getCosineDistances(query, 5, new
MutableRoaringBitmap()).isEmpty());
+
+ // Stateless: a later search does not see the documents of an earlier
one.
+ Assert.assertEquals(reader.getCosineDistances(query, 3).size(), 3);
+ }
+ }
+ }
+
+ /// The metric persisted in the index decides whether distances are served:
a table config changed to another
+ /// function without rebuilding the index must not convert the old scores as
cosine scores.
+ @Test
+ public void testServesDistancesByThePersistedMetric()
+ throws IOException {
+ File indexDir = new File(INDEX_DIR, "metric");
+ FileUtils.forceMkdir(indexDir);
+ float[][] vectors = {{2, 0}, {0, 1}, {1, 1}, {3, 4}};
+ float[] query = {1, 0};
+ for (String[] builtAndLoaded : new String[][]{{"EUCLIDEAN", "COSINE"},
{"COSINE", "EUCLIDEAN"}}) {
+ FileUtils.cleanDirectory(indexDir);
+ try (HnswVectorIndexCreator creator =
+ new HnswVectorIndexCreator("baz", indexDir,
hnswConfig(builtAndLoaded[0]))) {
+ for (float[] vector : vectors) {
+ creator.add(vector);
+ }
+ creator.seal();
+ }
+ try (HnswVectorIndexReader reader =
+ new HnswVectorIndexReader("baz", indexDir, vectors.length,
hnswConfig(builtAndLoaded[1]))) {
+ if (builtAndLoaded[0].equals("EUCLIDEAN")) {
+ Assert.assertNull(reader.getCosineDistances(query, 4));
+ Assert.assertNull(reader.getCosineDistances(query, 4,
MutableRoaringBitmap.bitmapOf(0, 1)));
+ } else {
+ assertCosineDistances(reader.getCosineDistances(query, 4), vectors,
query);
+ }
+ }
+ }
+ }
+
+ private static VectorIndexConfig hnswConfig(String distanceFunction) {
+ Map<String, String> properties = new HashMap<>();
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "2");
+ properties.put("vectorDistanceFunction", distanceFunction);
+ return new VectorIndexConfig(properties);
+ }
+
+ private static int[] sortedDocIds(Int2FloatMap distances) {
+ int[] docIds = distances.keySet().toIntArray();
+ Arrays.sort(docIds);
+ return docIds;
+ }
+
+ private static void assertCosineDistances(Int2FloatMap distances, float[][]
vectors, float[] query) {
+ for (Int2FloatMap.Entry entry : distances.int2FloatEntrySet()) {
+ Assert.assertEquals(entry.getFloatValue(),
VectorFunctions.cosineDistance(vectors[entry.getIntKey()], query),
+ 1e-5);
+ }
+ }
}
diff --git
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/FilterAwareVectorIndexReader.java
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/FilterAwareVectorIndexReader.java
index ebd0b6ebcf6..ca430ce0e8f 100644
---
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/FilterAwareVectorIndexReader.java
+++
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/FilterAwareVectorIndexReader.java
@@ -18,6 +18,9 @@
*/
package org.apache.pinot.segment.spi.index.reader;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
+import java.util.Objects;
+import javax.annotation.Nullable;
import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
@@ -45,6 +48,17 @@ public interface FilterAwareVectorIndexReader extends
VectorIndexReader {
/// silently searching unfiltered, which would return documents
outside the caller's filter.
ImmutableRoaringBitmap getDocIds(float[] vector, int topK,
ImmutableRoaringBitmap preFilterBitmap);
+ /// Searches like [#getDocIds(float[], int, ImmutableRoaringBitmap)] and
returns the same top-K documents with their
+ /// approximate cosine distances, as described in
[#getCosineDistances(float[], int)].
+ ///
+ /// @return cosine distances keyed by Pinot doc id, or `null` if the reader
does not support them
+ /// @throws NullPointerException if preFilterBitmap is null
+ @Nullable
+ default Int2FloatMap getCosineDistances(float[] vector, int topK,
ImmutableRoaringBitmap preFilterBitmap) {
+ Objects.requireNonNull(preFilterBitmap, "Pre-filter bitmap must not be
null for filtered vector search");
+ return null;
+ }
+
/// Returns true if this reader supports efficient pre-filter search.
/// Some implementations may support the interface but only for certain
/// filter selectivities or index configurations.
diff --git
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/VectorIndexReader.java
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/VectorIndexReader.java
index a25e81187d0..0c944f3efd7 100644
---
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/VectorIndexReader.java
+++
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/reader/VectorIndexReader.java
@@ -18,7 +18,9 @@
*/
package org.apache.pinot.segment.spi.index.reader;
+import it.unimi.dsi.fastutil.ints.Int2FloatMap;
import java.util.Map;
+import javax.annotation.Nullable;
import org.apache.pinot.segment.spi.index.IndexReader;
import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
@@ -31,6 +33,14 @@ public interface VectorIndexReader extends IndexReader {
/// @return bitmap of top k closest vectors
ImmutableRoaringBitmap getDocIds(float[] vector, int topK);
+ /// Searches like [#getDocIds(float[], int)] and returns the same top-K
documents, keyed by Pinot doc id, with
+ /// approximate cosine distances (1 - cosine similarity) from the loaded
index. A reader that cannot supply
+ /// cosine distances returns `null` without executing a search, so the
caller can use [#getDocIds(float[], int)].
+ @Nullable
+ default Int2FloatMap getCosineDistances(float[] vector, int topK) {
+ return null;
+ }
+
/// Returns a map of effective runtime state for debug and explain output.
/// Implementations should report actual loaded values, not just requested
config.
///
diff --git
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index 5e4ca875113..dab8151dcdf 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -1311,6 +1311,10 @@ public class CommonConstants {
/// Controls whether HNSW uses a bounded top-K collector queue.
Defaults to true.
/// Setting false uses an unbounded per-query collector and requires
vectorEfSearch.
public static final String VECTOR_USE_BOUNDED_QUEUE =
"vectorUseBoundedQueue";
+
+ /// Allows `cosineDistance` to use approximate scores from a paired
COSINE vector index search.
+ /// This can change projected values and their ordering. Defaults to
false.
+ public static final String VECTOR_APPROXIMATE_DISTANCE =
"vectorApproximateDistance";
}
public static class QueryOptionValue {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]