DS DevShelfHub Projects · AI tools
Tutorials / LangChain / Reference / Methods / .similarity_search()
Method Vector stores

.similarity_search(): Reference Guide

By DevShelfHub

Find k most similar documents to query.

What is .similarity_search()?

.similarity_search() is the primary retrieval method on all LangChain vector store classes. It takes a plain-text query string, embeds it using the same embedding function that was used to index your documents, and returns the k nearest neighbors from the vector store ranked by embedding similarity. Under the hood it calls the embedding model once per query — you do not pre-embed the query yourself.

The default distance metric and the meaning of "similar" depends on the vector store backend. Chroma defaults to cosine similarity; FAISS can use L2, cosine, or inner product depending on the index type you initialized it with; Pinecone uses the metric configured when the index was created. Most backends return documents sorted from most to least similar, but .similarity_search() discards the actual scores — if you need the distance values for threshold filtering or debugging, use .similarity_search_with_score() instead.

The filter parameter (where supported) lets you scope retrieval to documents matching specific metadata values before or after the vector search, depending on the backend. Chroma and Pinecone both support pre-filter (metadata-first, then vector search on the filtered set). Most backends accept filter as a dict of key-value pairs: {"source": "handbook.pdf"}. The filter syntax varies by backend — Chroma uses {"source": {"$eq": "handbook.pdf"}} style while others use simpler equality dicts. Check your vector store's documentation for exact syntax.

Use Cases

  • RAG retrieval
  • Document search
  • Q&A systems
  • Recommendations
  • Content discovery
  • Similarity matching

Key Features

  • k-nearest neighbors
  • Relevance ranking
  • Vector matching
  • Metadata filtering
  • Fast retrieval
  • Configurable metrics

When NOT to Use

For exact keyword matching—use BM25. Without embeddings.

Notes

k defaults to 4 — tune based on context window budget

The default k=4 is a reasonable starting point but often not optimal. Too few documents miss relevant context; too many fill the context window with noise and increase cost. For GPT-4o with a 128k context window, k=10–20 is feasible. For smaller models, k=3–5 keeps the prompt within limits. Benchmark retrieval recall at different k values for your dataset.

Scores are discarded — use similarity_search_with_score() to access them

similarity_search() returns only the Document objects, not the distances. If you want to filter out low-confidence results (e.g., only keep documents above a relevance threshold), call similarity_search_with_score() instead and check the float score against your threshold.

filter syntax differs per backend

Chroma uses MongoDB-style operators: {"field": {"$eq": "value"}}. Pinecone uses plain dicts: {"field": "value"}. FAISS in-memory stores do not support metadata filtering at all. Always test filter behavior against your specific backend — passing an unsupported filter silently returns all k results on some backends.

Distance metric is set at index creation, not at query time

You cannot change the similarity metric per-query. The metric (cosine, dot product, L2) is baked in when the vector index is created. If you need to experiment with metrics, you must re-index with a new vector store configuration.

Method Signature

python
docs = vector_store.similarity_search(query, k=4)

Parameters

Parameter Type Required Purpose
query str Yes Query text

Return Value

Type:

List[Document]

Description:

k most similar documents

Example Output:

[Document(...), Document(...), ...]

Code Examples

Basic similarity search

python
from langchain_community.vectorstores import Chroma
vector_store = Chroma.from_documents(docs, embeddings)
results = vector_store.similarity_search('What is AI?', k=3)
for doc in results:
    print(doc.page_content)

Similarity search with metadata filter

python
results = vector_store.similarity_search(
    'deployment best practices',
    k=5,
    filter={'category': 'devops'}
)
for doc in results:
    print(doc.metadata["source"], doc.page_content[:100])

Similarity search via LCEL-compatible retriever

python
retriever = vector_store.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 6}
)
docs = retriever.invoke('explain transformers')
# Use in LCEL chain
chain = retriever | format_docs | prompt | model | StrOutputParser()

Common Mistakes

❌ Forget that query needs embedding internally

✅ similarity_search() embeds query automatically

Browse the full LangChain API reference index to explore more classes, methods, and decorators, or start with the LangChain introduction tutorial for end-to-end context on building with .similarity_search() and the wider framework.

.similarity_search() FAQ

What does .similarity_search() do in LangChain?

Find k most similar documents to query. .similarity_search() is the primary retrieval method on all LangChain vector store classes. It takes a plain-text query string, embeds it using the same embedding function that was used to index your documents, and returns the k nearest neighbors from the vector store ranked by embedding similarity. Under the hood it calls the embedding model once per query — you do not pre-embed the query yourself. The default distance metric and the meaning of "similar" depends on the vect…

Which LangChain classes support .similarity_search()?

.similarity_search() is available on Vector stores. Pin your installed LangChain version and verify the method exists in that release before deploying.

When should I use .similarity_search()?

Use .similarity_search() when your LangChain chains, agents, or pipelines need the behavior described in this guide.

What does .similarity_search() return?

.similarity_search() returns a List[Document]. k most similar documents

Does .similarity_search() have an async equivalent?

.similarity_search() does not have a documented async variant. Avoid .similarity_search() For exact keyword matching—use BM25. Without embeddings.

Where can I explore more LangChain API reference pages?

Open the LangChain API reference index on DevShelfHub to browse classes, methods, and decorators, each with runnable examples, parameters, common mistakes, and cross-links.