-
Install Necessary Libraries:
faiss-cpu or faiss-gpu (depending on your needs and hardware)
numpy
- The sentence transformer library used by
txtai (e.g., sentence-transformers)
pip install faiss-cpu numpy sentence-transformers
# or for GPU:
# pip install faiss-gpu numpy sentence-transformers
-
Identify txtai Database Files: Locate the directory where txtai saved its output. You should find files like config.json, index.faiss, and index.npy.
-
Load Configuration: Read config.json to get essential information, primarily the vector dimension.
import json
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer # Or the specific library txtai used
# --- Configuration ---
# Replace with the actual path to your txtai database directory
txtai_db_path = "/path/to/your/txtai_database"
config_file = "config.json"
faiss_index_file = "index.faiss"
id_map_file = "index.npy" # Often named like this
# --- Load Configuration ---
try:
with open(f"{txtai_db_path}/{config_file}", 'r') as f:
config = json.load(f)
print("Loaded config:", config)
except FileNotFoundError:
print(f"Error: config.json not found at {txtai_db_path}")
exit()
except Exception as e:
print(f"Error reading config file: {e}")
exit()
# Extract dimension (crucial!) - the key name might vary slightly
# Common keys: 'dimension', 'vector_dimension', 'dim'
vector_dimension = config.get('dimension')
if vector_dimension is None:
# Try other common names if the first fails
vector_dimension = config.get('vector_dimension')
if vector_dimension is None:
print("Error: Could not determine vector dimension from config.json.")
# You might need to inspect config.json manually to find the correct key
# or know it from when you created the index.
exit()
print(f"Detected vector dimension: {vector_dimension}")
-
Load the Faiss Index: Use faiss.read_index to load the index file.
# --- Load Faiss Index ---
try:
index = faiss.read_index(f"{txtai_db_path}/{faiss_index_file}")
print(f"Successfully loaded Faiss index. Index type: {type(index)}")
print(f"Index dimension: {index.d}, Number of vectors: {index.ntotal}")
if index.d != vector_dimension:
print(f"Warning: Dimension mismatch between config ({vector_dimension}) and index ({index.d}). Using index.d.")
vector_dimension = index.d # Prefer the index's actual dimension
except Exception as e:
print(f"Error loading Faiss index from {faiss_index_file}: {e}")
exit()
Note: faiss.read_index is usually good at inferring the index type, but if you encounter issues, you might need to explicitly know the index type (e.g., IndexFlatL2, IndexIVFFlat) and load it using the corresponding Faiss class constructor, though this is less common.
-
Load Document ID Mapping: Load the .npy file containing the mapping. This array holds the original IDs in the same order as the vectors in the Faiss index.
# --- Load Document ID Mapping ---
try:
doc_ids = np.load(f"{txtai_db_path}/{id_map_file}")
print(f"Loaded {len(doc_ids)} document IDs from {id_map_file}")
# Ensure the number of IDs matches the number of vectors in the index
if len(doc_ids) != index.ntotal:
print(f"Warning: Number of document IDs ({len(doc_ids)}) does not match index size ({index.ntotal}).")
except FileNotFoundError:
print(f"Error: ID mapping file '{id_map_file}' not found at {txtai_db_path}. Cannot map results back to original IDs.")
doc_ids = None # Set to None if not found
except Exception as e:
print(f"Error loading ID mapping file: {e}")
doc_ids = None
-
Load the Embedding Model: Load the exact same model txtai used. You can often find the model name in config.json (e.g., under pipeline or embedding sections).
# --- Load Embedding Model ---
# Find the model name in config.json, e.g., config['pipeline'][0]['model']
# Adjust this line based on your actual config file structure
embedding_model_name = config.get('pipeline', [{}])[0].get('model', 'all-MiniLM-L6-v2') # Example default
print(f"Attempting to load embedding model: {embedding_model_name}")
try:
# Ensure you're using the same model class txtai used
embedder = SentenceTransformer(embedding_model_name)
print("Embedding model loaded successfully.")
except Exception as e:
print(f"Error loading embedding model '{embedding_model_name}': {e}")
exit()
-
Generate Query Vector: Convert your search query text into a vector using the loaded model.
# --- Prepare Query ---
query_text = "your search query here"
query_vector = embedder.encode([query_text]) # Pass query as a list
# Ensure query vector dimension matches index dimension
if query_vector.shape[1] != vector_dimension:
print(f"Error: Query vector dimension ({query_vector.shape[1]}) does not match index dimension ({vector_dimension}).")
exit()
print(f"Query vector shape: {query_vector.shape}")
-
Perform Similarity Search: Use the Faiss index's search method.
# --- Perform Search ---
k = 5 # Number of nearest neighbors to retrieve
print(f"Searching for top {k} nearest neighbors...")
# Faiss expects a 2D array [num_queries, dimension]
distances, indices = index.search(query_vector, k)
print(f"Search results (indices): {indices}")
print(f"Search results (distances): {distances}")
-
Map Results to Document IDs: Use the loaded doc_ids array to find the original IDs corresponding to the Faiss indices.
# --- Map Results to Document IDs ---
if doc_ids is not None:
print(f"\nTop {k} results:")
# indices[0] because we only had one query vector
for i, idx in enumerate(indices[0]):
if idx >= 0 and idx < len(doc_ids): # Check if index is valid
original_doc_id = doc_ids[idx]
distance = distances[0][i]
print(f" - Rank {i+1}: Document ID: '{original_doc_id}', Distance: {distance:.4f}")
else:
print(f" - Rank {i+1}: Invalid index ({idx}) returned by Faiss.")
else:
print("\nCould not map results to document IDs because the ID mapping file was not loaded.")
print("You only have the Faiss index positions. You'll need to manually inspect or load document data separately.")
This process allows you to leverage the optimized C++ backend of Faiss directly while using the metadata generated by txtai to understand the structure and mapping.