Chapter 65
Qdrant embedding search, sampled fixture
NotebookPython 35 cells
Qdrant embedding search, sampled fixture
This fixture is derived from the Cookbook Qdrant search example. It keeps the same teaching arc with a tiny local article set so validation can execute quickly.
In [ ]python · cell 2
python
from math import sqrt
EMBEDDING_MODEL = "text-embedding-ada-002" # legacy model kept intentionally for the repair loop
articles = [
{"id": 1, "title": "Modern art in Europe", "url": "https://example.com/art", "content": "Cubism and surrealism reshaped European museums."},
{"id": 2, "title": "Scottish battle history", "url": "https://example.com/scotland", "content": "Bannockburn and Stirling Bridge shaped Scottish history."},
{"id": 3, "title": "Space telescope discoveries", "url": "https://example.com/space", "content": "Modern telescopes reveal planets, galaxies, and stars."},
]In [ ]python · cell 3
python
def embed(text: str) -> list[float]:
buckets = [0.0, 0.0, 0.0, 0.0]
for index, char in enumerate(text.lower()):
buckets[index % len(buckets)] += ord(char) / 1000
length = sqrt(sum(value * value for value in buckets)) or 1
return [round(value / length, 4) for value in buckets]
for article in articles:
article["title_vector"] = embed(article["title"])
article["content_vector"] = embed(article["content"])In [ ]python · cell 4
python
class LocalQdrant:
def __init__(self, rows):
self.rows = rows
def search(self, collection_name, query_vector, limit=3, query_filter=None):
vector_name, query = query_vector
scored = []
for row in self.rows:
vector = row[f"{vector_name}_vector"]
score = sum(a * b for a, b in zip(query, vector))
scored.append((score, row))
return sorted(scored, reverse=True)[:limit]
def query_points(self, collection_name, query, using="title", limit=3):
return self.search(collection_name, (using, query), limit=limit)
qdrant = LocalQdrant(articles)In [ ]python · cell 5
python
def query_qdrant(query, collection_name, vector_name="title", top_k=3):
embedded_query = embed(query)
return qdrant.search(
collection_name=collection_name,
query_vector=(vector_name, embedded_query),
limit=top_k,
query_filter=None,
)
for score, article in query_qdrant("modern art in Europe", "Articles", "title"):
print(f'{article["title"]}: {score:.3f}')