Skip to content

FAISS: filtered search misses matching documents outside the first top_k * 10 neighbours #4322

Done

Description

@astroknot-sheep

Describe the bug
FAISSDocumentStore.search() with filters (and so FAISSEmbeddingRetriever) only looks at the first min(ntotal, top_k * 10) nearest neighbours and filters those. If the matching documents are further away than that, the search returns fewer than top_k results, or nothing at all, even though filter_documents() finds them.

To Reproduce

from haystack import Document
from haystack_integrations.document_stores.faiss import FAISSDocumentStore
from haystack_integrations.components.retrievers.faiss import FAISSEmbeddingRetriever

s = FAISSDocumentStore(embedding_dim=2)
docs = [Document(content=f"en{i}", meta={"lang": "en"}, embedding=[1.0, i / 1000]) for i in range(50)]
docs.append(Document(content="de", meta={"lang": "de"}, embedding=[-1.0, 0.0]))
s.write_documents(docs)
f = {"field": "meta.lang", "operator": "==", "value": "de"}

print([d.content for d in s.filter_documents(f)])                         # ['de']
print([d.content for d in s.search([1.0, 0.0], top_k=3, filters=f)])      # []
r = FAISSEmbeddingRetriever(document_store=s, top_k=3)
print([d.content for d in r.run(query_embedding=[1.0, 0.0], filters=f)["documents"]])  # []

Expected behavior
['de'] from both search() and the retriever. A filtered search should return up to top_k matching documents whenever the store has them, as the other document stores do.

Additional context
Seen on main (07a6e48), Python 3.13. A small fix is to search again with a larger k (doubling, up to ntotal) when the filters leave fewer than top_k results, so unfiltered searches and the common case don't change. I have a fix with a test ready and will open a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions