Search Tutorials
--Ads--Storing and Managing Embeddings
Store, version and migrate embeddings safely: formats, metadata, model changes and re-embedding.
Embeddings take time and money to compute, and they are only meaningful together with the model that produced them. A vector from one model cannot be compared with a vector from another, or even with a vector from the same model under a different configuration. This lesson covers how to store embeddings so you never mix them up, how to keep a reusable embedding cache, and how to migrate safely to a new embedding model without downtime.
What you will learn
- What to store with every embedding, and why
- Storage formats for embeddings outside the vector database, and their sizes
- How to build a content-hash embedding cache to avoid recomputing
- How to re-embed a collection with a new model using a blue-green migration
Prerequisites
Installation
pip install numpy sentence-transformers
Step 1: Store the embedding's identity
Record these with every collection (or every vector, if you mix sources):
| Field | Example | Why |
|---|---|---|
| Model name and version | BAAI/bge-small-en-v1.5 | Vectors from different models are incompatible |
| Dimensions | 384 | Catches truncation or the wrong model at write time |
| Normalisation | l2 | Cosine and dot product only agree for normalised vectors |
| Query/document prefixes | BGE query instruction | Changing prefixes changes the vectors |
| Text preprocessing version | chunker-v3 | Same model, different chunk text means different vectors |
| Content hash | SHA-256 of the chunk text | Detects changed text and enables caching |
| Created at | timestamp | Audits and partial re-embedding |
Put the configuration in one place and derive an embedding space id from it. Any change to the model, prefix, normalisation or chunker gives a new id, so it is impossible to search one space with a query from another:
import hashlib
import json
EMBEDDING_CONFIG = {
"model": "BAAI/bge-small-en-v1.5",
"dimensions": 384,
"normalize": "l2",
"query_prefix": "Represent this sentence for searching relevant passages: ",
"chunker": "chunker-v3",
}
def space_id(config: dict) -> str:
digest = hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest()[:10]
return f"{config['model'].split('/')[-1]}-{digest}"
SPACE = space_id(EMBEDDING_CONFIG)
print(SPACE) # e.g. bge-small-en-v1.5-3f9a1c2b7d; use it in the collection name
Naming the vector collection after the space id (for example docs__bge-small-en-v1.5-3f9a1c2b7d) makes the model visible everywhere and makes migrations straightforward.
Step 2: Choose a storage format
The vector database is the serving copy. It is also worth keeping a source-of-truth copy of chunks and embeddings outside it, so you can rebuild or move the index without re-embedding everything.
| Format | Good for | Notes |
|---|---|---|
NumPy .npy + JSONL metadata | Simple pipelines, notebooks | Fast; memory-map large files |
| Parquet | Data pipelines, analytics, cloud storage | Columnar, compressed, stores vectors as list columns with metadata |
| PostgreSQL + pgvector | When the database is also the source of truth | Transactions, backups, joins |
| JSON with float lists | Avoid for large data | Several times larger and slower than binary formats |
Storage size is easy to estimate: vectors × dimensions × bytes per value. One million 384-dimension float32 vectors take 1,000,000 × 384 × 4 bytes = about 1.5 GB; float16 halves that, and int8 quantization quarters it (with a small loss of accuracy).
Step 3: Build a content-hash cache
Most re-indexing runs change only a small part of the corpus. If you key embeddings by the hash of the exact text (plus the space id), unchanged chunks never need to be embedded again:
import sqlite3
import numpy as np
from rag_helpers import embed
class EmbeddingCache:
def __init__(self, path: str = "embedding_cache.db"):
self.db = sqlite3.connect(path)
self.db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, vector BLOB)")
@staticmethod
def key(text: str) -> str:
return SPACE + ":" + hashlib.sha256(text.encode("utf-8")).hexdigest()
def embed(self, texts: list[str]) -> np.ndarray:
keys = [self.key(t) for t in texts]
found = {}
for start in range(0, len(keys), 500): # stay under SQLite's parameter limit
batch = keys[start:start + 500]
placeholders = ",".join("?" * len(batch))
for k, blob in self.db.execute(f"SELECT key, vector FROM cache WHERE key IN ({placeholders})", batch):
found[k] = np.frombuffer(blob, dtype=np.float32)
missing = [i for i, k in enumerate(keys) if k not in found]
if missing:
new_vectors = embed([texts[i] for i in missing]).astype(np.float32)
self.db.executemany("INSERT OR REPLACE INTO cache VALUES (?, ?)",
[(keys[i], v.tobytes()) for i, v in zip(missing, new_vectors)])
self.db.commit()
for i, v in zip(missing, new_vectors):
found[keys[i]] = v
print(f"cache hits: {len(texts) - len(missing)}/{len(texts)}")
return np.vstack([found[k] for k in keys])
cache = EmbeddingCache()
vectors = cache.embed(["Employees get 18 days of paid leave.", "Expense claims are due in 30 days."])
vectors = cache.embed(["Employees get 18 days of paid leave.", "Laptops are replaced every 3 years."])
cache hits: 0/2
cache hits: 1/2
Because the space id is part of the key, switching models automatically misses the cache instead of returning incompatible vectors. Only cache document embeddings; query embeddings are cheap and too varied to be worth it in most systems.
Step 4: Migrate to a new embedding model
You will change embedding models: a better one is released, you move to a multilingual model, or you fine-tune your own. Because old and new vectors cannot be mixed, use a blue-green migration:
- Build green: create a new collection named after the new space id and re-embed all chunks into it, while the old (blue) collection keeps serving.
- Dual-write: while the backfill runs, send new and changed documents to both collections.
- Evaluate: run your golden test set against both; switch only if retrieval quality improves (see Retrieval Metrics).
- Switch: point the application's query path, including the query embedding model and prefix, at the green collection with a configuration change.
- Keep blue briefly for rollback, then delete it.
ACTIVE_SPACES = {"docs": "bge-small-en-v1.5-3f9a1c2b7d"} # stored in config, not code
def collection_for(corpus: str) -> str:
return f"{corpus}__{ACTIVE_SPACES[corpus]}"
# The query must be embedded with the SAME space's model and prefix as the collection.
The most common migration bug is switching the collection but not the query model (or the reverse). Results then look plausible but are close to random. Keeping the model configuration next to the collection name prevents it.
Common errors and troubleshooting
- Dimension mismatch errors: the query model differs from the index model; check the space id on both paths.
- Quality suddenly drops with no error: same dimensions, different model or prefix; the vectors are incompatible but the database cannot tell.
- Cache returns wrong-sized vectors: the cache key does not include the model configuration.
- Huge JSON exports: store vectors in binary formats (npy, Parquet, database columns).
Key takeaways
- An embedding is only meaningful with its model, dimensions, normalisation, prefixes and chunker version.
- Derive a space id from that configuration and use it in collection names and cache keys.
- Keep a source-of-truth copy of chunks and vectors, and cache by content hash to avoid re-embedding.
- Change models with a blue-green migration: build, dual-write, evaluate, switch, then retire.
Frequently asked questions
Can I convert old vectors to a new model's space?
Not reliably. Research on learned mappings between embedding spaces exists, but re-embedding the text is the dependable approach, which is why you keep the chunk text.
Do API embedding models change over time?
Providers usually keep a model name stable and release new names for new versions, but read their deprecation notices: when a model is retired you must re-embed.
Practice exercises
- Add the cache to your indexing pipeline and measure how much of a re-index run it saves.
- Simulate a migration: build a second collection with a different model and compare recall@5 on your test set.