A Tiny Vector Store

File: VectorStore.lean

A vector store holds texts with their embeddings and finds the entries closest to a query vector. Retrieval for LLM applications uses this operation. The measure here is cosine similarity:

math

This program uses four-dimensional vectors that I wrote by hand, so the results are easy to check. Real embeddings come from a model and have hundreds or thousands of dimensions.

Cosine divides by both norms, so only direction matters. Two vectors (1, 0) and (100, 0) have cosine 1; their dot product is 100. Without the norms, a long vector would top the ranking even when it points elsewhere.

The Code

 1 -- lean --run VectorStore.lean   (in-memory dense vector store)
 2 import Std.Data.HashMap
 3 
 4 abbrev Vec := Array Float
 5 
 6 def dot (a b : Vec) : Float :=
 7   (a.zip b).foldl (fun acc (x, y) => acc + x * y) 0.0
 8 
 9 def norm (a : Vec) : Float := (dot a a).sqrt
10 
11 def cosine (a b : Vec) : Float :=
12   let na := norm a
13   let nb := norm b
14   if na == 0.0 || nb == 0.0 then 0.0 else dot a b / (na * nb)
15 
16 -- id -> (text, embedding)
17 abbrev VectorStore := Std.HashMap String (String × Vec)
18 
19 -- The k most similar entries as (score, id, text)
20 def VectorStore.search (store : VectorStore) (queryVec : Vec)
21     (k : Nat := 3) : List (Float × String × String) :=
22   let scored := store.toList.map fun (id, text, vec) =>
23     (cosine queryVec vec, id, text)
24   (scored.mergeSort (fun a b => a.1 ≥ b.1)).take k
25 
26 def fixed (x : Float) (d : Nat := 3) : String :=
27   let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
28   let frac := toString (n % 10 ^ d)
29   let pad := "".pushn '0' (d - frac.length)
30   s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
31 
32 -- Demo: semantic vector search in a 4D concept space
33 def main : IO Unit := do
34   let store : VectorStore := (∅ : VectorStore)
35     |>.insert "item-1" ("queen",    #[0.90, 0.90, 0.05, 0.10])
36     |>.insert "item-2" ("king",     #[0.95, 0.10, 0.05, 0.10])
37     |>.insert "item-3" ("princess", #[0.80, 0.95, 0.05, 0.15])
38     |>.insert "item-4" ("apple",    #[0.05, 0.10, 0.95, 0.30])
39     |>.insert "item-5" ("banana",   #[0.05, 0.10, 0.90, 0.95])
40 
41   IO.println s!"Vector Store Entries: {store.size}"
42 
43   IO.println "\nQuery 1: Royal female concept #[0.85, 0.85, 0.05, 0.10]"
44   for (score, id, text) in store.search #[0.85, 0.85, 0.05, 0.10] do
45     IO.println s!"  [sim: {fixed score}] ({id}) \"{text}\""
46 
47   IO.println "\nQuery 2: Sweet fruit concept #[0.05, 0.10, 0.85, 0.90]"
48   for (score, id, text) in store.search #[0.05, 0.10, 0.85, 0.90] do
49     IO.println s!"  [sim: {fixed score}] ({id}) \"{text}\""

How It Works

  • Vec is an Array Float. a.zip b pairs the elements of two arrays, and foldl sums the products.
  • Float has == for comparison. The code uses it to avoid division by zero.
  • VectorStore is another name for a hash map from an id to a pair of text and vector. Because the function is named VectorStore.search, main can call store.search.
  • (∅ : VectorStore) is an empty store. |>.insert calls insert on the result of the line above, so five inserts read as a list.
  • store.toList returns the entries in no fixed order. The sort fixes the order by score, and take k keeps the best k.
  • for (score, id, text) in ... takes each triple apart in the loop header.

zip stops at the shorter array with no error, so a 4D query against an 8D entry compares only four products while norm still uses all eight values of the entry. The score is wrong but the program prints it. Check dimensions when you load real embeddings. Scores that compare equal keep the unspecified hash-map order after mergeSort, so a tie can print in any order; search does not break ties by id.

The Geometry

Pair Cosine
queen, king 0.779
queen, princess 0.996
queen, apple 0.166
queen, banana 0.164
king, princess 0.725
king, apple 0.140
king, banana 0.156
princess, apple 0.181
princess, banana 0.196
apple, banana 0.875

The hand-written vectors place royal words on the first two axes and fruit on the last two. Queen and princess are near copies (0.996), king shares the first axis, and apple and banana share the last two. The printed query scores follow this table.

Lean 4 Notes

List or Array. Both hold a sequence of values of one type. A List is a chain of cells and suits code that takes the first element and recurses on the rest. An Array is one block of memory and suits numeric data and access by index. Array literals start with #. Both types have map, foldl, zip, and filter, so you can change from one to the other with few edits.

abbrev for types. abbrev VectorStore := Std.HashMap String (String × Vec) gives the hash map type a second name. Lean treats the two names as the same type everywhere. In main, store.size and store.insert find the HashMap functions, and store.search finds the function I defined in the VectorStore namespace.

Pipelines. x |>.f a means x.f a. The |>. form lets you write a series of calls one per line, with no nested parentheses. main builds the store with five of them.

Functions on Float. (dot a a).sqrt calls Float.sqrt. Float also has exp, log, abs, and round. Float follows the IEEE 754 standard for 64-bit numbers.

Escapes in strings. Inside s!"...", \" is a quote character and \n is a newline. Braces insert values. Any expression can go in the braces, such as the call {fixed score}.

Loops over any collection. for ... in works on lists, arrays, ranges, and hash maps. Here it runs over the List that search returns.

Running It

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

Using It

To store real embeddings, get a vector for each text from an embedding API and insert it. The Ollama and Gemini chapters show how to call such services. The search compares the query with every entry. That is fast enough for a few thousand entries. Try this: replace the five hand-written vectors with embeddings from Ollama or Gemini, then check that queen and king still rank above apple for a royal query.