From f1c7494c35ad9ad7c3790398bd7b8be14c460380 Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Sat, 21 Sep 2024 22:56:03 -0700 Subject: [PATCH] Added sorting [skip ci] --- src/hnswscan.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/hnswscan.c b/src/hnswscan.c index 287341c..a334cb0 100644 --- a/src/hnswscan.c +++ b/src/hnswscan.c @@ -141,6 +141,24 @@ hnswrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int no memmove(scan->orderByData, orderbys, scan->numberOfOrderBys * sizeof(ScanKeyData)); } +/* + * Compare search candidate distances + */ +static int +CompareSearchCandidateDistances(const ListCell *a, const ListCell *b) +{ + HnswSearchCandidate *hca = lfirst(a); + HnswSearchCandidate *hcb = lfirst(b); + + if (hca->distance < hcb->distance) + return 1; + + if (hca->distance > hcb->distance) + return -1; + + return 0; +} + /* * Fetch the next tuple in the given scan */ @@ -216,10 +234,12 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir) break; } - /* Return remaining tuples and exit */ - /* TODO sort */ + /* Return remaining tuples */ so->w = so->discarded; so->discarded = NIL; + + /* Sort in reverse order since results are removed from end */ + list_sort(so->w, CompareSearchCandidateDistances); } else { @@ -245,6 +265,8 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir) hc = llast(so->w); element = HnswPtrAccess(base, hc->element); + elog(INFO, "distance = %f", hc->distance); + /* Move to next element if no valid heap TIDs */ if (element->heaptidsLength == 0) {