Working with Embeddings
LatticeDB supports storing and searching vector embeddings on nodes. This guide covers the embedding options and how to use them.
Overview
To use embeddings:
- Enable vector storage when creating the database
- Generate embeddings (built-in hash or external service)
- Attach embeddings to nodes
- Search by similarity
Enabling Vector Storage
from latticedb import Database
db = Database(
"mydb.db",
create=True,
enable_vectors=True,
vector_dimensions=128, # Must match your embedding dimensions
vector_metric="cosine", # or "euclidean" or "dot_product"; fixed once created
)
db.open()
const db = new Database("mydb.db", {
create: true,
enableVectors: true,
vectorDimensions: 128,
});
await db.open();
The vector index is created with the database, and its configuration (dimensions,
metric, vector_m, vector_ef_construction) is stored in the file. Later opens
need no vector options: Database("mydb.db") opens the index as it was created,
also after a crash. An option you do pass must match the file, or the open fails
with a configuration-mismatch error (LatticeConfigMismatchError in Python). The
TypeScript options are vectorMetric, vectorM and vectorEfConstruction; the
CLI's are lattice create --vector-metric=cosine|euclidean|dot_product --vector-m=<n> --vector-ef-construction=<n>.
The metric decides what a distance means, and smaller is always nearer: cosine distance (1 minus cosine similarity, the default and the usual choice for text embeddings), Euclidean (L2) distance, or the negated dot product. It cannot be changed once the index exists; to change it, export the database and import it into one created with the new metric. See Distance Metric.
A node holds one vector, and Cypher reads it as n.embedding. set_vector takes
a key argument, which must be "embedding" (an empty key also works); any other
key is rejected with an unsupported-operation error rather than stored under that
name. Setting a vector on a node that already has one replaces it. On a database
created without a vector index, setting a vector, inserting nodes with vectors and
searching them fail with an unsupported-operation error that says so (before
0.18.1, an I/O error); opening the database with vectors enabled adds an index.
get_vector reads a node's vector back, and remove_vector takes it away: the
node stays, with its labels and properties, and vector search no longer returns
it. Removing a vector the node does not have does nothing. In Cypher,
REMOVE n.embedding and SET n.embedding = null do the same, and
SET n.embedding = $vector (or embedding in a CREATE or MERGE map) sets
the vector, on a database with a vector index. Removing a node's
labels leaves its vector alone, and deleting the node removes it.
with db.write() as txn:
vector = txn.get_vector(node.id) # None if the node has no vector
txn.remove_vector(node.id)
txn.commit()
The other bindings have the same calls: getVector/removeVector in
TypeScript and Java, GetVector/RemoveVector in Go, and
lattice_node_get_vector/lattice_node_remove_vector in C. Before 0.18.0 there
was no way to remove a vector short of deleting the node.
Every component must be a finite number: a vector containing NaN or infinity is rejected with an invalid-argument error, both when stored and when used as a search query. Under the cosine metric the database keeps only the normalised (unit-length) copy of a vector, so a committed vector reads back normalised. Under the Euclidean and dot-product metrics vectors are kept as given.
Hash Embeddings (Built-in)
hash_embed generates deterministic embeddings from text without an external service. It uses feature hashing to map text tokens to a fixed-dimension vector.
When to use: Testing, prototyping, or when keyword-level similarity is sufficient.
Python:
from latticedb.embedding import hash_embed
vec = hash_embed("hello world", dimensions=128)
# Returns a numpy array of shape (128,)
TypeScript:
import { hashEmbed } from "@hajewski/latticedb/embedding";
const vec = hashEmbed("hello world", 128);
// Returns a Float32Array of length 128
HTTP Embedding Client
For production-quality semantic embeddings, use the HTTP client to connect to an embedding service.
The endpoint is the full URL the client POSTs to; nothing is appended to it. Give
Ollama's /api/embeddings path or OpenAI's /v1/embeddings path, not the
server's base URL: given http://localhost:11434 alone, the client POSTs to /
on that server, which does not serve embeddings, and embed fails. The client
copies the endpoint, model and API key when it is created.
The timeout setting (timeout_ms in Python and C, timeoutMs in TypeScript and
Java, TimeoutMS in Go; 30 seconds by default, or when set to 0) is how long the
client waits for the server to start answering. A request that gets no response in that time fails with an I/O
error. Connecting, and reading the rest of a response that has begun, are not
bounded by it, and it is not applied on Windows.
Ollama
from latticedb.embedding import EmbeddingClient
with EmbeddingClient("http://localhost:11434/api/embeddings") as client:
vec = client.embed("hello world")
import { EmbeddingClient } from "@hajewski/latticedb/embedding";
const client = new EmbeddingClient({
endpoint: "http://localhost:11434/api/embeddings",
});
const vec = client.embed("hello world");
client.close();
OpenAI
from latticedb.embedding import EmbeddingClient, EmbeddingApiFormat
with EmbeddingClient(
"https://api.openai.com/v1/embeddings",
model="text-embedding-3-small",
api_format=EmbeddingApiFormat.OPENAI,
api_key="sk-...",
) as client:
vec = client.embed("hello world")
import { EmbeddingClient, EmbeddingApiFormat } from "@hajewski/latticedb/embedding";
const client = new EmbeddingClient({
endpoint: "https://api.openai.com/v1/embeddings",
model: "text-embedding-3-small",
apiFormat: EmbeddingApiFormat.OpenAI,
apiKey: "sk-...",
});
const vec = client.embed("hello world");
client.close();
Storing Embeddings
Attach a vector to a node within a write transaction:
from latticedb.embedding import hash_embed
with db.write() as txn:
node = txn.create_node(labels=["Chunk"], properties={"text": "some text"})
embedding = hash_embed("some text", dimensions=128)
txn.set_vector(node.id, "embedding", embedding)
txn.commit()
Searching
Programmatic API
query_vec = hash_embed("search query", dimensions=128)
results = db.vector_search(query_vec, k=10, ef_search=64)
for r in results:
print(f"Node {r.node_id}: distance={r.distance:.4f}")
Cypher
MATCH (n:Chunk)
WHERE n.embedding <=> $query < 0.5
RETURN n.text
ORDER BY n.embedding <=> $query
LIMIT 10
In Cypher, <=> in WHERE searches among the nodes your pattern matches: a
threshold query returns every Chunk within the distance, however many there are
and whatever other nodes are nearer, and a LIMIT stops the search once it has
enough, also when an ORDER BY on the same distance comes between them. For the
nearest k over the whole database, use vector_search. See
Vector Search in Cypher.
Batch Insert
For bulk loading, batch_insert_vectors creates a node and stores its vector for
every row in one call. It saves one binding call per node; each vector still goes
into the HNSW index individually:
import numpy as np
with db.write() as txn:
vectors = np.random.rand(10000, 128).astype(np.float32)
node_ids = txn.batch_insert_vectors("Document", vectors)
txn.commit()
Choosing Dimensions
The vector_dimensions parameter is set when the database is created, is stored in the file, and must match the embedding model output:
| Model | Dimensions |
|---|---|
hash_embed (built-in) | Configurable (default 128) |
text-embedding-3-small (OpenAI) | 1536 |
text-embedding-3-large (OpenAI) | 3072 |
nomic-embed-text (Ollama) | 768 |
mxbai-embed-large (Ollama) | 1024 |
Higher dimensions capture more semantic nuance but use more memory and slow down search.