pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feed[pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
15+ messages / 5 participants
[nested] [flat]
* [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-04-18 13:44 "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
0 siblings, 0 replies; 15+ messages in thread
From: VladlenPopolitov (@VladlenPopolitov) @ 2024-04-18 13:44 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
The current state: pgvector uses HNSW algorithm, that returns k-TOP nearest neighbours. If SQL query has WHERE clause, k-TOP neighbours could not satisfy the filter condition, and the query does not return any records.
The proposal: I propose to add an option in HNSW search to use the relaxed monotonicity proposed in the article https://www.usenix.org/system/files/osdi23-zhang-qianxi_1.pdf . The implementation does not affect the index build, it changes the greedy search algorithm only. If SQL query does not have WHERE clause, user could use standard greedy search (less overhead, more quick). If SQL query has WHERE clause (and even does not have), the user could use relaxed monotonicity algorithm (higher recall guaranteed). This choice is implemented by GUC variable easily.
In the proposed pull request the option is activated by setting `SET hnsw.use_relaxed=ON` . When this option is activated, HNSW returns nearest vectors until needed records are found using Open-Next interface, instead of efSearch-TOP records in the standard implementation. If `hnsw.use_relaxed=OFF` (default), HNSW behaves as usual.
Changes:
hnsw.c: PostgreSQL variable `hnsw.use_relaxed` and corresponding C variable `bool hnsw_use_relaxed` are added.
hnsw.h: Open-Next interface requires to store the search state between gettuple() calls, this state is stored in the members fields of the `struct HnswScanOpaqueData`
hnswscan.c: gettuple() was modified. If `hnsw.use_relaxed=ON` , it calls function OpenScanItemsRelaxed() instead of GetScanItems(), then it call NextScanItemsRelaxed() to get a next tuple.
hnswutils.c : HnswSearchLayerRelaxedNext(), HnswVisitedRelaxedNext() , HnswSearchLayerRelaxed() , NextScanItemsRelaxed() are added to implement Open-Next interface for greedy search.
tests/sql/hnsw_relaxed.sql and tests/expected/hnsw_relaxed.out added to check the work of HNSW search with and without hnsw.use_relaxed option. These files contain also the tests from hnsw_vector_l2 and hnsw_vector_ip to ensure the standard test execution, when the option in ON.
README.md was NOT updated until final commit (GUC variable names could be changed or added, comments are expected)
The example to demonstrate, that pgvector can work with WHERE condition using hnsw.use_relaxed option:
```SQL
SELECT t,
Array[t,t+1,t+2]::vector(3) AS val
INTO test_where
FROM generate_series(1, 2000) as t;
SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
t
------
1501
1502
(2 rows)
CREATE INDEX ON test_where USING hnsw (val vector_l2_ops) WITH (m=10);
set hnsw.use_relaxed=off;
set hnsw.ef_search=100;
SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
t
---
(0 rows)
set hnsw.use_relaxed=on;
SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
t
------
1501
1502
(2 rows)
```
ANN-benchmark without WHERE (see picture) condition in query shows the decrease the query per seconds rate (additional overhead to support Next interface), that in many cases compensated by increase of the recall (more vectors in the index are checked). Taking into consideration WHERE condition, pgvector with hnsw.use_relaxed option has superior recall comparing to standard HNSW implementation of all programs.
I am open for comments and discussions regarding this pull request.
Vladlen Popolitov.

inline patch 1: src/hnsw.c, src/hnsw.h, src/hnswscan.c and 3 more (+548/-20 lines) download inline-1.patch
diff --git a/src/hnsw.c b/src/hnsw.c
index a7b1e5fcc..1a7bf06f6 100644
--- a/src/hnsw.c
+++ b/src/hnsw.c
@@ -20,6 +20,7 @@
int hnsw_ef_search;
int hnsw_lock_tranche_id;
static relopt_kind hnsw_relopt_kind;
+bool hnsw_use_relaxed;
/*
* Assign a tranche ID for our LWLocks. This only needs to be done by one
@@ -67,6 +68,9 @@ HnswInit(void)
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
"Valid range is 1..1000.", &hnsw_ef_search,
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, 0, NULL, NULL, NULL);
+ DefineCustomBoolVariable("hnsw.use_relaxed", "Sets the flag to use Relaxed monotonicity algorithm during search",
+ "Valid values are ON, OFF, FALSE, TRUE.", &hnsw_use_relaxed,
+ false, PGC_USERSET, 0, NULL, NULL, NULL);
MarkGUCPrefixReserved("hnsw");
}
diff --git a/src/hnsw.h b/src/hnsw.h
index 2f4503905..62132d235 100644
--- a/src/hnsw.h
+++ b/src/hnsw.h
@@ -107,6 +107,7 @@
/* Variables */
extern int hnsw_ef_search;
extern int hnsw_lock_tranche_id;
+extern bool hnsw_use_relaxed;
typedef struct HnswElementData HnswElementData;
typedef struct HnswNeighborArray HnswNeighborArray;
@@ -324,6 +325,12 @@ typedef struct HnswNeighborTupleData
typedef HnswNeighborTupleData * HnswNeighborTuple;
+typedef struct HnswNextElement
+{
+ HnswCandidate *nextFromVisited,
+ *nextFromSearch;
+} HnswNextElement;
+
typedef struct HnswScanOpaqueData
{
const HnswTypeInfo *typeInfo;
@@ -335,6 +342,14 @@ typedef struct HnswScanOpaqueData
FmgrInfo *procinfo;
FmgrInfo *normprocinfo;
Oid collation;
+ char *base;
+ Datum q;
+ int m;
+ pairingheap *allVisited,
+ *candidates;
+ void *visitedFlag;
+ bool use_relaxed;
+ HnswNextElement next;
} HnswScanOpaqueData;
typedef HnswScanOpaqueData * HnswScanOpaque;
@@ -375,6 +390,8 @@ Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
void HnswInitPage(Buffer buf, Page page);
void HnswInit(void);
List *HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement);
+bool HnswSearchLayerRelaxed(IndexScanDesc scan, List *ep, int ef);
+ItemPointerData NextScanItemsRelaxed(IndexScanDesc scan);
HnswElement HnswGetEntryPoint(Relation index);
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
void *HnswAlloc(HnswAllocator * allocator, Size size);
diff --git a/src/hnswscan.c b/src/hnswscan.c
index 0463a898c..5247e8ccd 100644
--- a/src/hnswscan.c
+++ b/src/hnswscan.c
@@ -40,6 +40,42 @@ GetScanItems(IndexScanDesc scan, Datum q)
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, procinfo, collation, m, false, NULL);
}
+/*
+ * Algorithm 5 from paper with Relaxed option
+ */
+static bool
+OpenScanItemsRelaxed(IndexScanDesc scan, Datum q)
+{
+ HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
+ Relation index = scan->indexRelation;
+ FmgrInfo *procinfo = so->procinfo;
+ Oid collation = so->collation;
+ List *ep;
+ List *w;
+ int m;
+ HnswElement entryPoint;
+ char *base = NULL;
+
+ /* Get m and entry point */
+ HnswGetMetaPageInfo(index, &m, &entryPoint);
+
+ if (entryPoint == NULL)
+ return false;
+
+ ep = list_make1(HnswEntryCandidate(base, entryPoint, q, index, procinfo, collation, false));
+
+ for (int lc = entryPoint->level; lc >= 1; lc--)
+ {
+ w = HnswSearchLayer(base, q, ep, 1, lc, index, procinfo, collation, m, false, NULL);
+ ep = w;
+ }
+ /* save values to use them in NextCalls */
+ so->base = base;
+ so->q = q;
+ so->m = m;
+ return HnswSearchLayerRelaxed(scan, ep, hnsw_ef_search);
+}
+
/*
* Get scan value
*/
@@ -152,8 +188,18 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
* before marking tuples as deleted.
*/
LockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
-
- so->w = GetScanItems(scan, value);
+ so->use_relaxed = hnsw_use_relaxed;
+ if (so->use_relaxed)
+ {
+ if (!OpenScanItemsRelaxed(scan, value))
+ {
+ return false;
+ }
+ }
+ else
+ {
+ so->w = GetScanItems(scan, value);
+ }
/* Release shared lock */
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
@@ -164,29 +210,49 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
elog(INFO, "memory: %zu MB", MemoryContextMemAllocated(so->tmpCtx, false) / (1024 * 1024));
#endif
}
-
- while (list_length(so->w) > 0)
+ if (!so->use_relaxed)
{
- char *base = NULL;
- HnswCandidate *hc = llast(so->w);
- HnswElement element = HnswPtrAccess(base, hc->element);
- ItemPointer heaptid;
-
- /* Move to next element if no valid heap TIDs */
- if (element->heaptidsLength == 0)
+ while (list_length(so->w) > 0)
{
- so->w = list_delete_last(so->w);
- continue;
+ char *base = NULL;
+ HnswCandidate *hc = llast(so->w);
+ HnswElement element = HnswPtrAccess(base, hc->element);
+ ItemPointer heaptid;
+
+ /* Move to next element if no valid heap TIDs */
+ if (element->heaptidsLength == 0)
+ {
+ so->w = list_delete_last(so->w);
+ continue;
+ }
+
+ heaptid = &element->heaptids[--element->heaptidsLength];
+
+ MemoryContextSwitchTo(oldCtx);
+
+ scan->xs_heaptid = *heaptid;
+ scan->xs_recheck = false;
+ scan->xs_recheckorderby = false;
+ return true;
}
+ }
+ else
+ {
+ ItemPointerData heaptiddata;
- heaptid = &element->heaptids[--element->heaptidsLength];
-
+ heaptiddata = NextScanItemsRelaxed(scan);
MemoryContextSwitchTo(oldCtx);
-
- scan->xs_heaptid = *heaptid;
- scan->xs_recheck = false;
- scan->xs_recheckorderby = false;
- return true;
+ if (ItemPointerIsValid(&heaptiddata))
+ {
+ scan->xs_heaptid = heaptiddata;
+ scan->xs_recheck = false;
+ scan->xs_recheckorderby = false;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
}
MemoryContextSwitchTo(oldCtx);
diff --git a/src/hnswutils.c b/src/hnswutils.c
index f69c057ad..0f133555b 100644
--- a/src/hnswutils.c
+++ b/src/hnswutils.c
@@ -14,6 +14,9 @@
#include "utils/datum.h"
#include "utils/memdebug.h"
#include "utils/rel.h"
+#include "utils/syscache.h"
+#include "access/relscan.h"
+#include "vector.h"
#if PG_VERSION_NUM < 170000
static inline uint64
@@ -1406,3 +1409,294 @@ hnsw_sparsevec_support(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(&typeInfo);
};
+
+/*
+ * Algorithm 2 from paper with adoptation from Relaxed monotonicity
+ */
+static HnswCandidate *
+HnswSearchLayerRelaxedNext(char *base, Datum q, Relation index,
+ FmgrInfo *procinfo, Oid collation, int m,
+ pairingheap *C, visited_hash * v)
+{
+ HnswNeighborArray *neighborhoodData = NULL;
+ Size neighborhoodSize;
+ HnswCandidate *c = NULL;
+
+ /* Create local memory for neighborhood if needed */
+ if (index == NULL)
+ {
+ neighborhoodSize = HNSW_NEIGHBOR_ARRAY_SIZE(HnswGetLayerM(m, 0));
+ neighborhoodData = palloc(neighborhoodSize);
+ }
+
+
+ if (!pairingheap_is_empty(C))
+ {
+ HnswNeighborArray *neighborhood;
+ HnswElement cElement;
+
+ c = HnswGetPairingHeapCandidate(c_node, pairingheap_remove_first(C));
+
+ cElement = HnswPtrAccess(base, c->element);
+
+ if (HnswPtrIsNull(base, cElement->neighbors))
+ HnswLoadNeighbors(cElement, index, m);
+
+ /* Get the neighborhood at layer lc */
+ neighborhood = HnswGetNeighbors(base, cElement, 0);
+
+ /* Copy neighborhood to local memory if needed */
+ if (index == NULL)
+ {
+ LWLockAcquire(&cElement->lock, LW_SHARED);
+ memcpy(neighborhoodData, neighborhood, neighborhoodSize);
+ LWLockRelease(&cElement->lock);
+ neighborhood = neighborhoodData;
+ }
+
+ for (int i = 0; i < neighborhood->length; i++)
+ {
+ HnswCandidate *e = &neighborhood->items[i];
+ bool visited;
+
+ AddToVisited(base, v, e->element, index, &visited);
+
+ if (!visited)
+ {
+ float eDistance;
+ HnswElement eElement = HnswPtrAccess(base, e->element);
+ HnswCandidate *ec;
+
+ if (index == NULL)
+ eDistance = GetElementDistance(base, e->element.ptr , q, procinfo, collation) ;
+ else
+ HnswLoadElement(eElement, &eDistance, &q, index, procinfo, collation, false, NULL);
+
+ Assert(!eElement->deleted);
+ ec = palloc(sizeof(HnswCandidate));
+
+ HnswPtrStore(base, ec->element, eElement);
+ ec->distance = eDistance;
+
+ pairingheap_add(C, &(CreatePairingHeapNode(ec)->c_node));
+ }
+ }
+ }
+ return c;
+}
+
+static HnswCandidate *
+HnswVisitedRelaxedNext(char *base, pairingheap *all_visited)
+{
+ while (!pairingheap_is_empty(all_visited))
+ {
+ HnswCandidate *candidate = HnswGetPairingHeapCandidate(c_node, pairingheap_remove_first(all_visited));
+ HnswElement element = HnswPtrAccess(base, candidate->element);
+
+ if (element->heaptidsLength > 0)
+ {
+ return candidate;
+ }
+ }
+ return NULL;
+}
+
+
+/*
+ * Algorithm 2 from paper with adoptation from Relaxed monotonicity
+ */
+bool
+HnswSearchLayerRelaxed(IndexScanDesc scan, List *ep, int ef)
+{
+ HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
+ Relation index = scan->indexRelation;
+ FmgrInfo *procinfo = so->procinfo;
+ Oid collation = so->collation;
+ char *base = so->base;
+ Datum q = so->q;
+ int m = so->m;
+ pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
+ pairingheap *W = pairingheap_allocate(CompareFurthestCandidates, NULL);
+ pairingheap *all_visited = pairingheap_allocate(CompareNearestCandidates, NULL);
+ int wlen = 0;
+ visited_hash *v = (visited_hash *) palloc(sizeof(visited_hash));
+ ListCell *lc2;
+ HnswNeighborArray *neighborhoodData = NULL;
+ Size neighborhoodSize;
+
+ InitVisited(base, v, index, ef, m);
+
+ /* Create local memory for neighborhood if needed */
+ if (index == NULL)
+ {
+ neighborhoodSize = HNSW_NEIGHBOR_ARRAY_SIZE(HnswGetLayerM(m, 0));
+ neighborhoodData = palloc(neighborhoodSize);
+ }
+
+ /* Add entry points to v, C, and W */
+ foreach(lc2, ep)
+ {
+ HnswCandidate *hc = (HnswCandidate *) lfirst(lc2);
+ bool found;
+
+ AddToVisited(base, v, hc->element, index, &found);
+
+ pairingheap_add(C, &(CreatePairingHeapNode(hc)->c_node));
+ pairingheap_add(W, &(CreatePairingHeapNode(hc)->w_node));
+ wlen++;
+ }
+
+ while (!pairingheap_is_empty(C))
+ {
+ HnswNeighborArray *neighborhood;
+ HnswCandidate *c = HnswGetPairingHeapCandidate(c_node, pairingheap_remove_first(C));
+ HnswCandidate *f = HnswGetPairingHeapCandidate(w_node, pairingheap_first(W));
+ HnswElement cElement;
+
+ cElement = HnswPtrAccess(base, c->element);
+
+ if (HnswPtrIsNull(base, cElement->neighbors))
+ HnswLoadNeighbors(cElement, index, m);
+
+ /* Get the neighborhood at layer 0 */
+ neighborhood = HnswGetNeighbors(base, cElement, 0);
+
+ /* Copy neighborhood to local memory if needed */
+ if (index == NULL)
+ {
+ LWLockAcquire(&cElement->lock, LW_SHARED);
+ memcpy(neighborhoodData, neighborhood, neighborhoodSize);
+ LWLockRelease(&cElement->lock);
+ neighborhood = neighborhoodData;
+ }
+
+ for (int i = 0; i < neighborhood->length; i++)
+ {
+ HnswCandidate *e = &neighborhood->items[i];
+ bool visited;
+
+ AddToVisited(base, v, e->element, index, &visited);
+
+ if (!visited)
+ {
+ float eDistance;
+ HnswElement eElement = HnswPtrAccess(base, e->element);
+ HnswCandidate *ec;
+
+ if (index == NULL)
+ eDistance = GetElementDistance(base, e->element.ptr , q, procinfo, collation);
+ else
+ HnswLoadElement(eElement, &eDistance, &q, index, procinfo, collation, false, NULL);
+
+ Assert(!eElement->deleted);
+ ec = palloc(sizeof(HnswCandidate));
+
+ HnswPtrStore(base, ec->element, eElement);
+ ec->distance = eDistance;
+
+ pairingheap_add(C, &(CreatePairingHeapNode(ec)->c_node));
+ }
+ }
+ pairingheap_add(all_visited, &(CreatePairingHeapNode(c)->c_node));
+
+/*
+ * Check the condition to exit the loop:
+ * 1) the best candidates queue (W) is full
+ * 2) the current candidate (c) distance is further than the furthest in W
+ * 3) the next candidate from candidate set (C) is further than the furthest in W or candidate set (C) is empty
+ */
+ if ((wlen == ef) &&
+ f->distance < c->distance &&
+ (pairingheap_is_empty(C) ||
+ (f->distance < HnswGetPairingHeapCandidate(c_node, pairingheap_first(C))->distance)
+ )
+ )
+ {
+ break;
+ }
+ if (wlen == ef)
+ {
+ HnswGetPairingHeapCandidate(w_node, pairingheap_remove_first(W));
+ wlen--;
+ }
+ pairingheap_add(W, &(CreatePairingHeapNode(c)->w_node));
+ wlen++;
+ }
+ /* save all variables stored search state */
+ so->next.nextFromSearch = HnswSearchLayerRelaxedNext(base, q, index, procinfo, collation, m, C, (visited_hash *) v);
+ so->next.nextFromVisited = HnswVisitedRelaxedNext(base, all_visited);
+ so->visitedFlag = v;
+ so->candidates = C;
+ so->allVisited = all_visited;
+ return true;
+}
+
+
+ItemPointerData
+NextScanItemsRelaxed(IndexScanDesc scan)
+{
+ HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
+ char *base = so->base;
+ Datum q = so->q;
+ Relation index = scan->indexRelation;
+ FmgrInfo *procinfo = so->procinfo;
+ Oid collation = so->collation;
+ int m = so->m;
+ pairingheap *C = so->candidates;
+ void *v = so->visitedFlag;
+ pairingheap *all_visited = so->allVisited;
+ HnswNextElement *next = &so->next;
+
+ ItemPointerData heaptid;
+
+ if (next->nextFromVisited && next->nextFromSearch)
+ {
+ if (next->nextFromVisited->distance < next->nextFromSearch->distance)
+ {
+ HnswElement element = HnswPtrAccess(base, next->nextFromVisited->element);
+
+ heaptid = element->heaptids[--element->heaptidsLength];
+ if (element->heaptidsLength == 0)
+ {
+ next->nextFromVisited = HnswVisitedRelaxedNext(base, all_visited);
+ }
+ }
+ else
+ {
+ HnswElement element = HnswPtrAccess(base, next->nextFromSearch->element);
+
+ heaptid = element->heaptids[--element->heaptidsLength];
+ if (element->heaptidsLength == 0)
+ {
+ next->nextFromSearch = HnswSearchLayerRelaxedNext(base, q, index, procinfo, collation, m, C, (visited_hash *) v);
+ }
+ }
+ }
+ else if (next->nextFromVisited)
+ {
+ HnswElement element = HnswPtrAccess(base, next->nextFromVisited->element);
+
+ heaptid = element->heaptids[--element->heaptidsLength];
+ if (element->heaptidsLength == 0)
+ {
+ next->nextFromVisited = HnswVisitedRelaxedNext(base, all_visited);
+ }
+ }
+ else if (next->nextFromSearch)
+ {
+ HnswElement element = HnswPtrAccess(base, next->nextFromSearch->element);
+
+ heaptid = element->heaptids[--element->heaptidsLength];
+ if (element->heaptidsLength == 0)
+ {
+ next->nextFromSearch = HnswSearchLayerRelaxedNext(base, q, index, procinfo, collation, m, C, (visited_hash *) v);
+ }
+ }
+ else
+ {
+ /* tid with ip_posid==0 is invalid */
+ ItemPointerSet(&heaptid, InvalidBlockNumber, 0);
+ }
+
+ return heaptid;
+}
diff --git a/test/expected/hnsw_relaxed.out b/test/expected/hnsw_relaxed.out
new file mode 100644
index 000000000..443d5d46e
--- /dev/null
+++ b/test/expected/hnsw_relaxed.out
@@ -0,0 +1,100 @@
+SELECT t,
+Array[t,t+1,t+2]::vector(3) AS val
+INTO test_where
+FROM generate_series(1, 2000) as t;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+ t
+------
+ 1501
+ 1502
+(2 rows)
+
+CREATE INDEX ON test_where USING hnsw (val vector_l2_ops) WITH (m=10);
+set hnsw.use_relaxed=off;
+set hnsw.ef_search=100;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+ t
+---
+(0 rows)
+
+set hnsw.use_relaxed=on;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+ t
+------
+ 1501
+ 1502
+(2 rows)
+
+SELECT t FROM test_where WHERE t>2000 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+ t
+---
+(0 rows)
+
+DELETE FROM test_where;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+ t
+---
+(0 rows)
+
+TRUNCATE test_where;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+ t
+---
+(0 rows)
+
+DROP TABLE test_where;
+SET enable_seqscan = off;
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val vector_l2_ops);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+ val
+---------
+ [1,2,3]
+ [1,2,4]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector)) t2;
+ count
+-------
+ 4
+(1 row)
+
+SELECT COUNT(*) FROM t;
+ count
+-------
+ 5
+(1 row)
+
+TRUNCATE t;
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+ val
+-----
+(0 rows)
+
+DROP TABLE t;
+SET enable_seqscan = off;
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val vector_ip_ops);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+ val
+---------
+ [1,2,4]
+ [1,2,3]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::vector)) t2;
+ count
+-------
+ 4
+(1 row)
+
+DROP TABLE t;
+set hnsw.use_relaxed=off;
diff --git a/test/sql/hnsw_relaxed.sql b/test/sql/hnsw_relaxed.sql
new file mode 100644
index 000000000..d19100869
--- /dev/null
+++ b/test/sql/hnsw_relaxed.sql
@@ -0,0 +1,47 @@
+SELECT t,
+Array[t,t+1,t+2]::vector(3) AS val
+INTO test_where
+FROM generate_series(1, 2000) as t;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+CREATE INDEX ON test_where USING hnsw (val vector_l2_ops) WITH (m=10);
+set hnsw.use_relaxed=off;
+set hnsw.ef_search=100;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+set hnsw.use_relaxed=on;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+SELECT t FROM test_where WHERE t>2000 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+DELETE FROM test_where;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+TRUNCATE test_where;
+SELECT t FROM test_where WHERE t>1500 ORDER BY val <-> '[1000.2,1000,1000.1]' LIMIT 2;
+DROP TABLE test_where;
+SET enable_seqscan = off;
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val vector_l2_ops);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector)) t2;
+SELECT COUNT(*) FROM t;
+
+TRUNCATE t;
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+
+DROP TABLE t;
+SET enable_seqscan = off;
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val vector_ip_ops);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::vector)) t2;
+
+DROP TABLE t;
+
+set hnsw.use_relaxed=off;
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-04-18 13:56 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: VladlenPopolitov (@VladlenPopolitov) @ 2024-04-18 13:56 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@VladlenPopolitov renamed this.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-04-18 15:49 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: jkatz (@jkatz) @ 2024-04-18 15:49 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
> ANN-benchmark without WHERE (see picture) condition in query shows the decrease the query per seconds rate (additional overhead to support Next interface), that in many cases compensated by increase of the recall (more vectors in the index are checked). Taking into consideration WHERE condition, pgvector with hnsw.use_relaxed option has superior recall comparing to standard HNSW implementation of all programs.
What dataset(s) was used to test the above? What were the PostgreSQL configurations and instance that it was run on.
Did you test the recall/performance on a dataset that specifically was testing the filters?
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-04-18 17:44 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: VladlenPopolitov (@VladlenPopolitov) @ 2024-04-18 17:44 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
1. The reason to make ANN-benchmark without WHERE is to ensure, that there is no significant performance degradation, that can kill this idea. I tested this idea on hnswlib library and did benchmark, that had similar results. After that I implemented it in pgvector code and checked in benchmark. Attached picture above has results from benchmark with lastfm dataset (run on MacBookPro M1). PostgreSQL 16.1, maintenance_work_mem 16Gb, shared_buffers 4Gb. lastfm data set on the server with AMD EPYC 9654(AVX256) has the similar results. Also I tested on datasets glove-100 and fashion-mnist: decrease of rate 0-10% with the increase of recall by 0-3% (as value). The increase of a recall is mentioned in the article.
2. Benchmark with WHERE was not used. The article discuss the dataset Recipes1M+, that needs the permission for usage, that is not suitable for open-source benchmarks. I think now, how to prepare standard datasets for benchmarks with WHERE based on the standard datasets from ANN-benchmarks (with equal, less, more conditions in WHERE clause). The benchmark with WHERE is relevant only for algorithms , that implement filtering. Algorithms without filtering will show very low recall. It is like 2 different generations, it is not fair to compare them.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-04-19 20:16 ` "ankane (@ankane)" <noreply+ankane@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: ankane (@ankane) @ 2024-04-19 20:16 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hi @VladlenPopolitov, thanks for the PR! I'm planning to focus on inline filtering after 0.7.0 (#508), so should have more thoughts then (it may take some time, so patience is appreciated). Iterative searching (like this or #282) seems promising, but I also want to explore other options.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-08-14 20:50 ` "jonahharris (@jonahharris)" <noreply+jonahharris@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: jonahharris (@jonahharris) @ 2024-08-14 20:50 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane @jkatz is there any reason this wasn't picked up? As @VladlenPopolitov mentioned, this performs substantially better when predicates are present, which is a pretty common case I've seen. I have a slightly cleaned-up version, but wanted to see what the status of this is before doing anything with it.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-08-14 21:14 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: jkatz (@jkatz) @ 2024-08-14 21:14 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@jonahharris We've collectively been doing a lot of research on filtering, and it's a very nuanced topic. I'm hoping to share my own findings soon.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-08-14 22:32 ` "jonahharris (@jonahharris)" <noreply+jonahharris@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: jonahharris (@jonahharris) @ 2024-08-14 22:32 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Cool. Moving closer to VBASE's approach would be good, IMO - but maybe there is newer research (aside from the vector/scalar hybrid variants directly incorporating scalars). Of the PG vector index implementations I've seen so far, none seem to do proper costing/selectivity in the filtering case.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-08-18 10:03 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: VladlenPopolitov (@VladlenPopolitov) @ 2024-08-18 10:03 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hi @ankane ! I did benchmarks for pgvector in standard mode and relaxed mode and found, that search results depends more on filters value distributrion, than search algorithms: there is no universal best search algorithm.
1) When there is no filter, standard pgvector slightly quicker, than relaxed (due to relaxed's overhead to store all visited vectors- I showed it on picture in pull request comment above)
2) When there is filter condition with ~2-10 values, relaxed algorithm becomes faster than standard (relaxed decreases speed with the remaining recall, standard increases efsearch to keep the same recall resulting higher speed decrease)

