Lesson 4.8 · 8 of 10 · 6 min read · Reviewed 24 Nov 2026
Lab: watch nearest neighbours change
By the end, you can
- See how the query, the data and filters change the nearest neighbours.
- Fix a broken similarity function and a tenant leak.
This is a hands-on lesson. Open the Playground project A tiny vector storeVector database: A database built to store embeddings and find the nearest ones to a query quickly. (link below). It runs entirely in your browser with toy 6-number embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together., so you can see every number. No API key, no cost.
The toy space
Each of the 6 dimensions stands for one topic:
[ billing, login, shipping, device, returns, time ]
A word list turns text into a vector: “charged” adds to billing, “password” to login, “laptop” to device, and so on. Real models learn hundreds of dimensions you can’t name, but the geometry works the same way.
Step 1. Run the starter and read the output
You’ll see three queries and their top 3 results. Notice two problems:
kb-9, a long FAQ that mentions everything, ranks first for almost every query.- The globex query returns
kb-documents that belong to a different customer.
Step 2. Fix cosine()
The starter returns the raw dot product. Divide by the two lengths so only direction counts:
cosine(a, b) = dot(a, b) / (|a| x |b|)
Run again. kb-5 should now top “laptop will not power on”, and kb-2 should top “I was charged twice”. The FAQ drops because pointing a little in every direction is not the same as pointing your way.
Step 3. Fix the tenant leak
Add the tenant filter back so each query only sees its own tenant’s documents, before scoring. Run again: the globex query should return g-1 and nothing from acme.
Step 4. Experiment
Change things and watch the neighbours move:
| Try | What to look for |
|---|---|
| Change a query to “refund for the late parcel” | Results shift towards returns and shipping |
| Add a word like “invoice” to a document | That document climbs for billing queries |
| Add a new doc that is a near copy of kb-2 | Two near-equal scores; the id tie-break keeps order stable |
| Set k = 1, then k = 5 | More results bring in weaker, less relevant matches |
| Remove the tenant filter again | The leak returns; this is why filters are a security control |
What carries over to real systems
- Normalise vectors (or use cosine) unless your model’s docs say dot product is intended.
- Apply access filters inside the search, never after the model has seen the results.
- Inspect real nearest neighbours for real queries. It’s the fastest way to spot chunkingChunking: Splitting documents into smaller passages before embedding and indexing them. or model problems.
Key points
- Nearest neighbours depend on three things: the query vector, what's in the store, and which filters run first.
- Using a raw dot product instead of cosine lets long documents win just for being long.
- Filtering by tenant before ranking is a security control, not a tuning choice.
- Ties need a stable tie-break (such as id) so results don't flicker between runs.
Fix cosine and the tenant leak
Repair a tiny vector store so long documents stop winning and one customer never sees another's data.
You will have: A working search() that uses cosine similarity, filters by tenant before ranking and breaks ties by id.
Steps
- Run the starter: the long FAQ 'kb-9' tops every query and the globex query returns acme documents.
- Fix cosine() so it divides the dot product by both lengths.
- Filter documents to the query's tenant before scoring.
- Sort by score, then id, so ties are stable.
- Rerun and check each query's top hit.
Done when
- 'laptop will not power on' returns kb-5 first.
- The globex query returns only g- documents.
- kb-9 no longer tops every query.
Open in the Playground No API key needed.
Starter code (Python)
import math
DOCS = [
{"id": "kb-2", "tenant": "acme", "v": [1, 0, 0, 0]},
{"id": "kb-5", "tenant": "acme", "v": [0, 0, 0, 1]},
{"id": "kb-7", "tenant": "acme", "v": [0, 1, 0, 0]},
{"id": "kb-9", "tenant": "acme", "v": [3, 3, 3, 3]},
{"id": "g-1", "tenant": "globex", "v": [0, 0.9, 0, 0.1]},
]
QUERIES = [("I was charged twice", "acme", [1, 0, 0, 0.1]), ("laptop will not power on", "acme", [0, 0, 0.1, 1]),
("cannot log in", "globex", [0, 1, 0, 0])]
def cosine(a, b):
return sum(x * y for x, y in zip(a, b)) # TODO: divide by the two lengths
def search(qv, tenant, k=2):
pool = DOCS # TODO: keep only documents of this tenant
return [d["id"] for d in sorted(pool, key=lambda d: -cosine(qv, d["v"]))][:k] # TODO: tie-break by id
for text, tenant, qv in QUERIES:
print(f"{text} ({tenant}):", search(qv, tenant))
Show a solution
import math
DOCS = [
{"id": "kb-2", "tenant": "acme", "v": [1, 0, 0, 0]},
{"id": "kb-5", "tenant": "acme", "v": [0, 0, 0, 1]},
{"id": "kb-7", "tenant": "acme", "v": [0, 1, 0, 0]},
{"id": "kb-9", "tenant": "acme", "v": [3, 3, 3, 3]},
{"id": "g-1", "tenant": "globex", "v": [0, 0.9, 0, 0.1]},
]
QUERIES = [("I was charged twice", "acme", [1, 0, 0, 0.1]), ("laptop will not power on", "acme", [0, 0, 0.1, 1]),
("cannot log in", "globex", [0, 1, 0, 0])]
def cosine(a, b):
la, lb = math.sqrt(sum(x * x for x in a)), math.sqrt(sum(x * x for x in b))
return sum(x * y for x, y in zip(a, b)) / (la * lb) if la and lb else 0.0
def search(qv, tenant, k=2):
pool = [d for d in DOCS if d["tenant"] == tenant]
return [d["id"] for d in sorted(pool, key=lambda d: (-cosine(qv, d["v"]), d["id"]))][:k]
for text, tenant, qv in QUERIES:
print(f"{text} ({tenant}):", search(qv, tenant))
Do it Build a tiny vector store and watch neighbours change in the Playground. No API key needed.