Design Vector DB , to so sematic search on excel data with multiple columns, search can be done using only one column data for can be multi column together , Give Python code to store data in Vector DB such that it can serve query from one column or multi column query. Use FAISS
Assistant
User
no this will now solve my problem . i need nested vector store
Assistant
Certainly! To build a semantic search on Excel data using multiple columns with FAISS, you generally need to:
Load your Excel data.
Convert each row (or selected columns) into a semantic vector.
Store those vectors in FAISS.
At query time, convert the query (which may be one or multiple columns concatenated) into a vector.
Search in FAISS based on vector similarity.
High-level approach:
Use an embedding model (e.g., from sentence-transformers) to convert text to vectors.
Concatenate column values when multiple columns are involved.
Index vectors with FAISS.
Retrieve nearest neighbors using query embeddings.
import pandas as pd
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer
# Load model for embeddings
model = SentenceTransformer('all-MiniLM-L6-v2') # lightweight and good quality
# Load your Excel file
df = pd.read_excel('data.xlsx') # Adjust filename and sheet name if needed
# Columns to index - can be multiple columns
index_columns = ['Column1', 'Column2', 'Column3'] # change as per your excel
# Combine columns into a single string representation for each row
def combine_columns(row, cols):
# Join columns with a separator (space)
texts = [str(row[col]) for col in cols if pd.notna(row[col])]
return ' '.join(texts)
# Create list of combined texts
documents = [combine_columns(row, index_columns) for idx, row in df.iterrows()]
# Encode documents to vectors
embeddings = model.encode(documents, convert_to_numpy=True)
# Normalize vectors (optional but improves cosine search)
faiss.normalize_L2(embeddings)
# Build FAISS index
dimension = embeddings.shape[1]
index = faiss.IndexFlatIP(dimension) # Using Inner Product for cosine after normalization
index.add(embeddings)
print(f"Indexed {len(documents)} rows.")
# Store additional data to map search result indices back to original data (if needed)
# For example store row indices or original DataFrame rows
# For simplicity, let's just store DataFrame indices (they match order in embeddings)
row_id_map = df.index.to_list()
def semantic_search(query_dict, top_k=5):
"""
Query dict: key=column name, value=search text (can be one or multiple columns)
Example: {'Column1': 'some text', 'Column3': 'other text'}
"""
# Combine query columns text similarly as indexed data
query_texts = [str(query_dict[col]) for col in index_columns if col in query_dict and query_dict[col]]
if not query_texts:
raise ValueError("At least one query column with non-empty value is required")
query_input = ' '.join(query_texts)
query_vector = model.encode([query_input], convert_to_numpy=True)
faiss.normalize_L2(query_vector)
distances, indices = index.search(query_vector, top_k)
results = []
for dist, idx in zip(distances[0], indices[0]):
if idx == -1: # no match
continue
# Retrieve original DataFrame row and similarity distance
row_idx = row_id_map[idx]
result_row = df.loc[row_idx].to_dict()
result_row['_similarity'] = float(dist)
results.append(result_row)
return results
# Example queries:
print("Query example 1: Only one column")
results = semantic_search({'Column1': "example search text"}, top_k=3)
for res in results:
print(res)
print("Query example 2: Multiple columns")
results = semantic_search({'Column1': "search text", 'Column2': "extra info"}, top_k=3)
for res in results:
print(res)
Explanation:
We read Excel into a DataFrame.
Concatenate specified columns per row into one string and embed it.
Store embeddings in FAISS index (using cosine similarity via inner product after L2 normalization).
During query, same concatenation and embedding applied.
Search top_k nearest vectors in FAISS and map back to original rows.
This approach lets you perform semantic similarity search using one or multiple columns together flexibly.
Notes:
Adjust index_columns to reflect the columns you want to include.
You can extend this code by saving FAISS index and using persistent storage.
Embedding model choice depends on your data/domain.
For large datasets, consider more advanced FAISS indices (e.g., IndexIVFFlat).
Thanks for the clarification! You want a nested vector store to enable semantic search on Excel data where each column can be individually vectorized, stored, and also supports flexible querying on any single column or multiple columns combined.
What does "nested vector store" mean in this context?
Per-column embeddings: Each column content is embedded separately.
Store per-column vectors in FAISS indexes separately or combined in a nested structure.
Flexible queries:
Query one column embeddings and get best matches from that column.
Because direct concatenation of all columns to a single vector (as in the previous example) is inflexible if:
You want to query only Column2 semantics without mixing Column1.
You want fine-grained control on similarity contributions from each column.
You want to blend multiple column embeddings dynamically.
Solution Outline
For each searchable column:
Calculate embeddings separately (e.g., sentences in Column1, Column2, etc).
Build a separate FAISS index per column.
Maintain a map for each row across all columns.
For query:
You provide dict like {Column1: "text1", Column3: "text3"}.
For each queried column:
Create query embeddings.
Search corresponding column's FAISS.
Retrieve similarity scores.
Aggregate scores across columns (e.g., weighted average or sum).
Return top matches based on combined similarity scores.
Python Code Example
python
import pandas as pd
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer
class NestedVectorStore:
def __init__(self, dataframe, columns):
"""
dataframe: pandas DataFrame with data
columns: list of columns to index
"""
self.df = dataframe.reset_index(drop=True)
self.columns = columns
self.model = SentenceTransformer('all-MiniLM-L6-v2')
self.faiss_indexes = {} # key: col name, value: faiss index
self.embeddings = {} # key: col name, value: np array of embeddings normalized
self.index_to_row = list(range(len(dataframe)))
self.build_indexes()
def build_indexes(self):
for col in self.columns:
# Get only non-null string representations for this column
texts = self.df[col].fillna("").astype(str).tolist()
emb = self.model.encode(texts, convert_to_numpy=True)
faiss.normalize_L2(emb)
dimension = emb.shape[1]
index = faiss.IndexFlatIP(dimension) # cosine similarity over normalized vectors
index.add(emb)
self.faiss_indexes[col] = index
self.embeddings[col] = emb
print(f"Built FAISS indexes for columns: {self.columns}")
def search(self, query_dict, top_k=5, weights=None):
"""
query_dict: dict of {column: query_text} for one or more columns
top_k: number of results to return
weights: dict of weights per column influence e.g. {'Column1':0.7, 'Column2':0.3}
if none, equal weighting assumed
Returns: List of dicts (rows) with similarity scores combined
"""
if not query_dict:
raise ValueError("Query dict cannot be empty")
query_columns = [col for col in self.columns if col in query_dict and query_dict[col].strip()]
if not query_columns:
raise ValueError("No valid query columns with text found")
if weights is None:
weights = {col: 1.0 for col in query_columns}
else:
# Normalize weights to sum to 1
w_sum = sum(weights.get(col, 0) for col in query_columns)
weights = {col: weights.get(col, 0)/w_sum for col in query_columns}
# Accumulate similarity scores per row index
scores_per_row = np.zeros(len(self.df), dtype=np.float32)
for col in query_columns:
query_text = query_dict[col]
query_emb = self.model.encode([query_text], convert_to_numpy=True)
faiss.normalize_L2(query_emb)
index = self.faiss_indexes[col]
distances, indices = index.search(query_emb, top_k=len(self.df)) # search all to get full scores
# distances shape (1, N), indices shape (1, N)
# distances are inner product (cosine sim), higher is better
# Aggregate distances by row index:
# Note: Indices are in order of similarity; but since we retrieved all rows,
# can sum distances into full array by position
for sim, idx in zip(distances[0], indices[0]):
if idx == -1:
continue
# Add weighted similarity to that row
scores_per_row[idx] += weights[col] * sim
# Get top_k rows by combined score
top_indices = np.argsort(-scores_per_row)[:top_k]
results = []
for idx in top_indices:
if scores_per_row[idx] <= 0:
# No similarity - skip since no relevance
continue
row_dict = self.df.iloc[idx].to_dict()
row_dict['_combined_similarity'] = float(scores_per_row[idx])
results.append(row_dict)
return results
# ---- USAGE Example ----
# Load Excel data
df = pd.read_excel('data.xlsx')
cols_to_index = ['Column1', 'Column2', 'Column3'] # replace with your actual columns
store = NestedVectorStore(df, cols_to_index)
# Query example 1: Search using only one column
q1 = {'Column1': "example search text"}
print("Single column query results:")
for res in store.search(q1, top_k=3):
print(res)
# Query example 2: Search using multiple columns with weights
q2 = {'Column1': "example", 'Column3': "other value"}
weights = {'Column1': 0.6, 'Column3': 0.4}
print("\nMulti-column query results:")
for res in store.search(q2, top_k=3, weights=weights):
print(res)
Explanation
NestedVectorStore class:
Builds independent FAISS indexes and embeddings per column.
At query time, queries each column's index with the corresponding text, retrieves similarity.
Combines similarity scores weighted by provided weights per column.
Returns the top-k matching rows sorted by combined similarity.
This allows fully flexible search:
Query any subset of columns.
Tune column importance via weights.
You get a global relevance score by combining per-column semantic similarity.
Additional tips:
For very large datasets, consider approximate FAISS indexes (e.g., IndexIVFFlat).
Persist indexes and load them back with faiss.write_index / faiss.read_index.
Experiment with embedding models per your domain (e.g., OpenAI embeddings).
You can enhance by adding filters pre- or post-search (e.g., exact matches on other columns).
If you want, I can also provide example for persistence and incremental updates or custom similarity scoring. Let me know!