3) When filter has ~100 values relaxed drops speed keeping recall rate, standard drops recall to 1-10% and becomes unusable, it returns empty datasets instead of some not nearest vectors.

4) When filter has ~1000 values, standard returns almost always empty datasets, relaxed returns the same recall, but slower than table scan without index. In this situation usual btree index works very fast (quick filter and then distance calculation for filtered tuples from table).

5) When filter has ~1000 values and table is very big, then btree index also does not work. In this situation composite index can help, that naturally process filter conditions.
relaxed mode gives to users more options to search, when they need filters. Also I would point, that pgvectorscale also implemented similar algorithm, when results returned until filter conditions are satisfied and all records returned.
I think, maybe "relaxed" name is not properly explain the method, probably better is "stream".
I could update pull request to the current code base. It is also interesting, what are your findings regarding filtered search.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-09-11 16:09 ` "heathiviesyncro (@heathiviesyncro)" <noreply+heathiviesyncro@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: heathiviesyncro (@heathiviesyncro) @ 2024-09-11 16:09 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hello: Is it possible to get this branch updated to resolve the conflicts?
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-09-20 12:14 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: VladlenPopolitov (@VladlenPopolitov) @ 2024-09-20 12:14 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@heathiviesyncro pull request updated to the current master version.
I did benchmark to check the correct work (in addition to tests), it works on the same performance, but has post-filter capabilities as additional feature.

^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-09-22 20:03 ` "ankane (@ankane)" <noreply+ankane@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: ankane (@ankane) @ 2024-09-22 20:03 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hi @VladlenPopolitov, thanks for sharing the benchmarks, and sorry for not getting to this sooner.
I've been spending time on this area recently and think I've found an approach that works well with vacuuming (#678). Let me know if you have any feedback.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-09-30 18:19 ` "heathiviesyncro (@heathiviesyncro)" <noreply+heathiviesyncro@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: heathiviesyncro (@heathiviesyncro) @ 2024-09-30 18:19 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
> @heathiviesyncro pull request updated to the current master version. I did benchmark to check the correct work (in addition to tests), it works on the same performance, but has post-filter capabilities as additional feature. 
Thank you very much for getting this updated.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-10-30 22:36 ` "ankane (@ankane)" <noreply+ankane@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: ankane (@ankane) @ 2024-10-30 22:36 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane closed this.
^ permalink raw [nested|flat] 15+ messages in thread
* Re: [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity)
@ 2024-10-30 22:36 ` "ankane (@ankane)" <noreply+ankane@github.com>
13 siblings, 0 replies; 15+ messages in thread
From: ankane (@ankane) @ 2024-10-30 22:36 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
0.8.0 is now released, so closing this out.
Big thanks @VladlenPopolitov for helping move this feature forward (and finding the `TRUNCATE` crash).
^ permalink raw [nested|flat] 15+ messages in thread
end of thread, other threads:[~2024-10-30 22:36 UTC | newest]
Thread overview: 15+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-04-18 13:44 [pgvector/pgvector] PR #524: Add search option to better process queries with WHERE clause (relaxed monotonicity) "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
2024-04-18 13:56 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
2024-04-18 15:49 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-04-18 17:44 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
2024-04-19 20:16 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-08-14 20:50 ` "jonahharris (@jonahharris)" <noreply+jonahharris@github.com>
2024-08-14 21:14 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-08-14 22:32 ` "jonahharris (@jonahharris)" <noreply+jonahharris@github.com>
2024-08-18 10:03 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
2024-09-11 16:09 ` "heathiviesyncro (@heathiviesyncro)" <noreply+heathiviesyncro@github.com>
2024-09-20 12:14 ` "VladlenPopolitov (@VladlenPopolitov)" <noreply+VladlenPopolitov@github.com>
2024-09-22 20:03 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-09-30 18:19 ` "heathiviesyncro (@heathiviesyncro)" <noreply+heathiviesyncro@github.com>
2024-10-30 22:36 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-30 22:36 ` "ankane (@ankane)" <noreply+ankane@github.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox