A vector database stores vectorized documents or conversation snippets so they can be retrieved through similarity searches. In retrieval-augmented generation (RAG), relevant results provide context for an LLM’s answer. section 8.2
A document-retrieval workflow typically:
- Loads documents, splits them into chunks, embeds the chunks, and stores them. section 8.2
- Embeds a query, retrieves similar content, and supplies that content as context to an LLM. section 8.2
From keyword matching to semantic retrieval
A Python in-memory example uses TF–IDF vectors and cosine similarity to return document text and scores, but may miss context and meaning. A Chroma example searches document embeddings and scores results by distance. section 8.3.2 section 8.3.4
Listing 8.5 document_query_chromadb.py (relevant code sections)
embeddings = [get_embedding(doc) for doc in documents] #1
ids = [f"id{i}" for i in range(len(documents))] #1
chroma_client = chromadb.Client() #2
collection = chroma_client.create_collection(
name="documents") #2
collection.add( #3
embeddings=embeddings,
documents=documents,
ids=ids
)
def query_chromadb(query, top_n=2): #4
query_embedding = get_embedding(query)
results = collection.query(
query_embeddings=[query_embedding],
n_results=top_n
)
return [(id, score, text) for id, score, text in
zip(results['ids'][0],
results['distances'][0],
results['documents'][0])]
while True: #5
query = input("Enter a search query (or 'exit' to stop): ")
if query.lower() == 'exit':
break
top_n = int(input("How many top matches do you want to see? "))
search_results = query_chromadb(query, top_n)
print("Top Matched Documents:")
for id, score, text in search_results:
print(f"""
ID:{id} TEXT: {text} SCORE: {round(score, 2)}
""") #5
print("\n")
###Output
Enter a search query (or 'exit' to stop): dogs are lazy
How many top matches do you want to see? 3
Top Matched Documents:
ID:id7 TEXT: The dog is lazy but the brown fox is quick! SCORE: 0.24
ID:id5 TEXT: The brown fox is quick and the blue dog is lazy! SCORE: 0.28
ID:id2 TEXT: The quick brown fox jumps over the lazy dog. SCORE: 0.29
The listing illustrates adding document embeddings and IDs to a Chroma collection, then querying it for matching documents and distances. section 8.3.4

























