Skip to content

feat: add similarity search with distance score #125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/langchain_google_firestore/vectorstores.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ def _similarity_search(
query: List[float],
k: int = DEFAULT_TOP_K,
filters: Optional[BaseFilter] = None,
with_scores: Optional[bool] = False,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding the support!

Could we pass distance_result_field as parameter so that we could calculate the score based on any field (not limit to distance)?

Copy link
Author

@juanfe88 juanfe88 May 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left it as optional with a default value, but it can be overriden. I also added a test for these cases WDYT ? 😄

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! In this case, do we still need with_scores? Since distance_result_field is optional, with_scores field can be implicitly done by distance_result_field.

(ex: if distance_result_field is specified, return scores)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. I just refactored it so that we can get the scores just by passing the name of field

) -> List[DocumentSnapshot]:
_filters = filters or self.filters

Expand All @@ -253,6 +254,7 @@ def _similarity_search(
query_vector=Vector(query),
distance_measure=self.distance_strategy,
limit=k,
distance_result_field= 'distance' if with_scores else None
)

return results.get()
Expand Down Expand Up @@ -413,6 +415,14 @@ def max_marginal_relevance_search_by_vector(
)
return [convert_firestore_document(doc_results[i]) for i in mmr_doc_indexes]

def similarity_search_with_score(self, query, k = 4,filters: Optional[BaseFilter] = None, **kwargs):
docs = self._similarity_search(
self.embedding_service.embed_query(query), k, filters=filters,with_scores=True
)
return [
(convert_firestore_document(doc, page_content_fields=[self.content_field]),doc.to_dict()["distance"])
for doc in docs
]
@classmethod
def from_texts(
cls: Type[FirestoreVectorStore],
Expand Down
70 changes: 70 additions & 0 deletions tests/test_vectorstores.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,76 @@ def test_firestore_max_marginal_relevance_by_vector(
test_case.assertEqual(len(results), k)


def test_firestore_similarity_search_with_score(
test_case: TestCase,
test_collection: str,
client,
embeddings: FakeEmbeddings,
):
"""
An end-to-end test for similarity search with score in FirestoreVectorStore.
"""

# Create FirestoreVectorStore instance
firestore_store = FirestoreVectorStore(test_collection, embeddings, client=client)

texts = ["test1", "test2"]
k = 2

# Add vectors to Firestore
firestore_store.add_texts(texts, ids=["1", "2"])

# Perform similarity search with score
results = firestore_store.similarity_search_with_score("test1", k)

# Verify that the search results are as expected
test_case.assertEqual(len(results), k)

# Check that each result is a tuple with a Document and a score
for result in results:
test_case.assertTrue(isinstance(result, tuple))
test_case.assertEqual(len(result), 2)
test_case.assertTrue(isinstance(result[0], Document))
test_case.assertTrue(isinstance(result[1], float))


def test_firestore_similarity_search_with_score_with_filters(
test_case: TestCase,
test_collection: str,
client: firestore.Client,
embeddings: FakeEmbeddings,
):
"""
An end-to-end test for similarity search with score in FirestoreVectorStore with filters.
Requires an index on the filter field in Firestore.
"""

# Create FirestoreVectorStore instance
firestore_store = FirestoreVectorStore(test_collection, embeddings, client=client)

# Add vectors to Firestore
firestore_store.add_texts(
["test1", "test2"],
ids=["1", "2"],
metadatas=[{"foo": "bar"}, {"foo": "baz"}],
)

# Perform similarity search with score and filter
results = firestore_store.similarity_search_with_score(
"test1", k=2, filters=FieldFilter("metadata.foo", "==", "bar")
)

# Verify that the search results are as expected with the filter applied
test_case.assertEqual(len(results), 1)

# Check that the result is a tuple with a Document and a score
doc, score = results[0]
test_case.assertTrue(isinstance(doc, Document))
test_case.assertTrue(isinstance(score, float))
test_case.assertEqual(doc.page_content, "test1")
test_case.assertEqual(doc.metadata["metadata"]["foo"], "bar")


def test_firestore_from_texts(
test_case: TestCase,
test_collection: str,
Expand Down