vectorstore.similarity_search(query, k=4) turns your query into a vector with the embedding model the store was built with, asks the store for the k nearest stored vectors, and returns them as a list of LangChain Document objects, most similar first. It returns no scores; for those you call similarity_search_with_score, and what that number means depends on the store behind it. This guide covers the search methods on LangChain's VectorStore interface as of langchain-core 1.8.4 (November 2026): scores, maximal marginal relevance, retrievers, metadata filters and the mistakes that make results look wrong.
What does vectorstore.similarity_search do, step by step?
LangChain's integration docs describe it in one line: "Issue a semantic query using similarity_search, which returns the closest embedded documents". Underneath, the call does four things:
- Embeds the query. The store calls
embed_queryon the embedding model you passed when you created it. You never pass a model to the search call itself. - Runs a nearest neighbor search. The store compares the query vector with the stored vectors using its distance metric. InMemoryVectorStore "computes cosine similarity for search using numpy" over every vector; Chroma, Postgres and Qdrant use their own indexes and metrics.
- Applies the filter, if you pass one and the integration supports it.
- Returns
Documentobjects. Each haspage_content,metadataand, in current versions, anid.
If embeddings, nearest neighbor search and HNSW indexes are new to you, our explainer on what a vector database is covers the concepts. This article stays on the LangChain API.
Here is a complete example with no external database:
# pip install -qU langchain-core langchain-openai numpy
# export OPENAI_API_KEY=...
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vector_store = InMemoryVectorStore(embedding=embeddings)
docs = [
Document(
page_content="Refunds are issued within 14 days of receiving the returned item.",
metadata={"source": "returns-policy", "lang": "en"},
),
Document(
page_content="Worn shoes can be returned if they are in resalable condition.",
metadata={"source": "returns-policy", "lang": "en"},
),
Document(
page_content="Standard shipping takes 3 to 5 working days.",
metadata={"source": "shipping", "lang": "en"},
),
Document(
page_content="Rückerstattungen erfolgen innerhalb von 14 Tagen.",
metadata={"source": "returns-policy", "lang": "de"},
),
Document(
page_content="Use the size guide to measure your foot length.",
metadata={"source": "size-guide", "lang": "en"},
),
]
vector_store.add_documents(docs)
results = vector_store.similarity_search("Can I send back shoes I have worn?", k=2)
for doc in results:
print(doc.id, doc.metadata["source"], doc.page_content)
We ran every InMemoryVectorStore snippet in this article against langchain-core 1.8.4, swapping OpenAIEmbeddings for the library's DeterministicFakeEmbedding so no API key was needed. That confirms the calls, return types and errors described here; the rankings a fake model produces are meaningless, so we do not show them. One finding from that run: numpy is not installed with langchain-core, and InMemoryVectorStore search fails without it, which is why it is in the install line.
Which LangChain vector store search method should you use?
All of these live on the base VectorStore class, so the same names work across integrations, although each integration decides how to implement them.
| Method | Returns | When to use |
|---|---|---|
similarity_search(query, k=4, filter=...) |
list[Document] |
Default top k retrieval for RAG |
similarity_search_with_score(query, k=4) |
list[tuple[Document, float]] |
Debugging, logging, thresholds tuned to one store |
similarity_search_with_relevance_scores(query, k=4) |
list[tuple[Document, float]], 0 to 1 |
Thresholds that survive a store change, where implemented |
similarity_search_by_vector(embedding, k=4) |
list[Document] |
You already have the query vector |
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5) |
list[Document] |
Results full of near duplicate chunks |
as_retriever(search_type=..., search_kwargs=...) |
VectorStoreRetriever |
Plugging search into chains and agents |
asimilarity_search, amax_marginal_relevance_search and other a methods |
Awaitable of the same types | Async applications |
What is the difference between similarity_search_with_score and similarity_search_with_relevance_scores?
similarity_search_with_score returns whatever number the store produces. The base class describes it as "Run similarity search with distance.", but in practice some stores return a distance and some a similarity:
| Store (package) | Raw score from similarity_search_with_score |
Better match |
|---|---|---|
| InMemoryVectorStore (langchain-core) | Cosine similarity | Higher |
| Chroma (langchain-chroma) | Distance; Chroma's collection default is "l2 (squared L2 norm)" |
Lower |
| PGVectorStore (langchain-postgres) | "distance scores", with distance strategy "Defaults to COSINE_DISTANCE" | Lower |
| QdrantVectorStore (langchain-qdrant) | Qdrant's score; the default metric is models.Distance.COSINE |
Higher for cosine |
Qdrant's own docs warn that a score threshold "may exclude lower or higher scores depending on the used metric", which is the general rule: read the raw score only after you know the store and its metric. Even LangChain's docs label raw scores loosely; the PGVector example prints a cosine distance as SIM=0.763449 on the integration page.
similarity_search_with_relevance_scores exists to remove that ambiguity. It promises to "Return docs and relevance scores in the range [0, 1]", where 0 is dissimilar and 1 is most similar, and it accepts a score_threshold. Each integration converts its distance to that scale with a function chosen by its metric; for cosine distance, langchain-core simply uses one minus the distance. The catch is that a store must implement that conversion. InMemoryVectorStore does not, and in langchain-core 1.8.4 the call raises NotImplementedError, so search_type="similarity_score_threshold" fails on it too. Use similarity_search_with_score there and filter the cosine similarities yourself.
for doc, score in vector_store.similarity_search_with_score("refund window", k=3):
print(f"{score:.3f}", doc.metadata["source"])
How does max_marginal_relevance_search work?
Plain similarity search often returns several chunks that say the same thing, because overlapping chunks of one document sit close together. Maximal marginal relevance fixes that. The reference puts it plainly: MMR "optimizes for similarity to query AND diversity among selected documents".
It works in two stages. The store first fetches fetch_k candidates by similarity (default 20), then picks k of them one at a time, each pick trading relevance to the query against similarity to what was already picked. lambda_mult sets the balance, a number between 0 and 1 "with 0 corresponding to maximum diversity and 1 to minimum diversity". The default is 0.5.
docs = vector_store.max_marginal_relevance_search(
"refund window", k=3, fetch_k=20, lambda_mult=0.3
)
Raise fetch_k when your corpus has many near duplicates, since MMR can only choose among what it fetched. Lower lambda_mult when results are still repetitive.
How do you use as_retriever with search_type and search_kwargs?
as_retriever wraps the store in a VectorStoreRetriever, the object chains and agents expect. search_type "Can be 'similarity' (default), 'mmr', or 'similarity_score_threshold'", and search_kwargs is passed straight to the matching search method: k, fetch_k, lambda_mult, score_threshold and filter.
retriever = vector_store.as_retriever(
search_type="mmr",
search_kwargs={"k": 3, "fetch_k": 20, "lambda_mult": 0.5},
)
docs = retriever.invoke("Can I return worn shoes?")
Two things trip people up. similarity_score_threshold requires a float score_threshold in search_kwargs, and creating the retriever without one raises a validation error (a ValueError subclass). And because that search type calls similarity_search_with_relevance_scores, it only works on stores that implement relevance scores. The retriever is what you hand to a RAG chain or register as a tool for an agent; our guides to RAG vs fine-tuning and building an AI agent cover when retrieval is the right design.
How do metadata filters work in LangChain similarity search?
You pass filter= to the search method or inside search_kwargs, but the value you pass is specific to the integration. LangChain does not translate a common filter language for these methods.
InMemoryVectorStore takes a function that receives a Document and returns a boolean. A dictionary raises TypeError: 'dict' object is not callable.
def english_only(doc: Document) -> bool:
return doc.metadata.get("lang") == "en"
vector_store.similarity_search("refund", k=3, filter=english_only)
Chroma takes a metadata dictionary. "Using the $eq operator is equivalent to using the metadata field directly in your where filter", and conditions combine with $and or $or:
chroma_store.similarity_search(
"refund", k=3, filter={"$and": [{"source": "returns-policy"}, {"lang": "en"}]}
)
PGVectorStore takes operator dictionaries and "currently supports the following operators and all Postgres data types": $eq, $ne, $lt, $lte, $gt, $gte, $in, $nin, $between, $exists, $like, $ilike, $and and $or. Filters work on the metadata columns you declare when creating the table, since by default "Metadata is stored in a JSON column".
Qdrant takes a qdrant_client Filter, and LangChain stores your metadata under a metadata key in the payload, so field names need that prefix, as in the reference example key="metadata.bar":
from qdrant_client import models
qdrant_store.similarity_search(
"refund",
k=3,
filter=models.Filter(
must=[models.FieldCondition(key="metadata.lang", match=models.MatchValue(value="en"))]
),
)
How do you switch from InMemoryVectorStore to Chroma, PGVector or Qdrant?
InMemoryVectorStore lives in process memory, so it is gone when the process exits. The search calls stay the same when you move to a persistent store; the constructor and the filter syntax change. The current packages, per LangChain's integration list, are langchain-chroma, langchain-postgres and langchain-qdrant.
Chroma, saved to a local folder. The docs say "You can provide the persist_directory argument to save your data across multiple runs of your program."
# pip install -qU langchain-chroma
from langchain_chroma import Chroma
chroma_store = Chroma(
collection_name="support_docs",
embedding_function=embeddings,
persist_directory="./chroma_db",
)
chroma_store.add_documents(docs)
Postgres with pgvector. The langchain-postgres README states: "In v0.0.14+, PGVector is deprecated. Please migrate to PGVectorStore". New code should use PGVectorStore, which needs a table sized to your embedding model (1,536 dimensions for text-embedding-3-small):
# pip install -qU langchain-postgres
from langchain_postgres import PGEngine, PGVectorStore
engine = PGEngine.from_connection_string(
url="postgresql+psycopg://user:password@localhost:5432/app"
)
engine.init_vectorstore_table(table_name="support_docs", vector_size=1536)
pg_store = PGVectorStore.create_sync(
engine=engine, table_name="support_docs", embedding_service=embeddings
)
pg_store.add_documents(docs)
Qdrant, here on disk with no server; point url at a Qdrant server in production.
# pip install -qU langchain-qdrant
from langchain_qdrant import QdrantVectorStore
qdrant_store = QdrantVectorStore.from_documents(
docs, embeddings, path="./qdrant_db", collection_name="support_docs"
)
We tested only the InMemoryVectorStore code; the three snippets above follow the current integration docs and package source but were not run against live databases.
Does LangChain have async similarity search?
Yes. Every search method has an a twin: asimilarity_search, asimilarity_search_with_score, asimilarity_search_with_relevance_scores, amax_marginal_relevance_search and asimilarity_search_by_vector, and retrievers support await retriever.ainvoke(query).
docs = await vector_store.asimilarity_search("refund window", k=2)
Check whether your integration implements them natively. In langchain-core's base class, the default async score method hands the sync method to a thread executor, with a code comment calling it "a temporary workaround". That keeps your event loop free but adds no real concurrency inside the database client. PGVectorStore's documentation is written async first, noting that "All async methods have corresponding sync methods."
Why does LangChain similarity search return the wrong results?
Most bad results come from five causes, roughly in order of how often we see them.
Different embedding models at index and query time. The store embeds queries with whatever model it was constructed with. If you indexed with one model and later reopen the store with another, the vectors are not comparable and results look random. Pass the model name explicitly to OpenAIEmbeddings rather than relying on the default, and re-embed everything when you change it.
Scores that look inverted. A Chroma or PGVectorStore result of 0.12 is a better match than 0.45, because those are distances. Code that keeps "scores above 0.7" will keep the worst results. Use relevance scores, or check the table above for your store.
k too small. With the default of 4, the answer can sit at position 5 or 6, especially when near duplicate chunks fill the top slots. Retrieve 10 to 20 and rerank or use MMR, rather than raising k blindly into the prompt.
Poor chunking. Search returns chunks, not documents. Chunks that are too long blur several topics into one vector; chunks that are too short lose the context that made them relevant. Fix chunking before tuning search parameters.
Filters silently ignored. Search methods accept **kwargs, so a misspelled argument often does nothing. In our test, similarity_search(query, k=2, filters=...) on InMemoryVectorStore returned unfiltered results with no error. The same applies to a filter in a format the integration does not read. Always test a filter with a query that should return nothing.
When these are fixed and retrieval quality still matters to the business, it usually needs evaluation sets, hybrid keyword search and access control on every query. Qubba builds internal search and RAG systems like this for companies, on a fixed written quote after a 30 minute call.
Frequently asked questions
What is the default k in LangChain similarity_search?
The default is 4.
The base VectorStore.similarity_search signature uses k=4, and as_retriever documents the same default for search_kwargs.
Chroma's integration also sets its default to 4.
Pass a larger k explicitly when answers may be spread across several chunks, and consider MMR or reranking so extra results add new information instead of repetition.
Does similarity_search return scores?
No.
It returns a list of Document objects only.
Use similarity_search_with_score to get the store's raw score, which may be a distance or a similarity depending on the integration, or similarity_search_with_relevance_scores to get a score between 0 and 1 where 1 is most similar, on stores that implement that conversion.
Can I pass a filter dictionary to InMemoryVectorStore?
No.
InMemoryVectorStore expects a function that takes a Document and returns True or False.
Passing a dictionary raises a TypeError because the store tries to call it.
Write a small function that checks doc.metadata, or move to Chroma, PGVectorStore or Qdrant if you need operator based filters on a persistent store.
Is PGVector deprecated in LangChain?
The PGVector class in langchain-postgres is deprecated from version 0.0.14 in favor of PGVectorStore, according to the package README.
Both ship in the same langchain-postgres package. PGVectorStore uses a PGEngine connection, its own table layout with optional metadata columns for filtering, and cosine distance by default.
What is the difference between similarity_search and as_retriever?
similarity_search is a direct method call that returns documents. as_retriever wraps the same store in a retriever object with a fixed search type and fixed search arguments, which you call with invoke or ainvoke.
Use the method in scripts and tests; use the retriever when you plug search into a chain, an agent tool or tracing.
