DO you have any python code to do a pyramid sematic search on Vector DB ?
Assistant
Certainly! A pyramid semantic search usually refers to a hierarchical or multi-level semantic search where you first filter broadly and then refine results at finer granularity levels, often leveraging vector search capabilities.
If you want to implement a semantic search over a vector database in Python, you typically:
Encode your documents (or chunks) into embeddings using a model (like from OpenAI, SentenceTransformers, etc.).
Store these embeddings in a vector database (like Pinecone, FAISS, Weaviate, Qdrant).
Query the database with the query embedding.
Optionally do hierarchical or multi-level filtering/refinement — this might be what you refer to as "pyramid".
Here is an example of how to do a basic vector search and then a two-level "pyramid" semantic search (first broad, then refine).
Example setup with FAISS and SentenceTransformers
python
User
I want to search by passing limited query string then pass full query string
Assistant
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
# Sample documents
documents = [
"The cat sat on the mat.",
"Dogs are great pets.",
"I love playing football.",
"Python is a programming language.",
"Artificial intelligence is fascinating.",
"The quick brown fox jumps over the lazy dog."
]
# Load sentence transformer model for embeddings
model = SentenceTransformer('all-MiniLM-L6-v2')
# Encode documents
doc_embeddings = model.encode(documents)
# We create a FAISS index — here using L2 distance
dimension = doc_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
# Add embeddings to index
index.add(doc_embeddings)
# Pyramid semantic search example:
# 1 - broad search: search all data, get top N results
# 2 - refine search: for top candidates, re-rank or filter using more fine-grained embeddings or other logic
def pyramid_semantic_search(query, top_k=3, refine_top_k=2):
# Encode query embedding for broad search
query_embedding = model.encode([query])
# Step 1: Broad search in vector DB
distances, indices = index.search(query_embedding, top_k)
broad_results = [(documents[i], distances[0][idx]) for idx, i in enumerate(indices[0])]
print("Broad search results (Top {}):".format(top_k))
for doc, dist in broad_results:
print(f"Document: {doc} - Distance: {dist:.4f}")
# Step 2: Refine: For demonstration,
# Let's do a simple re-ranking by cosine similarity using another embedding or a different similarity metric
# Re-encode the top_k documents separately for refinement (simulating a "finer" search)
top_docs = [documents[i] for i in indices[0]]
top_doc_embeddings = model.encode(top_docs)
# Normalize embeddings for cosine similarity
def normalize(vecs):
return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
query_norm = normalize(query_embedding)
top_doc_norm = normalize(top_doc_embeddings)
cosine_similarities = (query_norm @ top_doc_norm.T).flatten()
# Take the top refined_top_k results after re-ranking
refined_indices = np.argsort(-cosine_similarities)[:refine_top_k]
refined_results = [(top_docs[i], cosine_similarities[i]) for i in refined_indices]
print("\nRefined search results (Top {}):".format(refine_top_k))
for doc, score in refined_results:
print(f"Document: {doc} - Cosine Similarity: {score:.4f}")
return refined_results
# Example query
query = "I like programming languages."
pyramid_semantic_search(query)
Explanation:
Step 1: Query embedding is searched in FAISS with Euclidean (L2) distance for top 3 documents.
Step 2: Refine the top 3 results by re-ranking with cosine similarity.
This simulates a pyramid: broad filter -> fine re-rank.
Using a managed Vector DB
For production applications, you may want to use services like Pinecone, Qdrant, or Weaviate. This pyramid approach can still be applied by:
Do an initial vector search for top K.
Then, call an additional API or perform re-ranking on the client side based on additional metadata, text similarity, or reranking models.
If you want I can provide example code for Pinecone or Qdrant similarly — just let me know!
Got it! You want a two-step pyramid semantic search where:
You first search using a limited or short query string (a brief or high-level query). This corresponds to your "broad" search level.
Then, you refine the search using the full query string (a more detailed or verbose query) on the results from step 1.
This approach mimics how a pyramid works — first coarse filtering then fine-grained re-ranking on a smaller subset.
Implementation outline
Encode all your documents into embeddings and store in a vector DB or FAISS.
Encoding gets done once.
For the search:
Encode the limited query string.
Search vector DB and fetch top K candidates.
Then encode the full query string.
Re-rank the fetched candidates based on similarity to the full query string embedding.
Here's example Python code using sentence-transformers and faiss demo:
python
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
# Sample documents
documents = [
"The cat sat on the mat.",
"Dogs are great pets and are very loyal.",
"I love playing football every weekend.",
"Python is a popular programming language.",
"Artificial intelligence and machine learning are fascinating fields.",
"The quick brown fox jumps over the lazy dog in the park."
]
# Initialize model and embed documents once
model = SentenceTransformer('all-MiniLM-L6-v2')
doc_embeddings = model.encode(documents, convert_to_numpy=True)
dimension = doc_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(doc_embeddings)
def pyramid_search(limited_query, full_query, top_k=5, refine_top_k=3):
# Step 1: Encode limited query string and do broad search
limited_query_emb = model.encode([limited_query], convert_to_numpy=True)
distances, indices = index.search(limited_query_emb, top_k)
# Candidates from broad search
candidate_docs = [documents[i] for i in indices[0]]
candidate_embeddings = doc_embeddings[indices[0]]
print(f"Step 1 - Broad search (limited query): '{limited_query}'")
for idx, (doc, dist) in enumerate(zip(candidate_docs, distances[0])):
print(f"{idx+1}: {doc} (distance: {dist:.4f})")
# Step 2: Encode full query and re-rank top candidates by cosine similarity
full_query_emb = model.encode([full_query], convert_to_numpy=True)
def normalize(vecs):
return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
full_query_norm = normalize(full_query_emb)
candidate_emb_norm = normalize(candidate_embeddings)
cosine_similarities = (full_query_norm @ candidate_emb_norm.T).flatten()
# Get indices of top refined_top_k candidates by descending similarity
refined_indices = np.argsort(-cosine_similarities)[:refine_top_k]
refined_results = [(candidate_docs[i], cosine_similarities[i]) for i in refined_indices]
print(f"\nStep 2 - Refined search (full query): '{full_query}'")
for idx, (doc, score) in enumerate(refined_results):
print(f"{idx+1}: {doc} (cosine similarity: {score:.4f})")
return refined_results
# Example usage
limited_query = "programming language"
full_query = "I want to learn Python programming language"
results = pyramid_search(limited_query, full_query)
How it works:
You pass "programming language" as the limited query.
It retrieves the top 5 broadly matching docs.
Then using the full query "I want to learn Python programming language", you re-rank the previous results by cosine similarity.
Finally, you return the refined top 3 documents.
Let me know if you want an example with a managed vector DB like Pinecone or Qdrant!