Build semantic search in Python with ITZMA
Embed documents with an open model, store them in ITZMA, and query them by meaning, with an attribute filter.
On this page
What you’ll build
Semantic search finds documents by meaning rather than by matching words: “How does the index find nearest neighbors?” should find a passage about graph search even though it shares almost no words with it. It works in two steps. An embedding model turns each text into a vector, so texts that mean similar things get nearby vectors. A vector database stores those vectors and returns the ones nearest a query’s vector.
ITZMA is the second step. It does not embed text; your application calls a model and hands ITZMA the vectors. This guide uses all-MiniLM-L6-v2, a small open model that runs on a laptop CPU through the sentence-transformers package. Any model works, local or behind an API, as long as every vector in a namespace comes from the same one.
The same steps are the retrieval half of retrieval-augmented generation (RAG): the passages a query finds are what you put in front of a language model.
Install
pip install itzma sentence-transformersitzma has wheels for macOS and Linux, Python 3.10 and later. The first run downloads the model, about 90 MB.
Embed the documents
Each document gets an id, its text and a topic attribute to filter on. normalize_embeddings=True scales every vector to length 1, the usual choice for cosine distance.
import itzma
from itzma import attr
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
docs = [
{"id": "s3-durability", "text": "A write is in the bucket before the call returns.", "topic": "storage"},
{"id": "hnsw", "text": "HNSW walks a graph of neighbors to find close vectors fast.", "topic": "indexing"},
{"id": "sq8", "text": "SQ8 stores one byte per dimension and reads only the partitions it probes.", "topic": "indexing"},
{"id": "filters", "text": "Typed attributes narrow a vector query to matching documents.", "topic": "querying"},
{"id": "gc", "text": "Garbage collection deletes segments that a merge replaced.", "topic": "storage"},
]
vectors = model.encode([d["text"] for d in docs], normalize_embeddings=True)Store them
A namespace’s schema fixes the vector dimension, the metric and each attribute’s type. The dimension comes from the model: 384 for this one. Keeping the text as an attribute lets a hit carry it back, which is what a RAG prompt needs.
store = itzma.Store("memory://") # or "s3://bucket/prefix", "gs://bucket/prefix", "az://container/prefix"
schema = itzma.Schema(
dim=vectors.shape[1],
metric=itzma.Metric.COSINE,
attrs={"topic": itzma.AttrType.STRING, "text": itzma.AttrType.STRING},
)
ns = itzma.Namespace.create(store, "articles", schema)
ns.upsert(
ids=[d["id"] for d in docs],
vectors=vectors,
attrs=[{"topic": d["topic"], "text": d["text"]} for d in docs],
)upsert takes NumPy arrays of any float dtype, a list of dicts, or an Arrow, Polars or DuckDB table. Once it returns, the documents are stored and searchable.
Query by similarity
A query embeds the question with the same model and asks for the nearest vectors. Hits come back closest first; with cosine, the distance is one minus the similarity, so lower is closer.
def search(question, top_k=3, where=None):
query = model.encode(question, normalize_embeddings=True)
return ns.query(query, top_k=top_k, filter=where)
for hit in search("How does the index find nearest neighbors?"):
print(f"{hit.distance:.3f} {hit.id} {hit.attrs['text']}")0.518 hnsw HNSW walks a graph of neighbors to find close vectors fast.
0.778 sq8 SQ8 stores one byte per dimension and reads only the partitions it probes.
0.787 filters Typed attributes narrow a vector query to matching documents.The passage about graph search comes first, though the only word it shares with the question is “neighbors”. Exact distances can differ slightly between versions of the model.
Filter by an attribute
A filter narrows the query to documents whose attributes match. Build it from attr(name) with comparison operators:
print()
for hit in search("Is my data safe once I write it?", where=attr("topic") == "storage"):
print(f"{hit.distance:.3f} {hit.id} {hit.attrs['topic']}")0.721 s3-durability storage
0.891 gc storageOnly the two storage documents can match, so the query returns two hits even though it asked for three. Conditions combine with &, | and ~; wrap each comparison in parentheses, as in (attr("topic") == "storage") | (attr("topic") == "querying"). Filtering lists every operator.
The four Python blocks above, in order, are a complete script.
Taking it to production
- Keep the data.
memory://lasts as long as the process. Point the store at a bucket,s3://,gs://oraz://, and open the namespace withNamespace.openin later runs. Vector search on object storage explains what that costs and why it is durable. - Keep it fast. New writes land in a log that queries read until something compacts it, and indexes are built per compacted segment. Start the background maintainer with
ns.start_maintenance(timedelta(seconds=60)), or schedulemaintainandindexyourself (Maintenance). - Load in bulk. For many documents, embed in batches and pass each batch’s matrix to
upsert. Arrow tables are written in bounded memory (Writing). - Change models deliberately. Vectors from different models are not comparable, and a namespace’s dimension is fixed. A new model means a new namespace, filled again.
- Serve it. In a web server, open the namespace once per process and share the handle; the async API never blocks the event loop (Python API).
