Embeddings, Vector Stores and Retrievers
Retrieval is a pipeline you can reason about: an embedding model turns text into vectors, a vector store keeps and searches them, and a retriever is the Runnable "query in, Documents out" interface that chains and agents call. Know the VectorStore API and its defaults, how `as_retriever` maps `search_type` and `search_kwargs` onto store methods, which advanced retrievers fix which failure, and how to keep an index in sync with the indexing API.
Key points
- 1
Embeddingshas two abstract methods:embed_documents(texts) -> list[list[float]](one vector per text) andembed_query(text) -> list[float]. Index and query with the same model; vectors from different models are not comparable even at the same dimension. - 2
CacheBackedEmbeddings.from_bytes_store(model, store, namespace=...)(inlangchain_classic.embeddings) caches document vectors by a hash of the text. Setnamespace(for example the model name) to avoid collisions between models; query embeddings are only cached if you passquery_embedding_cache. - 3
Shared VectorStore API:
add_documents(docs, ids=...),add_texts,from_documents,delete(ids=...),get_by_ids,similarity_search(query, k=4),similarity_search_with_score,similarity_search_with_relevance_scoresandmax_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5). Re-adding an existing id upserts; adding without ids creates new UUIDs and therefore duplicates. - 4
Vector stores are not Runnables;
as_retriever()returns aVectorStoreRetriever(a Runnable).search_typeis"similarity"(default),"mmr"or"similarity_score_threshold"(which requiressearch_kwargs={"score_threshold": x}with x between 0 and 1).search_kwargssuch ask,fetch_k,lambda_multandfilterare passed to the store method. - 5
Scores are store-specific:
InMemoryVectorStorereturns cosine similarity (higher is better), FAISS defaults to Euclidean distance (lower is better). Normalised 0 to 1 scores come fromsimilarity_search_with_relevance_scores, whichInMemoryVectorStoredoes not implement, so its threshold retriever raisesNotImplementedErrorat query time. - 6
Filters vary by store:
InMemoryVectorStoretakes a callable on aDocument, Chroma takes dicts such as{"source": "news"}, PGVector supports$eq,$ne,$lt,$in,$nin,$between,$like,$and,$or. Filter inside the search, never in the prompt, and derive tenant filters from the authenticated session. - 7
Store choice:
InMemoryVectorStore(in-process dict,dump/loadto JSON) for tests and tutorials; FAISS (langchain-community, in-process,save_local/load_localwith a pickled docstore that needsallow_dangerous_deserialization=True); Chroma (langchain-chroma, in memory unlesspersist_directoryor a client is set); PGVector (langchain-postgres, psycopg3 connection string) for production multi-user systems. - 8
Custom retriever: subclass
BaseRetrieverand implement_get_relevant_documents(query, *, run_manager);_aget_relevant_documentsis optional (the default runs the sync method in an executor). Call retrievers withinvoke,batchorainvoke;get_relevant_documentsis not available in langchain-core 1.x. - 9
Advanced retrievers live in
langchain-classic:MultiQueryRetriever(one LLM call writes rephrasings, results are a unique union),EnsembleRetriever(weighted reciprocal rank fusion,c=60, de-duplicated bypage_contentorid_key) usually paired withBM25Retrieverfromlangchain-community(needsrank_bm25),ParentDocumentRetriever(children in the vector store, parents in a docstore linked bydoc_id; optionalparent_splitter),ContextualCompressionRetrieverwith a reranker orEmbeddingsFilter, andSelfQueryRetriever(LLM writes query plus filter fromdocument_contentsandmetadata_field_info; needslark). - 10
Indexing API:
index(docs, record_manager, vector_store, cleanup=..., source_id_key=...)fromlangchain_core.indexinghashes documents, skips unchanged ones and reportsnum_added,num_updated,num_skipped,num_deleted. Cleanup:Nonedeletes nothing;incrementalandscoped_fullneedsource_id_keyand only clean up source ids seen in the run;fulldeletes everything the loader did not return. The store must implementdelete. Prefer a non-SHA-1key_encoderfor new indexes. - 11
RAG wiring: LCEL
{"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | model | StrOutputParser(); legacycreate_retrieval_chain(retriever, create_stuff_documents_chain(model, prompt))expects{"input": ...}and returnsinput,contextandanswer; for agentic RAG,create_retriever_tool(retriever, name, description, response_format="content_and_artifact")returns text as content and theDocumentlist as the artifact. - 12
Two-step RAG gives high control and predictable latency; agentic RAG lets the model decide when to search (more flexible, variable latency); hybrid designs add query rewriting and validation steps.
Common traps
Querying with a different embedding model of the same dimension raises no error; results just become garbage.
MMR with
fetch_kequal tokcannot change the result set, only its order.ParentDocumentRetrieverapplieskto child chunks, so several hits from one parent collapse into a single returned document.index(..., cleanup="full")with a loader that returns only changed files deletes every unchanged document; an empty incremental run deletes nothing.Porting a score threshold between stores breaks when one returns similarity and the other returns distance.
Feeding a dict into a chain whose first step is a retriever, or skipping
format_docs, either fails or stuffs theDocumentrepr (ids and metadata) into the prompt.Putting tenant or permission rules in the system prompt, or letting a self-query LLM choose the tenant filter, is not access control.
Read the source
Further reading
Suggest a resourceNo extra reading for Embeddings, Vector Stores and Retrievers yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Embeddings, Vector Stores and Retrievers
Ten questions, with the answer and explanation after each one.