A shopper asks for something cosy to read on a rainy evening. No blurb has those words. Embed every blurb, embed the question, and find the closest books by meaning.
We embed every blurb, and store each vector in the embedding column. Then we embed the question, and order books by cosine distance to it. Run it. A love story, a calm cookbook, and an overnight train, all about cosy moods.
vector_search.pypython
import psycopgfrom sentence_transformers import SentenceTransformerURL = "postgresql://postgres:postgres@localhost:5432/riverside"model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")conn = psycopg.connect(URL)books = conn.execute("SELECT book_id, blurb FROM books").fetchall()for (book_id, blurb), vec in zip(books, model.encode([b for _, b in books])): conn.execute("UPDATE books SET embedding = %s WHERE book_id = %s", (str(vec.tolist()), book_id))q = str(model.encode("something cosy to read on a rainy evening").tolist())for (title,) in conn.execute( "SELECT title FROM books ORDER BY embedding <=> %s LIMIT 3", (q,)): print(title)
Output
Letters to Lisbon
The Quiet Kitchen
Night Train to Oslo
The embedding model runs in your app, or a service. Vectors are stored in Postgres, beside the rows. Search is just order by distance, with a limit. And you can join, filter and paginate like any query.