Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Fix HNSW search RuntimeError when limit exceeds indexed element count (#1159)

Amir Fathi50ca7b2fde1c
diff --git a/src/python/txtai/ann/dense/hnsw.py b/src/python/txtai/ann/dense/hnsw.py
index 598b6b18..b10722fe 100644
--- a/src/python/txtai/ann/dense/hnsw.py
+++ b/src/python/txtai/ann/dense/hnsw.py
@@ -85,8 +85,8 @@ class HNSW(ANN):
if ef:
self.backend.set_ef(ef)
- # Run the query
- ids, distances = self.backend.knn_query(queries, k=limit)
+ # Run the query, clamp k to the current element count as hnswlib errors when k exceeds it
+ ids, distances = self.backend.knn_query(queries, k=min(limit, self.count()))
# Map results to [(id, score)]
results = []
diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.py
index bc39d649..11b6e3d2 100644
--- a/test/python/testann/testdense.py
+++ b/test/python/testann/testdense.py
@@ -196,6 +196,21 @@ class TestDense(unittest.TestCase):
# Test with custom settings
self.runTests("hnsw", {"hnsw": {"efconstruction": 100, "m": 4, "randomseed": 0, "efsearch": 5}})
+ def testHnswSearchLimitExceedsCount(self):
+ """
+ Test Hnswlib backend search when limit exceeds the indexed element count
+ """
+
+ data = np.random.rand(3, 240).astype(np.float32)
+ self.normalize(data)
+
+ ann = ANNFactory.create({"backend": "hnsw", "dimensions": 240})
+ ann.index(data)
+
+ # Query limit (10) exceeds the number of indexed elements (3), previously raised a RuntimeError
+ results = ann.search(data[0:1], 10)
+ self.assertEqual(len(results[0]), 3)
+
@unittest.skipIf(os.name == "nt", "Skip Milvus on Windows")
def testMilvus(self):
"""