Vector retrieval supplies the context that a retrieval-augmented application can use for each question. Setting the candidate count deliberately helps balance recall against the time and context space consumed by nodes that reach later processing stages.
The similarity_top_k argument belongs where a VectorStoreIndex creates its retriever. It is an upper limit rather than a guarantee because an index, metadata filter, or vector store may return fewer candidates.
A small credential-free index can expose the setting without involving response synthesis. MockEmbedding makes the retrieval repeatable enough to confirm both the retriever property and the number of nodes returned, while relevance tuning still belongs on representative production queries.
Steps to set LlamaIndex retriever similarity top K:
- Install llama-index-core in the active Python environment.
$ python -m pip install llama-index-core
Related: How to install LlamaIndex with pip
- Create the document set and local embedding configuration in retriever_top_k.py.
- retriever_top_k.py
from llama_index.core import Document, Settings, VectorStoreIndex from llama_index.core.embeddings import MockEmbedding Settings.embed_model = MockEmbedding(embed_dim=8) documents = [ Document(text="Billing reviews refund requests.", metadata={"source": "billing"}), Document(text="Logistics reviews shipping claims.", metadata={"source": "shipping"}), Document(text="Trust reviews account closures.", metadata={"source": "trust"}), ]
- Append the vector index and retriever configured with similarity_top_k=2.
- retriever_top_k.py
index = VectorStoreIndex.from_documents(documents) retriever = index.as_retriever(similarity_top_k=2)
- Append the retrieval call and result reporting.
- retriever_top_k.py
nodes = retriever.retrieve("Which teams review requests?") print(f"similarity_top_k={retriever.similarity_top_k}") print(f"retrieved_count={len(nodes)}") for node in nodes: print(f"source={node.node.metadata['source']}")
- Run retriever_top_k.py to confirm that the configured retriever returns two nodes.
$ python retriever_top_k.py similarity_top_k=2 retrieved_count=2 source=billing source=shipping
The source order depends on the embedding model and indexed content. The two count lines prove the configured upper limit reached the retriever and the controlled index supplied that many candidates.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.