In-App Semantic Search with Zvec (No External Vector DB Required)
A Step-by-Step Python Tutorial to Build Local, Embedded Vector Search Using Alibaba Zvec and Sentence Transformers
On this page8 sections
Full Article
Read the complete article, including examples, background, practical insights, and technical details.
In our earlier overview, Alibaba Just Dropped Zvec — A Vector Database That Runs Inside Your App, we covered why Zvec matters: it brings Proxima-grade vector indexing directly into your Python process with zero external servers, zero Docker containers, and zero network latency.
In this step-by-step tutorial, you’ll build a 100% local, persistent semantic search engine inside a Python script—combining zvec for embedded vector storage and sentence-transformers for local embeddings.
Prerequisites
You need 64-bit Python (3.10–3.14) and pip.
Install zvec and sentence-transformers:
pip install zvec sentence-transformersWhy
sentence-transformers? It runs a lightweight embedding model (all-MiniLM-L6-v2, 384 dimensions) locally on your CPU, so your entire search pipeline works offline with no API keys.
Step 1: Define a Collection Schema
Zvec stores documents in a Collection. Each collection has:
- Scalar fields (
FieldSchema) for metadata like titles, categories, or years. - Vector fields (
VectorSchema) for dense embeddings and their index configuration (HnswIndexParamwith cosine similarity).
import zvec
schema = zvec.CollectionSchema(
name="knowledge_base",
fields=[
zvec.FieldSchema(name="title", data_type=zvec.DataType.STRING),
zvec.FieldSchema(
name="category",
data_type=zvec.DataType.STRING,
index_param=zvec.InvertIndexParam(),
),
],
vectors=[
zvec.VectorSchema(
name="embedding",
data_type=zvec.DataType.VECTOR_FP32,
dimension=384, # Matches all-MiniLM-L6-v2
index_param=zvec.HnswIndexParam(metric_type=zvec.MetricType.COSINE),
),
],
)Adding InvertIndexParam() on category enables fast metadata filtering alongside vector search.
Step 2: Create or Open the Embedded Database
Zvec persists data directly to a local directory—similar to how SQLite stores a database in a local file.
from pathlib import Path
DB_PATH = "./zvec_kb"
if Path(DB_PATH).exists():
collection = zvec.open(path=DB_PATH)
else:
collection = zvec.create_and_open(path=DB_PATH, schema=schema)No background daemon, no port binding, and no connection strings.
Step 3: Embed and Insert Documents
Convert your text documents into 384-dimensional float vectors and insert them as zvec.Doc objects:
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("all-MiniLM-L6-v2")
articles = [
{
"id": "doc_1",
"title": "Getting Started with Spec-Driven Development",
"category": "devops",
"text": "Validate pull requests against a versioned spec.md using GitHub Actions.",
},
{
"id": "doc_2",
"title": "Building Tool-Using Agents with SmolAgents",
"category": "agents",
"text": "Use Hugging Face CodeAgent to write and execute Python tools safely.",
},
{
"id": "doc_3",
"title": "Embedded Vector Search with Zvec",
"category": "databases",
"text": "Run fast HNSW vector similarity search inside your Python app without Docker.",
},
]
docs = []
for item in articles:
vector = embedder.encode(f"{item['title']}. {item['text']}").tolist()
docs.append(
zvec.Doc(
id=item["id"],
vectors={"embedding": vector},
fields={"title": item["title"], "category": item["category"]},
)
)
collection.insert(docs)Step 4: Run Semantic Search Queries
Encode a natural-language query into a vector and search the collection:
query_text = "How do I run vector search locally without a separate server?"
query_vector = embedder.encode(query_text).tolist()
results = collection.query(
vectors=zvec.VectorQuery(field_name="embedding", vector=query_vector),
topk=2,
)
for doc in results:
print(f"[{doc.score:.4f}] {doc.id} -> {doc.fields.get('title')} ({doc.fields.get('category')})")Note: Depending on the
zvecrelease you install,collection.query(...)acceptszvec.VectorQuery(...)orzvec.Query(...). Checkhelp(collection.query)in Python if you want to inspect all available filter and output parameters for your installed version.
Step 5: Complete Runnable Script (semantic_search.py)
Save the full example below and run python semantic_search.py:
from pathlib import Path
from sentence_transformers import SentenceTransformer
import zvec
DB_PATH = "./zvec_kb"
schema = zvec.CollectionSchema(
name="knowledge_base",
fields=[
zvec.FieldSchema(name="title", data_type=zvec.DataType.STRING),
zvec.FieldSchema(
name="category",
data_type=zvec.DataType.STRING,
index_param=zvec.InvertIndexParam(),
),
],
vectors=[
zvec.VectorSchema(
name="embedding",
data_type=zvec.DataType.VECTOR_FP32,
dimension=384,
index_param=zvec.HnswIndexParam(metric_type=zvec.MetricType.COSINE),
),
],
)
is_new = not Path(DB_PATH).exists()
collection = zvec.create_and_open(path=DB_PATH, schema=schema) if is_new else zvec.open(path=DB_PATH)
embedder = SentenceTransformer("all-MiniLM-L6-v2")
if is_new:
articles = [
("doc_1", "Spec-Driven Development in CI/CD", "devops", "Validate PRs against spec.md in GitHub Actions."),
("doc_2", "Tool-Using Agents with SmolAgents", "agents", "Build Python CodeAgent workflows in under 50 lines."),
("doc_3", "Embedded Vector Search with Zvec", "databases", "Run local HNSW vector search without Docker or servers."),
]
collection.insert([
zvec.Doc(
id=doc_id,
vectors={"embedding": embedder.encode(f"{title}. {body}").tolist()},
fields={"title": title, "category": category},
)
for doc_id, title, category, body in articles
])
query_vec = embedder.encode("How can I add semantic search without managing a database server?").tolist()
results = collection.query(
vectors=zvec.VectorQuery(field_name="embedding", vector=query_vec),
topk=3,
)
for doc in results:
print(f"[{doc.score:.4f}] {doc.id}: {doc.fields.get('title')} ({doc.fields.get('category')})")On the first run, it embeds the sample articles, writes the index to ./zvec_kb, and returns ranked results. On subsequent runs, it opens ./zvec_kb directly from disk in milliseconds.
When to Use Embedded Zvec vs. a Managed Vector DB
- Use Zvec when: You are building a CLI tool, desktop/edge app, local RAG prototype, or single-node backend API where simplicity, zero network hops, and low cost matter most.
- Use a client-server vector DB when: Multiple independent microservices need concurrent write access to the same shared index across a distributed cluster.
To learn more about the architecture behind Zvec and Proxima, read the companion overview: Alibaba Just Dropped Zvec — A Vector Database That Runs Inside Your App.
Related Articles
Comments load as you scroll…