An embedding is a function from a thing to a point in space, such that similar things land near each other. An embedding model takes text (or an image, or audio) and returns a fixed-length list of floats - 384, 768, 1536, 3072 are common lengths. The model was trained so that "how do I reset my password" and "I forgot my login details" produce nearby points, and "the mitochondrion is the powerhouse of the cell" produces a distant one. That is the entire idea, and everything a vector database does is arithmetic on those points.
The dimension is fixed by the model and cannot be changed. An index created for 768 dimensions accepts only 768-dimensional vectors. So the model choice is baked into the index, and changing the model means creating a new index and re-embedding everything - which Module 5 treats as the migration it is.
There are three similarity metrics and choosing the wrong one silently degrades your results.
- Cosine measures the angle between vectors, ignoring magnitude. It is the right default for text embeddings from most models.
- Dot product measures angle and magnitude. For normalised vectors (length 1) it is mathematically equivalent to cosine and slightly cheaper. For unnormalised vectors it favours longer ones, which may or may not be what you want.
- Euclidean measures straight-line distance. Correct for some models and some non-text domains.
The rule is to use the metric the model's documentation specifies. If a model was trained with a cosine objective and you query with Euclidean, the results are not an error - they are a ranked list in a slightly wrong order, which is exactly the kind of fault that survives into production. The practical tell: if your results look "mostly sensible but subtly off", check the metric first.
An index is a named collection of vectors with a fixed dimension and metric. Namespaces partition an index: vectors in one namespace are invisible to a query in another, queries can only target one namespace, and namespaces are free. That makes them the natural tenant isolation mechanism, and Module 6 builds on it.
Each vector has an id, the values, and optional metadata - a flat map of strings, numbers, booleans and string arrays, used for filtering. Metadata is not searchable except through filters, there is no nesting, and there is a size limit per vector, so metadata is for filters and small payloads rather than for storing your documents.
Build the ground-truth set in this module. Thirty to fifty questions, each with the document or chunk ids that genuinely answer it, written by a human who read them. It is tedious, it takes an afternoon, and without it every subsequent decision in this course is a guess. This is the single highest-value artefact you will produce.
Laboratory exercise 1 - provision, load and build the ground truth.
Create a Pinecone Serverless index. Record the dimension, the metric, the cloud and region, and the embedding model you chose with the metric its documentation specifies.
Embed and load at least 5,000 documents from a real corpus - documentation, a book, support articles, anything with genuine questions attached. Record the chunking you used, even though Module 2 will change it.
Build the ground-truth set: at least 30 questions, each with the ids that answer it, in a versioned file. Write them by hand and read the documents.
Then demonstrate the metric mismatch, which is the module's point: create two indexes over the same vectors, one with cosine and one with Euclidean, and run your ground-truth questions against both. Record recall@5 for each. The difference is a fault that produces no error.
Then demonstrate namespaces: load two tenants' data into two namespaces, query one and show the other's vectors absent.
Finally, record the limits you hit: the metadata size, the batch size, and the dimension immutability (try to upsert a wrong-dimension vector and capture the error).
Deliverable: an idempotent index creation and load script, the versioned ground-truth file, a README with the model and metric and why, the metric mismatch comparison with recall@5 for both, the namespace isolation evidence, and the three limit demonstrations.
# ------------------------------------------------------------------
# There is NO LOCAL PINECONE. No emulator, no container. Worth
# knowing before you plan the work.
# ------------------------------------------------------------------
import os, json, hashlib
from pinecone import Pinecone, ServerlessSpec
from sentence_transformers import SentenceTransformer
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
# ------------------------------------------------------------------
# THE MODEL DECIDES THE DIMENSION AND THE METRIC. Both are baked
# into the index.
# ------------------------------------------------------------------
MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
model = SentenceTransformer(MODEL_NAME)
DIM = model.get_sentence_embedding_dimension() # 768
# *** READ THE MODEL'S DOCUMENTATION FOR THE METRIC. *** This one
# specifies cosine. Using Euclidean instead is not an error - it is
# a ranked list in a slightly wrong order, which survives into
# production unnoticed.
METRIC = "cosine"
pc.create_index(
name="docs-v1",
dimension=DIM,
metric=METRIC,
spec=ServerlessSpec(cloud="aws", region="us-east-1"),
)
index = pc.Index("docs-v1")
print(pc.describe_index("docs-v1"))
# {'dimension': 768, 'metric': 'cosine', 'status': {'ready': True},
# 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-east-1'}}}
# *** THE DIMENSION CANNOT BE CHANGED. *** So the model choice is
# baked in, and changing models means A NEW INDEX AND RE-EMBEDDING
# EVERYTHING (Module 5):
try:
index.upsert([("bad", [0.1] * 384)]) # wrong dimension
except Exception as e:
print(e) # Vector dimension 384 does not match the dimension
# of the index 768
# ------------------------------------------------------------------
# A VECTOR: id, values, and FLAT metadata for filtering.
# ------------------------------------------------------------------
index.upsert(
vectors=[{
"id": "doc-0001#chunk-00",
"values": model.encode("How do I reset my password?").tolist(),
"metadata": {
"doc_id": "doc-0001",
"title": "Resetting your password",
"section": "account",
"published": 1764500460, # epoch: numbers filter
"public": True,
"tags": ["account", "security"], # string arrays filter
# A SMALL excerpt, not the document. Metadata has a size
# limit per vector, it is not searchable except through
# filters, and it cannot nest.
"excerpt": "Open Settings, choose Security, then..."[:500],
},
}],
namespace="tenant-acme",
)
# METADATA IS FOR FILTERS AND SMALL PAYLOADS. Store the documents
# somewhere else - object storage, a relational database - and keep
# an id here. A design that puts whole documents in metadata hits
# the limit at the size nobody predicted.
# ------------------------------------------------------------------
# NAMESPACES: free, and they are your tenant isolation.
# ------------------------------------------------------------------
index.upsert(vectors=[...], namespace="tenant-acme")
index.upsert(vectors=[...], namespace="tenant-globex")
r = index.query(vector=qv, top_k=5, namespace="tenant-acme")
# Vectors in tenant-globex are INVISIBLE here. A query targets
# EXACTLY ONE namespace - there is no cross-namespace search, which
# is precisely what makes this isolation rather than a convention.
print(index.describe_index_stats())
# {'namespaces': {'tenant-acme': {'vector_count': 4212},
# 'tenant-globex': {'vector_count': 3901}},
# 'total_vector_count': 8113, 'dimension': 768}
# ------------------------------------------------------------------
# *** THE THREE METRICS, AND WHY THE CHOICE MATTERS. ***
# ------------------------------------------------------------------
# COSINE the ANGLE between vectors; magnitude ignored.
# The right default for text embeddings.
# DOTPRODUCT angle AND magnitude. For NORMALISED vectors
# (length 1) it is MATHEMATICALLY EQUIVALENT to cosine
# and slightly cheaper. For unnormalised vectors it
# FAVOURS LONGER ONES.
# EUCLIDEAN straight-line distance. Correct for some models and
# some non-text domains.
#
# *** USE THE METRIC THE MODEL'S DOCUMENTATION SPECIFIES. *** And if
# your results look "mostly sensible but subtly off", CHECK THE
# METRIC FIRST - it is the cheapest thing to rule out.
import numpy as np
v = model.encode("How do I reset my password?")
print(np.linalg.norm(v)) # ~1.0 if the model normalises, in
# which case cosine and dotproduct
# agree and euclidean is monotonically
# related - but the SCORES differ, so
# any threshold you tuned is wrong.
# ------------------------------------------------------------------
# *** BUILD THE GROUND-TRUTH SET. The highest-value artefact in this
# *** course, and the one people skip. ***
# ------------------------------------------------------------------
GROUND_TRUTH = [
{"q": "How do I reset my password?",
"relevant": ["doc-0001#chunk-00", "doc-0001#chunk-01",
"doc-0044#chunk-03"]},
{"q": "What is the refund window?",
"relevant": ["doc-0117#chunk-02"]},
# ... at least 30, written BY HAND, by someone who READ the
# documents and confirmed they answer the question.
]
with open("ground_truth.v1.json", "w") as f:
json.dump({"model": MODEL_NAME, "metric": METRIC,
"chunking": "fixed-512-overlap-50",
"questions": GROUND_TRUTH}, f, indent=2)
# VERSION IT, and record the model, metric and chunking it was
# built against - because Module 2 changes the chunking and the
# ids change with it.
#
# *** WITHOUT THIS FILE, EVERY DECISION IN MODULES 2 AND 4 IS A
# *** GUESS. *** It takes an afternoon. Do it now.
def recall_at_k(index, ground_truth, k=5, namespace=None):
hits = 0
for case in ground_truth:
qv = model.encode(case["q"]).tolist()
res = index.query(vector=qv, top_k=k, namespace=namespace)
got = {m["id"] for m in res["matches"]}
if got & set(case["relevant"]):
hits += 1
return hits / len(ground_truth)
# recall@k here = "did at least one genuinely relevant chunk
# appear in the top k?" Module 4 defines the fuller metrics; this
# one is enough to compare two indexes.
# THE METRIC MISMATCH DEMONSTRATION - the module's point:
# create docs-cosine and docs-euclid over THE SAME vectors
# run the ground truth against both
# cosine recall@5 = 0.87
# euclidean recall@5 = 0.71
# *** NO ERROR. NO WARNING. Just worse answers. *** That is the
# shape of every fault in this course.
# ------------------------------------------------------------------
# The other limits to record.
# ------------------------------------------------------------------
# * BATCH SIZE on upsert: there is a per-request limit in vectors
# and in bytes. Find yours empirically and batch under it.
# * METADATA SIZE per vector: a limit in bytes. Try exceeding it.
# * TOP_K has a maximum, and a large top_k with include_values
# returns a great deal of data.
# * NO JOINS, NO AGGREGATIONS, NO TRANSACTIONS, NO QUERY LANGUAGE.
# Pinecone is A COMPONENT IN AN ARCHITECTURE, not a database you
# build an application on. That is a feature, and it means
# something else owns your documents and your metadata of record.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.