Merged PR 1653287: [Vector Search] Enable iterative index scans for HNSW and IVF in filtering searches

### Does this PR have any customer impact?
Yes

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Feature

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
Yes

### Release Note (Refer [Template](../docs/release_notes/pgmongo_template.md))

### Description
With the release of [pgvector 0.8.0](https://github.com/pgvector/pgvector/tree/5bc7937715c67add21c8bcc0d4284162c7a0174f?tab=readme-ov-file#iterative-index-scans), which supports iterative scan for HNSW and IVF, we enable it in filtering search to support pre-filtering(currently it is post-filtering)
- Pass the new parameter "iterativeScan" through the function bson_search_param from the coordinator to the worker.
Example : { "efSearch" : 10, "iterativeScan" : "relaxed_order"}
- Enable iterative scan for hnsw/ivf index on workers:
SET LOCAL  hnsw.iterative_scan = relaxed_order;
SET LOCAL  ivfflat.iterative_scan = relaxed_order;
relaxed_order by default, which allows results to be slightly out of order by distance, but provides better recall.
After iterative search, re-ordering will be applied to the results.
- Set iterative scan for diskann index to relaxed_order
SET LOCAL  diskann.iterative_search = relaxed_order;
- Check the availability of iterative scan in pgvector
The pgvector iterative scan is available from version 0.8.0. Currently, if the pgvector extension has not been upgraded to 0.8.0, the iterative scan will be disabled in those clusters until pgvector is upgraded to 0.8.0.

###Related GUCs
**documentdb.vectorPreFilterIterativeScanMode**: enable iterative index scans, which will automatically scan more of the index until enough results are found (relaxed_order by default)
- off, disable iterative scan
- relaxed_order,  allows results to be slightly out of order by distance, but provides better recall
- strict_order, ensures results are in the exact order by distance

####GUCs from pgvector
**hnsw.max_scan_tuples**: Specify the max number of tuples to visit (20,000 by default)
**hnsw.scan_mem_multiplier**: Specify the max amount of memory to use, as a multiple of work_mem (1 by default)
**ivfflat.max_probes**: Specify the max number of probes(32768 by default)

###Mongo Command(no change in this PR)
```
db.testing_hnsw_vector_collection.aggregate(
[
  {
    "$search": {
	  "cosmosSearch": {
        "vector": [ 3.0, 4.9, 1.0 ],
        "path": "vect",
        "filter": {"meta.a": [ { "b" : 3 } ]},
        "k": 4,
        "efSearch": 100
      },
    }
  },
  {
    "$project": {
      "rank": {
        "$floor": [{"$multiply": [{ "$meta": "searchScore"},100000]}]
      }
    }
  }
])
```

----
#### AI description  (iteration 1)
#### PR Classification
New feature

#### PR Summary
This pull request introduces iterative index scans for HNSW and IVF in filtering searches, enhancing the pre-filtering capabilities of vector searches...
This commit is contained in:
Zinan Ren authored and Shuai Tian committed 2025-05-09 14:08:53 +08:00
1 parent 7c8dede426
commit ac6f028c86
21 files changed
+2257 -1721

No files matched your search

@@ -45,6 +45,7 @@
#include "utils/feature_counter.h"
#include "utils/hashset_utils.h"
#include "vector/vector_common.h"
#include "vector/vector_configs.h"
#include "vector/vector_spec.h"
#include "vector/vector_utilities.h"
#include "api_hooks.h"
@@ -77,7 +78,13 @@ typedef struct
/* --------------------------------------------------------- */
/* Forward declaration */
/* --------------------------------------------------------- */
static void AddSearchParamFunctionToQuery(Query *query, Oid accessMethodOid,
static bool IsPgvectorIterativeScanAvailable();
static pgbson * SetIterativeScanToSearchParam(pgbson *searchParamPgbson);
static char * GetVectorIterativeScanModeName(VectorIterativeScanMode iterativeScanMode);
static void AddSearchParamFunctionToQuery(Query *query,
pgbson *searchParamPgbson);
static Expr * AddScoreFieldToDocumentEntry(TargetEntry *documentEntry,
@@ -89,9 +96,7 @@ static TargetEntry * AddCtidToQueryTargetList(Query *query,
static Query * JoinVectorSearchQueryWithFilterQuery(Query *leftQuery, Query *rightQuery,
TargetEntry *leftJoinEntry,
TargetEntry *rightJoinEntry,
const TargetEntry *sortEntry,
bool needsReordering);
TargetEntry *rightJoinEntry);
static void AddPathStringToHashset(List *indexIdList, HTAB *stringHashSet);
@@ -341,6 +346,69 @@ HandleMongoNativeVectorSearch(const bson_value_t *existingValue, Query *query,
/* Private methods */
/* --------------------------------------------------------- */
/*
* The pgvector iterative scan is available from 0.8.0,
*/
static bool
IsPgvectorIterativeScanAvailable()
{
/* array_to_sparsevec function is introduced in 0.8.0 */
/* so we can check the function is available or not to indicate the iterative scan is available */
bool missingOK = true;
return OidIsValid(PgDoubleToSparseVecFunctionOid(missingOK));
}
static pgbson *
SetIterativeScanToSearchParam(pgbson *searchParamPgbson)
{
if (!IsPgvectorIterativeScanAvailable())
{
return searchParamPgbson;
}
pgbson_writer docWriter;
PgbsonWriterInit(&docWriter);
if (searchParamPgbson != NULL)
{
PgbsonWriterConcat(&docWriter, searchParamPgbson);
}
PgbsonWriterAppendUtf8(&docWriter,
VECTOR_PARAMETER_NAME_ITERATIVE_SCAN,
VECTOR_PARAMETER_NAME_ITERATIVE_SCAN_STR_LEN,
GetVectorIterativeScanModeName(
VectorPreFilterIterativeScanMode));
return PgbsonWriterGetPgbson(&docWriter);
}
static char *
GetVectorIterativeScanModeName(VectorIterativeScanMode iterativeScanMode)
{
switch (iterativeScanMode)
{
case VectorIterativeScan_RELAXED_ORDER:
{
return "relaxed_order";
}
case VectorIterativeScan_STRICT_ORDER:
{
return "strict_order";
}
case VectorIterativeScan_OFF:
default:
{
break;
}
}
return "off";
}
/*
* Adds a wrapper function(bson_search_param) which includes the search parameters to the query.
@@ -348,14 +416,13 @@ HandleMongoNativeVectorSearch(const bson_value_t *existingValue, Query *query,
* In custom scan, we will dynamically calculate search param depend on the number of vectors in the collection.
*
* The example of the search param:
* ivfflat: { "nProbes": 4 }
* hnsw: { "efSearch": 16 }
* ivfflat: { "nProbes": 4, "iterativeScan": "strict_order"}
* hnsw: { "efSearch": 16, "iterativeScan": "relaxed_order" }
* e.g.
* WHERE bson_search_param(document, { "nProbes": 4 }) or WHERE bson_search_param(document, { "efSearch": 16 })
*/
static void
AddSearchParamFunctionToQuery(Query *query, Oid accessMethodOid,
pgbson *searchParamPgbson)
AddSearchParamFunctionToQuery(Query *query, pgbson *searchParamPgbson)
{
if (searchParamPgbson != NULL)
{
@@ -431,9 +498,7 @@ AddCtidToQueryTargetList(Query *query, bool replaceTargetList)
static Query *
JoinVectorSearchQueryWithFilterQuery(Query *leftQuery, Query *rightQuery,
TargetEntry *leftJoinEntry,
TargetEntry *rightJoinEntry,
const TargetEntry *sortEntry,
bool needsReordering)
TargetEntry *rightJoinEntry)
{
Query *finalQuery = makeNode(Query);
finalQuery->commandType = CMD_SELECT;
@@ -637,20 +702,20 @@ AddScoreFieldToDocumentEntry(TargetEntry *documentEntry, Expr *vectorSortExpr,
};
/* Use expression_tree_mutator so we copy the orderby Expr before changing it */
Expr *scoreExprInput = (Expr *) expression_tree_mutator((Node *) vectorSortExpr,
ReplaceDocumentVarOnSort,
&sortContext);
Expr *sortExprInput = (Expr *) expression_tree_mutator((Node *) vectorSortExpr,
ReplaceDocumentVarOnSort,
&sortContext);
/* For half vector index, we need to use full vector to re-calculate the score */
List *orderArgs = NIL;
if (IsA(scoreExprInput, OpExpr))
if (IsA(sortExprInput, OpExpr))
{
OpExpr *orderOpExpr = (OpExpr *) scoreExprInput;
OpExpr *orderOpExpr = (OpExpr *) sortExprInput;
orderArgs = orderOpExpr->args;
}
else if (IsA(scoreExprInput, FuncExpr))
else if (IsA(sortExprInput, FuncExpr))
{
FuncExpr *orderFuncExpr = (FuncExpr *) scoreExprInput;
FuncExpr *orderFuncExpr = (FuncExpr *) sortExprInput;
orderArgs = orderFuncExpr->args;
}
else
@@ -693,22 +758,22 @@ AddScoreFieldToDocumentEntry(TargetEntry *documentEntry, Expr *vectorSortExpr,
"unknown vector search operator type")));
}
if (IsA(scoreExprInput, FuncExpr))
if (IsA(sortExprInput, FuncExpr))
{
FuncExpr *orderFuncExpr = (FuncExpr *) scoreExprInput;
FuncExpr *orderFuncExpr = (FuncExpr *) sortExprInput;
orderFuncExpr->funcid = get_opcode(similarityOpOid);
orderFuncExpr->args = newArgs;
}
else /* OpExpr */
{
OpExpr *orderOpExpr = (OpExpr *) scoreExprInput;
OpExpr *orderOpExpr = (OpExpr *) sortExprInput;
orderOpExpr->opno = similarityOpOid;
orderOpExpr->args = newArgs;
}
}
/* Add the score field to the document */
Expr *scoreExpr = GenerateScoreExpr((Expr *) scoreExprInput, distanceMetric);
Expr *scoreExpr = GenerateScoreExpr((Expr *) sortExprInput, distanceMetric);
List *args = list_make2(documentEntry->expr, scoreExpr);
FuncExpr *resultExpr = makeFuncExpr(
@@ -717,7 +782,7 @@ AddScoreFieldToDocumentEntry(TargetEntry *documentEntry, Expr *vectorSortExpr,
documentEntry->expr = (Expr *) resultExpr;
return scoreExprInput;
return sortExprInput;
}
@@ -1071,16 +1136,12 @@ GeneratePrefilteringVectorSearchQuery(Query *searchQuery,
Query *joinedQuery = JoinVectorSearchQueryWithFilterQuery(searchQuery,
filterQuery,
leftCtidEntry,
rightCtidEntry,
sortEntry,
vectorSearchOptions->
vectorIndexDef->
needsReorderAfterFilter);
rightCtidEntry);
/* Add the limit to the sub-query */
joinedQuery->limitCount = limitCount;
if (vectorSearchOptions->vectorIndexDef->needsReorderAfterFilter &&
if (VectorPreFilterIterativeScanMode == VectorIterativeScan_RELAXED_ORDER &&
vectorSearchOptions->compressionType == VectorIndexCompressionType_None)
{
/* Search result by iterative search may be disordered, so we need to reorder the result */
@@ -1464,8 +1525,17 @@ HandleVectorSearchCore(Query *query, VectorSearchOptions *vectorSearchOptions,
/* Create the WHERE bson_search_param(document, searchParamPgbson) and add it to the WHERE */
if (!vectorSearchOptions->exactSearch)
{
AddSearchParamFunctionToQuery(query, vectorSearchOptions->vectorAccessMethodOid,
vectorSearchOptions->searchParamPgbson);
/* set iterative parameter for filtering */
/* e.g. Search param: { "iterativeScan": "relaxed_order" } */
bson_value_t filterBson = vectorSearchOptions->filterBson;
if (filterBson.value_type != BSON_TYPE_EOD &&
!IsBsonValueEmptyDocument(&filterBson))
{
vectorSearchOptions->searchParamPgbson = SetIterativeScanToSearchParam(
vectorSearchOptions->searchParamPgbson);
}
AddSearchParamFunctionToQuery(query, vectorSearchOptions->searchParamPgbson);
}
else
{
@@ -1515,7 +1585,7 @@ HandleVectorSearchCore(Query *query, VectorSearchOptions *vectorSearchOptions,
false,
true);
Expr *scoreExpr = NULL;
Expr *sortExpr = NULL;
/* If there's a filter, add it to the query */
if (EnableVectorPreFilterV2 &&
@@ -1547,10 +1617,10 @@ HandleVectorSearchCore(Query *query, VectorSearchOptions *vectorSearchOptions,
* matching the filter.
*/
TargetEntry *documentEntry = linitial(query->targetList);
scoreExpr = AddScoreFieldToDocumentEntry(documentEntry, sortEntry->expr,
vectorSearchOptions->distanceMetric);
sortExpr = AddScoreFieldToDocumentEntry(documentEntry, sortEntry->expr,
vectorSearchOptions->distanceMetric);
TargetEntry *scoreEntry = makeTargetEntry(scoreExpr, 2, "sortVal", false);
TargetEntry *scoreEntry = makeTargetEntry(sortExpr, 2, "sortVal", false);
query->targetList = lappend(query->targetList, scoreEntry);
/* now reorder to ensure it matches the score order by */
@@ -1579,8 +1649,8 @@ HandleVectorSearchCore(Query *query, VectorSearchOptions *vectorSearchOptions,
/* Add the score field */
TargetEntry *documentEntry = linitial(query->targetList);
scoreExpr = AddScoreFieldToDocumentEntry(documentEntry, sortEntry->expr,
vectorSearchOptions->distanceMetric);
sortExpr = AddScoreFieldToDocumentEntry(documentEntry, sortEntry->expr,
vectorSearchOptions->distanceMetric);
}
else
{
@@ -1592,18 +1662,18 @@ HandleVectorSearchCore(Query *query, VectorSearchOptions *vectorSearchOptions,
/* Add the score field */
TargetEntry *documentEntry = linitial(query->targetList);
scoreExpr = AddScoreFieldToDocumentEntry(documentEntry, sortEntry->expr,
vectorSearchOptions->distanceMetric);
sortExpr = AddScoreFieldToDocumentEntry(documentEntry, sortEntry->expr,
vectorSearchOptions->distanceMetric);
}
/* Reorder for the compression index */
if (vectorSearchOptions->compressionType != VectorIndexCompressionType_None &&
scoreExpr != NULL &&
sortExpr != NULL &&
vectorSearchOptions->exactSearch == false)
{
/* reorder the results by the full vector distance */
/* Exact search doesn't need to reorder */
query = ReorderResultsForCompression(query, context, scoreExpr);
query = ReorderResultsForCompression(query, context, sortExpr);
}
/* Add k limit to the top level query if oversampling is specified */
@@ -13,12 +13,22 @@
#include <utils/guc.h>
#include <limits.h>
#include "configs/config_initialization.h"
#include "vector/vector_configs.h"
/*
* Externally defined GUC constants
* TODO(OSS): Move these as appropriate.
*/
/* Enum values for iterative scan mode */
static const struct config_enum_entry VECTOR_ITERATIVE_SCAN_OPTIONS[] =
{
{ "off", VectorIterativeScan_OFF, false },
{ "relaxed_order", VectorIterativeScan_RELAXED_ORDER, false },
{ "strict_order", VectorIterativeScan_STRICT_ORDER, false },
{ NULL, 0, false }
};
/*
* enable_create_collection_on_insert GUC determines whether
* an insert into a non-existent collection should create a collection.
@@ -109,6 +119,9 @@ int MaxAggregationStagesAllowed = DEFAULT_AGGREGATION_STAGES_LIMIT;
#define DEFAULT_INDEX_TERM_COMPRESSION_THRESHOLD INT_MAX
int IndexTermCompressionThreshold = DEFAULT_INDEX_TERM_COMPRESSION_THRESHOLD;
#define DEFAULT_VECTOR_ITERATIVE_SCAN_MODE VectorIterativeScan_RELAXED_ORDER
int VectorPreFilterIterativeScanMode = DEFAULT_VECTOR_ITERATIVE_SCAN_MODE;
void
InitializeSystemConfigurations(const char *prefix, const char *newGucPrefix)
{
@@ -317,4 +330,14 @@ InitializeSystemConfigurations(const char *prefix, const char *newGucPrefix)
DEFAULT_INDEX_TERM_COMPRESSION_THRESHOLD, 256,
INT_MAX,
PGC_USERSET, 0, NULL, NULL, NULL);
DefineCustomEnumVariable(
psprintf("%s.vectorPreFilterIterativeScanMode", newGucPrefix),
gettext_noop(
"Set the iterative scan mode for vector pre-filtering. "
"Relaxed order allows results to be slightly out of order by distance, but provides better recall. "
"Strict order ensures results are in the exact order by distance"),
NULL, &VectorPreFilterIterativeScanMode, DEFAULT_VECTOR_ITERATIVE_SCAN_MODE,
VECTOR_ITERATIVE_SCAN_OPTIONS,
PGC_USERSET, 0, NULL, NULL, NULL);
}
@@ -191,26 +191,17 @@ AddExtensionQueryScanForVectorQuery(PlannerInfo *root, RelOptInfo *rel,
inputState->querySearchData = *searchQueryData;
inputState->hasVectorSearchData = true;
if (EnableVectorPreFilter)
{
bool failIfNotFound = true;
rel->pathlist = AddCustomPathForVectorCore(root, rel->pathlist, rel, inputState,
failIfNotFound);
bool failIfNotFound = true;
rel->pathlist = AddCustomPathForVectorCore(root, rel->pathlist, rel, inputState,
failIfNotFound);
if (rel->partial_pathlist != NIL)
{
failIfNotFound = false;
rel->partial_pathlist = AddCustomPathForVectorCore(root,
rel->partial_pathlist, rel,
inputState,
failIfNotFound);
}
}
else
if (rel->partial_pathlist != NIL)
{
TrySetDefaultSearchParamForCustomScan(&(inputState->querySearchData));
rel->pathlist = AddCustomPathCore(rel->pathlist, inputState);
rel->partial_pathlist = AddCustomPathCore(rel->partial_pathlist, inputState);
failIfNotFound = false;
rel->partial_pathlist = AddCustomPathForVectorCore(root,
rel->partial_pathlist, rel,
inputState,
failIfNotFound);
}
}
@@ -351,14 +342,14 @@ AddCustomPathForVectorCore(PlannerInfo *planner, List *pathList, RelOptInfo *rel
searchBson = DatumGetPgBson(queryState->querySearchData.SearchParamBson);
}
if (searchBson == NULL || IsPgbsonEmptyDocument(searchBson))
{
IndexPath *indexPath = (IndexPath *) vectorSearchPath;
pgbson *defaultSearchParam = CalculateSearchParamBsonForIndexPath(indexPath);
queryState->querySearchData.SearchParamBson = PointerGetDatum(defaultSearchParam);
}
/* For normal vector search, if the search param is not specified, searchBson will be NULL
* For filtering vector search, if the search param is not specified, searchBson contains the iterative param
* We let index specific handler to decide if the default search param is needed or not
*/
IndexPath *indexPath = (IndexPath *) vectorSearchPath;
pgbson *defaultSearchParam = CalculateSearchParamBsonForIndexPath(indexPath,
searchBson);
queryState->querySearchData.SearchParamBson = PointerGetDatum(defaultSearchParam);
/* wrap the path in a custom path */
CustomPath *customPath = makeNode(CustomPath);
@@ -598,6 +598,9 @@ typedef struct DocumentDBApiOidCacheData
/* OID of the array_to_vector function. */
Oid PgDoubleToVectorFunctionOid;
/* OID of the array_to_sparsevec function. */
Oid PgDoubleToSparseVecFunctionOid;
/* OID of the vector as vector Cast function */
Oid VectorAsVectorFunctionOid;
@@ -2776,6 +2779,32 @@ PgDoubleToVectorFunctionOid(void)
}
/*
* Returns the function Oid for converting a double[] to a sparse vector specifically the array_to_sparsevec function.
* Note: the array_to_sparsevec function is introduced in pgvector 0.8.0,
* Currently it is only used for checking if the version of pgvector is 0.8.0
* Set missingOK to true, this function will return InvalidOid if the pgvector version is lower than that.
*/
Oid
PgDoubleToSparseVecFunctionOid(bool missingOK)
{
InitializeDocumentDBApiExtensionCache();
if (Cache.PgDoubleToSparseVecFunctionOid == InvalidOid)
{
List *functionNameList = list_make2(makeString("public"),
makeString("array_to_sparsevec"));
Oid paramOids[3] = { FLOAT8ARRAYOID, INT4OID, BOOLOID };
Cache.PgDoubleToSparseVecFunctionOid =
LookupFuncName(functionNameList, 3, paramOids, missingOK);
}
return Cache.PgDoubleToSparseVecFunctionOid;
}
/*
* VectorAsVectorFunctionOid returns the OID of the vector as vector cast function.
*/
@@ -28,6 +28,7 @@
#include "utils/feature_counter.h"
#include "vector/vector_common.h"
#include "vector/vector_spec.h"
#include "vector/vector_utilities.h"
/* --------------------------------------------------------- */
@@ -90,13 +91,11 @@ static void SetIVFSearchParametersToGUC(const pgbson *searchParamBson);
static void SetHNSWSearchParametersToGUC(const pgbson *searchParamBson);
static pgbson * GetIVFDefaultSearchParamBson(void);
static pgbson * CalculateIVFSearchParamBson(bytea *indexOptions, Cardinality indexRows,
pgbson *searchParamBson);
static pgbson * GetHNSWDefaultSearchParamBson(void);
static pgbson * CalculateIVFSearchParamBson(bytea *indexOptions, Cardinality indexRows);
static pgbson * CalculateHNSWSearchParamBson(bytea *indexOptions, Cardinality indexRows);
static pgbson * CalculateHNSWSearchParamBson(bytea *indexOptions, Cardinality indexRows,
pgbson *searchParamBson);
static VectorIndexCompressionType ExtractIVFCompressionType(bytea *indexOptions);
@@ -110,26 +109,22 @@ static VectorIndexDefinition VectorIndexDefinitionArray[] = {
{
.kindName = "vector-ivf",
.indexAccessMethodName = "ivfflat",
.needsReorderAfterFilter = false,
.parseIndexCreationSpecFunc = &ParseIVFCreationSpec,
.generateIndexParamStrFunc = &GenerateIVFIndexParamStr,
.parseIndexSearchSpecFunc = &ParseIVFIndexSearchSpec,
.getIndexAccessMethodOidFunc = &PgVectorIvfFlatIndexAmId,
.setSearchParametersToGUCFunc = &SetIVFSearchParametersToGUC,
.getDefaultSearchParamBsonFunc = &GetIVFDefaultSearchParamBson,
.calculateSearchParamBsonFunc = &CalculateIVFSearchParamBson,
.extractIndexCompressionTypeFunc = &ExtractIVFCompressionType
},
{
.kindName = "vector-hnsw",
.indexAccessMethodName = "hnsw",
.needsReorderAfterFilter = false,
.parseIndexCreationSpecFunc = &ParseHNSWCreationSpec,
.generateIndexParamStrFunc = &GenerateHNSWIndexParamStr,
.parseIndexSearchSpecFunc = &ParseHNSWIndexSearchSpec,
.getIndexAccessMethodOidFunc = &PgVectorHNSWIndexAmId,
.setSearchParametersToGUCFunc = &SetHNSWSearchParametersToGUC,
.getDefaultSearchParamBsonFunc = &GetHNSWDefaultSearchParamBson,
.calculateSearchParamBsonFunc = &CalculateHNSWSearchParamBson,
.extractIndexCompressionTypeFunc = &ExtractHNSWCompressionType
},
@@ -221,12 +216,6 @@ RegisterVectorIndexExtension(const VectorIndexDefinition *extensibleDefinition)
"setSearchParametersToGUCFunc is not defined for the vector index")));
}
if (extensibleDefinition->getDefaultSearchParamBsonFunc == NULL)
{
ereport(ERROR, (errmsg(
"getDefaultSearchParamBsonFunc is not defined for the vector index")));
}
if (extensibleDefinition->calculateSearchParamBsonFunc == NULL)
{
ereport(ERROR, (errmsg(
@@ -630,8 +619,19 @@ ParseHNSWIndexSearchSpec(const VectorSearchOptions *vectorSearchOptions)
/* Private methods */
/* --------------------------------------------------------- */
static pgbson *
CalculateIVFSearchParamBson(bytea *indexOptions, Cardinality indexRows)
CalculateIVFSearchParamBson(bytea *indexOptions, Cardinality indexRows,
pgbson *searchParamBson)
{
/* If the searchParamBson already has the nProbes */
bson_iter_t documentIterator;
if (searchParamBson != NULL &&
PgbsonInitIteratorAtPath(searchParamBson, VECTOR_PARAMETER_NAME_IVF_NPROBES,
&documentIterator))
{
return searchParamBson;
}
/* Calculate the default nProbes */
int numLists = -1;
if (indexOptions == NULL)
{
@@ -678,13 +678,29 @@ CalculateIVFSearchParamBson(bytea *indexOptions, Cardinality indexRows)
defaultNumProbes);
}
if (searchParamBson != NULL)
{
PgbsonWriterConcat(&optionsWriter, searchParamBson);
}
return PgbsonWriterGetPgbson(&optionsWriter);
}
static pgbson *
CalculateHNSWSearchParamBson(bytea *indexOptions, Cardinality indexRows)
CalculateHNSWSearchParamBson(bytea *indexOptions, Cardinality indexRows,
pgbson *searchParamBson)
{
/* If the searchParamBson already has the efSearch */
bson_iter_t documentIterator;
if (searchParamBson != NULL &&
PgbsonInitIteratorAtPath(searchParamBson, VECTOR_PARAMETER_NAME_HNSW_EF_SEARCH,
&documentIterator))
{
return searchParamBson;
}
/* Calculate the default efSearch */
int efConstruction = -1;
if (indexOptions == NULL)
@@ -724,6 +740,11 @@ CalculateHNSWSearchParamBson(bytea *indexOptions, Cardinality indexRows)
defaultEfSearch);
}
if (searchParamBson != NULL)
{
PgbsonWriterConcat(&optionsWriter, searchParamBson);
}
return PgbsonWriterGetPgbson(&optionsWriter);
}
@@ -736,6 +757,7 @@ SetIVFSearchParametersToGUC(const pgbson *searchParamBson)
while (bson_iter_next(&documentIterator))
{
const char *key = bson_iter_key(&documentIterator);
const bson_value_t *value = bson_iter_value(&documentIterator);
if (strcmp(key, VECTOR_PARAMETER_NAME_IVF_NPROBES) == 0)
{
int32_t nProbes = BsonValueAsInt32(bson_iter_value(
@@ -748,8 +770,31 @@ SetIVFSearchParametersToGUC(const pgbson *searchParamBson)
snprintf(nProbesStr, sizeof(nProbesStr), "%d",
nProbes);
SetGUCLocally("ivfflat.probes", nProbesStr);
}
else if (strcmp(key, VECTOR_PARAMETER_NAME_ITERATIVE_SCAN) == 0)
{
if (value->value_type == BSON_TYPE_UTF8)
{
/*
* set local ivfflat.iterative_scan=relaxed_order
* TODO: set pgvector GUCs for ivf iterative scan
* ivfflat.max_probes: Specify the max number of probes(32768 by default)
*/
const char *iterativeScanMode = value->value.v_utf8.str;
break;
/* The default of GUC VectorPreFilterIterativeScanMode is relaxed_order,
* in case we set it to strict_order, it is not supported for the ivf index, use relaxed_order instead
* this may cause the results to be slightly out of order */
if (strcmp(iterativeScanMode, "strict_order") == 0)
{
ereport(WARNING, errmsg(
"Iiterative_scan '%s' is not supported for ivf index, use relaxed_order instead, this may cause the results to be slightly out of order.",
iterativeScanMode));
iterativeScanMode = "relaxed_order";
}
SetGUCLocally("ivfflat.iterative_scan", iterativeScanMode);
}
}
}
}
@@ -763,10 +808,10 @@ SetHNSWSearchParametersToGUC(const pgbson *searchParamBson)
while (bson_iter_next(&documentIterator))
{
const char *key = bson_iter_key(&documentIterator);
const bson_value_t *value = bson_iter_value(&documentIterator);
if (strcmp(key, VECTOR_PARAMETER_NAME_HNSW_EF_SEARCH) == 0)
{
int32_t efSearch = BsonValueAsInt32(bson_iter_value(
&documentIterator));
int32_t efSearch = BsonValueAsInt32(value);
/*
* set efSearch to local GUC hnsw.ef_search
@@ -775,41 +820,24 @@ SetHNSWSearchParametersToGUC(const pgbson *searchParamBson)
snprintf(efSearchStr, sizeof(efSearchStr), "%d",
efSearch);
SetGUCLocally("hnsw.ef_search", efSearchStr);
break;
}
else if (strcmp(key, VECTOR_PARAMETER_NAME_ITERATIVE_SCAN) == 0)
{
if (value->value_type == BSON_TYPE_UTF8)
{
/*
* set local hnsw.iterative_scan=relaxed_order
* TODO: set pgvector GUCs for hnsw iterative scan
* hnsw.max_scan_tuples: Specify the max number of tuples to visit (20,000 by default)
* hnsw.scan_mem_multiplier: Specify the max amount of memory to use, as a multiple of work_mem (1 by default)
*/
SetGUCLocally("hnsw.iterative_scan", value->value.v_utf8.str);
}
}
}
}
static pgbson *
GetIVFDefaultSearchParamBson(void)
{
pgbson_writer optionsWriter;
PgbsonWriterInit(&optionsWriter);
PgbsonWriterAppendInt32(&optionsWriter, VECTOR_PARAMETER_NAME_IVF_NPROBES,
VECTOR_PARAMETER_NAME_IVF_NPROBES_STR_LEN,
IVFFLAT_DEFAULT_NPROBES);
return PgbsonWriterGetPgbson(&optionsWriter);
}
static pgbson *
GetHNSWDefaultSearchParamBson(void)
{
pgbson_writer optionsWriter;
PgbsonWriterInit(&optionsWriter);
PgbsonWriterAppendInt32(&optionsWriter, VECTOR_PARAMETER_NAME_HNSW_EF_SEARCH,
VECTOR_PARAMETER_NAME_HNSW_EF_SEARCH_STR_LEN,
HNSW_DEFAULT_EF_SEARCH);
return PgbsonWriterGetPgbson(&optionsWriter);
}
static VectorIndexCompressionType
ExtractIVFCompressionType(bytea *indexOptions)
{
+3 -28
View File
@@ -25,6 +25,7 @@
#include "metadata/metadata_cache.h"
#include "vector/bson_extract_vector.h"
#include "vector/vector_common.h"
#include "vector/vector_configs.h"
#include "vector/vector_planner.h"
#include "vector/vector_utilities.h"
#include "vector/vector_spec.h"
@@ -100,11 +101,10 @@ EvaluateMetaSearchScore(pgbson *document)
* b. If the number of rows is greater than 10K, the default efSearch is HNSW_DEFAULT_EF_SEARCH.
*/
pgbson *
CalculateSearchParamBsonForIndexPath(IndexPath *vectorSearchPath)
CalculateSearchParamBsonForIndexPath(IndexPath *vectorSearchPath, pgbson *searchParamBson)
{
IndexPath *indexPath = (IndexPath *) vectorSearchPath;
Oid indexRelam = indexPath->indexinfo->relam;
pgbson *searchParamBson = NULL;
/* Get rows in the index */
Cardinality indexRows = indexPath->indexinfo->tuples;
@@ -122,7 +122,7 @@ CalculateSearchParamBsonForIndexPath(IndexPath *vectorSearchPath)
if (indexRelation->rd_options != NULL)
{
searchParamBson = definition->calculateSearchParamBsonFunc(
indexRelation->rd_options, indexRows);
indexRelation->rd_options, indexRows, searchParamBson);
}
RelationClose(indexRelation);
@@ -422,31 +422,6 @@ SetSearchParametersToGUC(Oid vectorAccessMethodOid, pgbson *searchParamBson)
}
/*
* This function set the default search parameters to inputState if the user did not specify
*/
void
TrySetDefaultSearchParamForCustomScan(SearchQueryEvalData *querySearchData)
{
pgbson *searchInput = NULL;
if (querySearchData->SearchParamBson != (Datum) 0)
{
searchInput = DatumGetPgBson(querySearchData->SearchParamBson);
}
if (searchInput == NULL || IsPgbsonEmptyDocument(searchInput))
{
const VectorIndexDefinition *definition = GetVectorIndexDefinitionByIndexAmOid(
querySearchData->VectorAccessMethodOid);
if (definition != NULL)
{
querySearchData->SearchParamBson = PointerGetDatum(
definition->getDefaultSearchParamBsonFunc());
}
}
}
/*
* This function returns the full vector operator id for the given distance metric.
*/