A tiny vector store

File: vector-store.lisp

Embedding-based semantic search in its simplest form: a hash table of labeled vectors and cosine-similarity ranking.

Cosine similarity measures the angle between two vectors, ignoring their magnitudes:

math

The code

 1 ;; sbcl --script vector-store.lisp (in-memory dense vector store)
 2 
 3 (defun v-dot (a b)
 4   (unless (= (length a) (length b))
 5     (error "Vector lengths differ: ~d vs ~d" (length a) (length b)))
 6   (loop for x across a for y across b sum (* x y)))
 7 
 8 (defun v-norm (a)
 9   (sqrt (v-dot a a)))
10 
11 (defun v-cosine (a b)
12   (let ((na (v-norm a)) (nb (v-norm b)))
13     (if (or (zerop na) (zerop nb)) 0.0 (/ (v-dot a b) (* na nb)))))
14 
15 (defun make-vector-store ()
16   (make-hash-table :test 'equal))
17 
18 (defun store-add (store id text vec)
19   (setf (gethash id store) (list text (coerce vec 'vector))))
20 
21 (defun store-search (store query-vec &optional (k 3))
22   (let ((qv (coerce query-vec 'vector)))
23     (subseq
24      (sort (loop for id being the hash-keys of store
25                    using (hash-value item)
26                  for score = (v-cosine qv (second item))
27                  collect (list score id (first item)))
28            #'> :key #'car)
29      0 (min k (hash-table-count store)))))
30 
31 ;; Demo: Semantic vector search in 4D concept space
32 (let ((store (make-vector-store)))
33   (store-add store "item-1" "queen"    #(0.90 0.90 0.05 0.10))
34   (store-add store "item-2" "king"     #(0.95 0.10 0.05 0.10))
35   (store-add store "item-3" "princess" #(0.80 0.95 0.05 0.15))
36   (store-add store "item-4" "apple"    #(0.05 0.10 0.95 0.30))
37   (store-add store "item-5" "banana"   #(0.05 0.10 0.90 0.95))
38 
39   (format t "Vector Store Entries: ~a~%" (hash-table-count store))
40 
41   (format t "~%Query 1: Royal female concept #(0.85 0.85 0.05 0.10)~%")
42   (dolist (hit (store-search store #(0.85 0.85 0.05 0.10) 3))
43     (format t "  [sim: ~5,3f] (~a) ~s~%"
44             (first hit) (second hit) (third hit)))
45 
46   (format t "~%Query 2: Sweet fruit concept #(0.05 0.10 0.85 0.90)~%")
47   (dolist (hit (store-search store #(0.05 0.10 0.85 0.90) 3))
48     (format t "  [sim: ~5,3f] (~a) ~s~%"
49             (first hit) (second hit) (third hit))))

How it works

  • v-dot steps through two vectors together with loop ... across, and v-norm reuses it for the Euclidean norm Code Test. A loop with two across clauses stops at the shorter vector without warning, so v-dot first checks that the lengths match. Mixing vectors from two embedding models is a common mistake, and an error beats a plausible but wrong score.
  • v-cosine guards against division by zero: it defines a zero vector’s similarity with anything as 0.0.
  • The store maps id to (text vector) in an equal hash table, so string IDs work. store-add coerces lists to vectors, so callers can pass either.
  • store-search scores every entry, sorts in descending order, and returns the top Code Test as (score id text) lists. min keeps subseq in bounds when the store holds fewer than Code Test items.

Running it

1 $ sbcl --script vector-store.lisp

Actual output:

 1 Vector Store Entries: 5
 2 
 3 Query 1: Royal female concept #(0.85 0.85 0.05 0.10)
 4   [sim: 1.000] (item-1) "queen"
 5   [sim: 0.996] (item-3) "princess"
 6   [sim: 0.779] (item-2) "king"
 7 
 8 Query 2: Sweet fruit concept #(0.05 0.10 0.85 0.90)
 9   [sim: 1.000] (item-5) "banana"
10   [sim: 0.875] (item-4) "apple"
11   [sim: 0.201] (item-3) "princess"

The demo uses hand-made 4D vectors whose axes roughly encode royalty, femininity, fruitiness, and sweetness. Query 1 (high royalty, female) ranks “queen” and “princess” above “king”. Query 2 (a sweet fruit) ranks both fruits above the rest, and the sweetness axis puts the banana (0.95) well ahead of the apple (0.30).

Using it

Replace the toy vectors with real embeddings from an API (Gemini and Ollama both offer embedding endpoints) and this code becomes a semantic search engine over your documents: split text into chunks, embed each chunk, store-add it, then store-search with the embedded question. Brute-force scoring handles thousands of vectors; beyond that, use an approximate-nearest-neighbor index. The interface here (add, search top-Code Test) matches what those indexes offer.