> ## Documentation Index
> Fetch the complete documentation index at: https://cache-pot.thatdevguy.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Vector store: cosine similarity search in Cache-Pot

> Cache-Pot provides a built-in vector store with cosine similarity search. Store float32 embeddings and query by nearest neighbours in the same keyspace.

Cache-Pot includes a native vector store — you can persist float32 embeddings and search by cosine similarity without standing up a separate database. Vector collections live in the same keyspace as all other data types, so they benefit from the same TTL, snapshot, and AOF support you already know. This makes Cache-Pot a single binary that covers both the caching layer and the semantic search layer of an AI application.

***

## Collections

Vectors are grouped into **named collections**. A collection is a regular Cache-Pot key whose type is `vector`. Within a collection, every vector must share the same dimension — the dimension is fixed the moment you insert the first vector with `VSET`, and any subsequent insert with a different number of floats returns an error.

Each vector entry has three components:

<CardGroup cols={3}>
  <Card title="ID" icon="fingerprint">
    A unique string identifier within the collection. Re-using an ID overwrites the existing vector.
  </Card>

  <Card title="Float32 array" icon="chart-line">
    The vector itself — a space-separated sequence of floating-point values passed directly in the command.
  </Card>

  <Card title="META (optional)" icon="tag">
    An arbitrary string attached to the vector, such as a document title, URL, or serialised JSON payload.
  </Card>
</CardGroup>

***

## Commands

| Command                                       | Description                                                                                                                                                               |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VSET key id f1 f2 ... fn [META text]`        | Insert or overwrite the vector `id` in collection `key`. The dimension is fixed by the first insert.                                                                      |
| `VSEARCH key f1 ... fn [TOPK k] [WITHSCORES]` | Return the top-`k` nearest neighbours by cosine similarity (default `k = 10`). Each result includes the ID and META string; add `WITHSCORES` to include the cosine score. |
| `VDEL key id`                                 | Delete the vector with the given ID from the collection.                                                                                                                  |
| `VCARD key`                                   | Return the number of vectors stored in the collection.                                                                                                                    |
| `VDIM key`                                    | Return the vector dimension of the collection.                                                                                                                            |

***

## Example workflow — document similarity search

<Steps>
  <Step title="Store document embeddings">
    Insert vectors with descriptive metadata. This example uses 4-dimensional vectors for readability; real embeddings typically have 768–3072 dimensions.

    ```bash theme={null}
    VSET docs intro 0.1 0.9 0.2 0.5 META "Introduction to machine learning"
    VSET docs adv   0.8 0.1 0.7 0.3 META "Advanced neural networks"
    VSET docs nlp   0.2 0.7 0.1 0.8 META "Natural language processing basics"
    ```
  </Step>

  <Step title="Search for the most similar document">
    Pass a query vector and request the top-2 results with scores.

    ```bash theme={null}
    VSEARCH docs 0.15 0.85 0.18 0.55 TOPK 2 WITHSCORES
    # Returns: 1) "intro" 2) "Introduction to machine learning" 3) "0.9970"
    #          4) "nlp"   5) "Natural language processing basics" 6) "0.9430"
    ```
  </Step>

  <Step title="Inspect collection stats">
    ```bash theme={null}
    VCARD docs   # (integer) 3
    VDIM  docs   # (integer) 4
    ```
  </Step>
</Steps>

***

## Using with an embedding model

In a real application, you convert text to vectors using an embedding model before calling `VSET` or `VSEARCH`. The example below uses the `openai` Python library with Cache-Pot's standard Redis wire protocol.

<CodeGroup>
  ```python Python (openai + redis-py) theme={null}
  import redis
  import openai

  r = redis.Redis(host='localhost', port=6379)
  client = openai.OpenAI()

  def embed(text):
      resp = client.embeddings.create(input=text, model='text-embedding-3-small')
      return resp.data[0].embedding

  # Store a document embedding
  vec = embed('Introduction to machine learning')
  args = ['VSET', 'docs', 'intro'] + [str(f) for f in vec] + ['META', 'Introduction to machine learning']
  r.execute_command(*args)

  # Search for similar documents
  q = embed('machine learning basics')
  args = ['VSEARCH', 'docs'] + [str(f) for f in q] + ['TOPK', '5', 'WITHSCORES']
  results = r.execute_command(*args)
  print(results)
  ```

  ```python Python (ollama + redis-py) theme={null}
  import redis
  import requests

  r = redis.Redis(host='localhost', port=6379)

  def embed(text):
      resp = requests.post(
          'http://localhost:11434/api/embeddings',
          json={'model': 'nomic-embed-text', 'prompt': text}
      )
      return resp.json()['embedding']

  vec = embed('Introduction to machine learning')
  args = ['VSET', 'docs', 'intro'] + [str(f) for f in vec] + ['META', 'intro']
  r.execute_command(*args)
  ```
</CodeGroup>

***

## Cosine similarity scoring

The score returned by `VSEARCH` is the cosine similarity between the query vector and each stored vector, in the range `[-1, 1]`:

| Score     | Meaning                                                  |
| --------- | -------------------------------------------------------- |
| `1.0`     | Vectors point in exactly the same direction              |
| `0.9+`    | Very high similarity — nearly identical semantic content |
| `0.7–0.9` | Moderate similarity — related topic                      |
| `< 0.7`   | Low similarity — probably unrelated                      |

<Note>
  Vector search uses flat (brute-force) cosine similarity — every vector in the collection is compared against the query. This is optimal for collections up to \~100 K vectors. An HNSW approximate-nearest-neighbour index is planned for a future release.
</Note>

<Tip>
  Vector collections are regular Cache-Pot keys, so you can set a TTL on the whole collection (`EXPIRE docs 86400`), delete it with `DEL docs`, check its type with `TYPE docs`, and scan for it with `KEYS *`. All standard key operations apply.
</Tip>
