faiss-haystack 3.0.1__tar.gz → 3.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [integrations/faiss-v3.1.0] - 2026-11-27
4
+
5
+ ### 🐛 Bug Fixes
6
+
7
+ - *(faiss)* Keep searching when filters drop the first candidates (#4323)
8
+
9
+
10
+ ## [integrations/faiss-v3.0.1] - 2026-11-09
11
+
12
+ ### 🐛 Bug Fixes
13
+
14
+ - *(faiss)* Don't leave orphaned vectors when a batch repeats a document ID (#4180)
15
+
16
+
3
17
  ## [integrations/faiss-v3.0.0] - 2026-10-16
4
18
 
5
19
  ### 🧪 Testing
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: faiss-haystack
3
- Version: 3.0.1
3
+ Version: 3.1.1
4
4
  Summary: An integration of FAISS (library for efficient similarity search of dense vectors) with Haystack
5
5
  Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/faiss#readme
6
6
  Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
@@ -145,12 +145,15 @@ class FAISSDocumentStore:
145
145
  if not documents:
146
146
  return 0
147
147
 
148
- # Check for duplicates first if policy is FAIL
148
+ # Check for duplicates first if policy is FAIL, including IDs repeated within this batch,
149
+ # so that a failing batch is rejected before anything is written
149
150
  if policy == DuplicatePolicy.FAIL:
151
+ batch_ids: set[str] = set()
150
152
  for doc in documents:
151
- if doc.id in self.documents:
153
+ if doc.id in self.documents or doc.id in batch_ids:
152
154
  msg = f"Document with id '{doc.id}' already exists."
153
155
  raise DuplicateDocumentError(msg)
156
+ batch_ids.add(doc.id)
154
157
 
155
158
  # Process documents. Pending vectors are keyed by document ID so that a later duplicate in the same
156
159
  # batch replaces the earlier one instead of leaving an orphaned vector in the FAISS index.
@@ -246,41 +249,45 @@ class FAISSDocumentStore:
246
249
  # Ensure embedding format
247
250
  query_vec = np.array([query_embedding], dtype="float32")
248
251
 
249
- # Search in FAISS
250
- # Valid strategy for pre-filtering vs post-filtering:
251
- # Since FAISS `IndexIDMap` doesn't support pre-filtering natively comfortably
252
- # without `RangeSearch` or specialized impls, we fetch more and filter post-retrieval.
253
-
252
+ # Filters are checked in Python on the documents, so they are applied to the FAISS hits (post-filtering).
253
+ # If too few of the fetched neighbours match the filters, search once more over the whole index, so matching
254
+ # documents further away are not missed. One full search is cheaper than growing k step by step: exhaustive
255
+ # indexes like "Flat" compare against every vector whatever k is, and each retry re-filters the same hits.
254
256
  fetch_k = top_k
255
257
  if filters:
256
- fetch_k = min(self.index.ntotal, top_k * 10) # Simple heuristic
258
+ fetch_k = min(self.index.ntotal, top_k * 10)
257
259
 
258
- distances, indices = self.index.search(query_vec, fetch_k)
260
+ while True:
261
+ distances, indices = self.index.search(query_vec, fetch_k)
259
262
 
260
- results = []
261
- for dist, int_id in zip(distances[0], indices[0], strict=False):
262
- if int_id == -1:
263
- continue
263
+ results = []
264
+ for dist, int_id in zip(distances[0], indices[0], strict=False):
265
+ if int_id == -1:
266
+ continue
264
267
 
265
- doc_id = self.id_map.get(int_id)
266
- if not doc_id or doc_id not in self.documents:
267
- continue
268
+ doc_id = self.id_map.get(int_id)
269
+ if not doc_id or doc_id not in self.documents:
270
+ continue
268
271
 
269
- doc = self.documents[doc_id]
272
+ doc = self.documents[doc_id]
270
273
 
271
- if filters and not self._matches_filters(doc, filters):
272
- continue
274
+ if filters and not self._matches_filters(doc, filters):
275
+ continue
273
276
 
274
- # Build a new instance instead of mutating score in place.
275
- score = float(1 / (1 + dist)) if self.index_string == "Flat" else float(dist)
276
- result_doc = replace(doc, score=score)
277
+ # Build a new instance instead of mutating score in place.
278
+ # Every index built here uses the L2 metric, so a smaller distance means a closer match whatever the
279
+ # index type. Map it to a score where higher is better, as the other document stores do.
280
+ score = float(1 / (1 + dist))
281
+ result_doc = replace(doc, score=score)
277
282
 
278
- results.append(result_doc)
283
+ results.append(result_doc)
279
284
 
280
- if len(results) >= top_k:
281
- break
285
+ if len(results) >= top_k:
286
+ break
282
287
 
283
- return results
288
+ if not filters or len(results) >= top_k or fetch_k >= self.index.ntotal:
289
+ return results
290
+ fetch_k = self.index.ntotal
284
291
 
285
292
  def _check_condition(self, doc: Document, condition: dict[str, Any]) -> bool:
286
293
  if "operator" not in condition and "conditions" not in condition:
@@ -55,6 +55,19 @@ class TestFAISSDocumentStoreUnit:
55
55
  with pytest.raises(DuplicateDocumentError, match="already exists"):
56
56
  ds.write_documents([Document(id="dup", content="second")], policy=DuplicatePolicy.FAIL)
57
57
 
58
+ def test_write_documents_fail_policy_raises_on_duplicate_in_same_batch(self):
59
+ ds = FAISSDocumentStore(embedding_dim=2)
60
+ docs = [
61
+ Document(id="a", content="old", embedding=[0.0, 0.0]),
62
+ Document(id="a", content="new", embedding=[0.1, 0.1]),
63
+ ]
64
+ with pytest.raises(DuplicateDocumentError, match="already exists"):
65
+ ds.write_documents(docs, policy=DuplicatePolicy.FAIL)
66
+
67
+ # The check runs before anything is written, so a failed batch leaves the store untouched
68
+ assert ds.count_documents() == 0
69
+ assert ds.index.ntotal == 0
70
+
58
71
  def test_write_documents_overwrite_duplicate_in_same_batch_leaves_no_orphan_vector(self):
59
72
  ds = FAISSDocumentStore(embedding_dim=2)
60
73
  docs = [
@@ -85,6 +98,17 @@ class TestFAISSDocumentStoreUnit:
85
98
  with pytest.raises(FilterError, match=error_match):
86
99
  ds.filter_documents(filters=filters)
87
100
 
101
+ def test_search_with_filters_finds_match_outside_first_candidates(self):
102
+ # The only matching document is the farthest one, outside the first `top_k * 10` neighbours.
103
+ ds = FAISSDocumentStore(embedding_dim=2)
104
+ docs = [Document(id=f"en{i}", embedding=[1.0, i / 100], meta={"lang": "en"}) for i in range(30)]
105
+ docs.append(Document(id="de", embedding=[-1.0, 0.0], meta={"lang": "de"}))
106
+ ds.write_documents(docs)
107
+
108
+ results = ds.search([1.0, 0.0], top_k=1, filters={"field": "meta.lang", "operator": "==", "value": "de"})
109
+
110
+ assert [doc.id for doc in results] == ["de"]
111
+
88
112
 
89
113
  @pytest.mark.integration
90
114
  class TestFAISSDocumentStore(
@@ -186,3 +210,18 @@ class TestFAISSDocumentStore(
186
210
 
187
211
  # get_metadata_field_unique_values behavior (search term, pagination, meta-prefix handling, non-string
188
212
  # type preservation, filter restriction) is covered by the inherited GetMetadataFieldUniqueValuesTest mixin.
213
+
214
+
215
+ @pytest.mark.parametrize("index_string", ["Flat", "HNSW32"])
216
+ def test_search_scores_higher_for_closer_documents(index_string):
217
+ store = FAISSDocumentStore(embedding_dim=4, index_string=index_string)
218
+ store.write_documents(
219
+ [
220
+ Document(id="near", content="near", embedding=[1.0, 0.0, 0.0, 0.0]),
221
+ Document(id="far", content="far", embedding=[0.0, 0.0, 0.0, 5.0]),
222
+ ]
223
+ )
224
+ results = store.search([1.0, 0.0, 0.0, 0.0], top_k=2)
225
+ assert [doc.id for doc in results] == ["near", "far"]
226
+ assert results[0].score > results[1].score
227
+ assert all(0.0 < doc.score <= 1.0 for doc in results)
File without changes