FastPlaid features an optional metadata filtering engine powered by SQLite. When you provide a metadata parameter during .create() or .update() calls, FastPlaid stores this information in a searchable database within your index directory.
To filter search results based on metadata, use fast_plaid.filtering.where() to execute standard SQL conditions. This returns a list of embedding IDs (a subset) that you can pass to the subset parameter of the .search() method to pre-filter your vector search.
Key functions:
fast_plaid.filtering.where(index, condition, parameters): Returns a subset of IDs matching the SQL condition.fast_plaid.search(..., subset=subset): Performs vector search restricted to the provided IDs.fast_plaid.filtering.get(index, subset): Retrieves the metadata for the specified subset of documents.
from datetime import date
import torch
from fast_plaid import filtering, search
# 1. Initialize the FastPlaid index
fast_plaid = search.FastPlaid(index="metadata_index")
embedding_dim = 128
# 2. Create initial documents with metadata
initial_embeddings = [torch.randn(10, embedding_dim) for _ in range(3)]
initial_metadata = [
{"name": "Alice", "category": "A", "join_date": date(2023, 5, 17)},
{"name": "Bob", "category": "B", "join_date": date(2021, 6, 21)},
{"name": "Alex", "category": "A", "join_date": date(2023, 8, 1)},
]
fast_plaid.create(documents_embeddings=initial_embeddings, metadata=initial_metadata)
# 3. Update the index with new documents and metadata
new_embeddings = [torch.randn(10, embedding_dim) for _ in range(2)]
new_metadata = [
{"name": "Charlie", "category": "B", "join_date": date(2020, 3, 15)},
{
"name": "Amanda",
"category": "A",
"join_date": date(2024, 1, 10),
"status": "active",
},
]
fast_plaid.update(documents_embeddings=new_embeddings, metadata=new_metadata)
# 4. Use filtering.where to get the corresponding rows of the FastPlaid index
subset = filtering.where(
index="metadata_index",
condition="name LIKE ? AND join_date > ?",
parameters=("A%", "2022-12-31"),
)
# 5. Perform a search restricted to the filtered subset
query_embedding = torch.randn(1, 5, embedding_dim)
scores = fast_plaid.search(queries_embeddings=query_embedding, top_k=3, subset=subset)
print("Search results within the subset:")
print(scores)
# 6. Access to the metadata of the retrieved documents
for match in scores:
print("Metadata of matched documents:")
print(filtering.get(index="metadata_index", subset=[subset for subset, _ in match]))