Store Chunks and Vectors in Postgres

Embeddings computed by a program live in its memory and vanish when it stops. Storing each chunk's text, source and vector together as a row in a PostgreSQL table keeps them for every later run, and with the pgvector extension the database understands the vectors themselves. This page explains the small amount of SQL that takes, how Python talks to the database safely, and how to load the chunks so that loading them a second time changes nothing.

What a database adds to vectors in memory

A semantic search can run entirely inside one Python program: embed every chunk, keep the vectors in a list, and compare a question against them. That works until the program ends. The list is gone, and the next run has to embed every chunk again, which takes the same time and work as the first.

A database is a program whose job is to keep data on disk and hand it back when asked. Putting the chunks in one changes three things:

  • The vectors persist. They are computed once and read back by every later run, or by any other program that connects.
  • Each vector stays beside its text and source. One row holds the chunk's words, the document and heading it came from, and its embedding, so a match can never lose track of what it matched.
  • The search runs where the other data already is. An application usually keeps its users, orders or documents in a database. When the vectors sit in the same database, a search can be combined with ordinary conditions (only this team's documents, only last year's) without copying anything out first.
QuestionA list in Python memoryA table in PostgreSQL
After the program endsGone, embed everything againStill there, read it back
Text and source with each vectorOnly if you keep several lists in stepAlways, they are one row
Used by other programsNoYes, any program that connects
Combined with application dataOnly after copying it inIn the same database

True or false?

Once the embeddings are stored in a database, a new run of the program does not need to embed the stored chunks again.

True. The vectors are saved on disk with their text, so later runs read them back. Only a new question still has to be embedded.

Tables, rows and a primary key

A PostgreSQL database holds tables. A table is a grid: its columns are fixed when it is created, each with a name and a type that every value in it must have, and each row is one record, here one chunk. You talk to the database in SQL, a language of statements such as CREATE TABLE, INSERT and SELECT.

A table of chunks needs only a few columns. Words are stored in columns of type text, PostgreSQL's native string type with no length limit; the documentation advises it over inventing an arbitrary maximum length.

One column is the primary key: the value that names a row, the way a chunk's id names that chunk. PostgreSQL holds it to two rules: every value is unique, and none is empty. An insert that breaks either rule is rejected. PostgreSQL also builds an index on the column, so finding a row by its key is quick.

chunks
id (primary key)sourcecontentembedding
leave.md#1leave.mdStaff get 25 days of paid leave.[0.12, -0.40, 0.91]
leave.md#2leave.mdUnused days carry over to March.[0.08, -0.35, 0.77]
remote.md#1remote.mdYou may work from home on Fridays.[-0.21, 0.66, 0.05]

The statement below creates that table. The last column uses the vector type, which the next section explains; a real embedding has hundreds of numbers, but three keep the example readable. Then one row goes in and is read back. In SQL, text values are written in single quotes, and a vector is written as a bracketed list inside a string.

CREATE TABLE chunks (
    id        text PRIMARY KEY,
    source    text NOT NULL,
    content   text NOT NULL,
    embedding vector(3) NOT NULL
);

INSERT INTO chunks (id, source, content, embedding)
VALUES ('leave.md#1', 'leave.md', 'Staff get 25 days of paid leave.', '[0.12, -0.40, 0.91]');

SELECT id, source, content FROM chunks WHERE id = 'leave.md#1';

NOT NULL forbids an empty value in that column, so a chunk cannot be stored without its source or its vector. SELECT lists the columns to return and WHERE picks the rows; this one returns the single row whose key is leave.md#1.

True or false?

Inserting a second row with an id that is already in the table adds a duplicate row.

False. Primary key values must be unique, so PostgreSQL rejects the insert with an error instead of storing a second row with the same key.

The vector type from pgvector

PostgreSQL has no built-in type for embeddings. pgvector adds one. It is an extension: a package of new types, functions and operators that plugs into the database server. Using it takes two separate steps, and confusing them is a common source of errors.

  1. Install the extension's files on the server. This happens once per server, through an operating system package, or by running a ready-made image such as pgvector/pgvector, which is the official PostgreSQL image with the files already added.
  2. Enable it in each database that uses it, with one SQL statement. A server can hold many databases, and an extension installed on the server exists in none of them until it is enabled there.
  • Database server pgvector files installed
  • Database notes CREATE EXTENSION vector
  • Database billing not enabled
  • vector(n) type usable in columns
  • type "vector" does not exist
  • Database server to Database notes
  • Database server to Database billing
  • Database notes to vector(n) type: adds
  • Database billing to type "vector" does not exist

The enabling statement is CREATE EXTENSION. In SQL the extension is called vector, not pgvector; only the packages and the image carry the longer name. Adding IF NOT EXISTS makes the statement safe to run every time a program starts: when the extension is already enabled, PostgreSQL issues a notice instead of an error.

Not every user may run it. pgvector is not marked as a trusted extension, so enabling it needs the privileges to create its objects, which in most setups means a superuser.

CREATE EXTENSION IF NOT EXISTS vector;

A fixed number of dimensions

A column declared as vector(n) holds vectors of exactly n numbers. Each number is stored in single precision, like PostgreSQL's real type. The size n must equal the output dimension of the embedding model, because every chunk and every question embedded by that model has that length. pgvector checks the length on every value it receives and refuses a mismatch instead of padding or cutting it:

INSERT INTO chunks (id, source, content, embedding)
VALUES ('x', 'x.md', 'Too short', '[0.5, 0.1]');
ERROR:  expected 3 dimensions, not 2

That error is useful. Switching to an embedding model with a different output size makes every insert fail at once, instead of quietly filling the table with vectors that cannot be compared with the old ones. Changing models therefore means a new column size and embedding every chunk again.

True or false?

Running a database from an image that has pgvector installed means the vector type can be used right away in every database.

False. The image only puts the extension files on the server. Each database still needs CREATE EXTENSION vector before the type exists in it.

A vector(3) column rejects a vector with four numbers.

True. pgvector checks the length of every value and raises an error such as "expected 3 dimensions, not 4".

Talking to the database from Python

Python reaches PostgreSQL through a driver, a library that opens a network connection to the server, sends it SQL and turns the rows that come back into Python values. The current PostgreSQL driver for Python is Psycopg 3, installed with pip install "psycopg[binary]" and imported as psycopg (there is no package called psycopg3).

Values travel as parameters

A program almost always sends SQL that contains values from Python: a chunk's text, its key, its vector. The tempting way is to paste them into the statement with an f-string or +. The Psycopg documentation forbids it. A chunk whose text contains an apostrophe ends the SQL string early and breaks the statement, and text crafted on purpose can turn into extra SQL that the database runs.

Instead, the statement holds a placeholder %s for each value. The placeholder is never put in quotes, and it is the same for text, numbers and every other type. The values themselves go in a tuple, passed as the second argument. Psycopg 3 sends the statement and the values to the server separately, so a value is never read as SQL, whatever it contains. A single value is still a tuple: (key,).

  • Python program
  • PostgreSQL
  • Python program to PostgreSQL: INSERT ... VALUES (%s, %s)
  • Python program to PostgreSQL: values, sent separately
  • Python program to PostgreSQL: COMMIT
  • Python program to PostgreSQL: SELECT ... WHERE id = %s
  • PostgreSQL to Python program: rows

Changes count only once committed

By default every statement Psycopg sends runs inside a transaction: a group of changes that the database applies all together or not at all. Inserted rows are invisible to other connections until the transaction is committed with conn.commit(), and if the connection closes before that, they are thrown away. Opening the connection in a with block handles this: when the block ends normally it commits and closes the connection, and when an exception escapes it rolls back and closes it.

The adapter for vectors

The driver knows PostgreSQL's built-in types, but not vector. The pgvector Python package (pip install pgvector) is an adapter that teaches it: register_vector(conn) looks up the vector type in the connected database and tells that connection how to send and receive it. Because it looks the type up, it must run after the extension is enabled; otherwise it fails with vector type not found in the database. It also runs once for every new connection, since each connection keeps its own adapters.

import psycopg
from pgvector import Vector
from pgvector.psycopg import register_vector

with psycopg.connect("dbname=notes user=postgres") as conn:
    conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
    conn.commit()
    register_vector(conn)

    conn.execute(
        "INSERT INTO chunks (id, source, content, embedding) VALUES (%s, %s, %s, %s)",
        ("leave.md#2", "leave.md", "Leave is booked in the HR portal.", Vector([0.31, 0.05, -0.77])),
    )

    row = conn.execute(
        "SELECT content, embedding FROM chunks WHERE id = %s", ("leave.md#2",)
    ).fetchone()
    print(row[1].to_list())
# leaving the block commits the insert and closes the connection

A plain Python list is sent as a PostgreSQL array: an INSERT converts it into the vector column, but a comparison with a vector fails with "operator does not exist", so it is wrapped as Vector([...]) to be sent as a vector everywhere; a one-dimensional NumPy array, which embedding libraries often return, can be passed as it is. A vector read back arrives as a Vector object, and .to_list() or .to_numpy() turns it into a list or an array. Its numbers can differ from the originals in the last decimal places, because they were stored in single precision.

True or false?

Once conn.execute() returns for an INSERT, the new row is saved for good, even if the program then stops without committing.

False. The insert waits in an open transaction. Closing the connection without a commit discards it.

With Psycopg 3, a chunk text full of apostrophes can be stored safely when it is passed as a %s parameter.

True. The values are sent to the server apart from the statement, so their content is never read as SQL.

Loading that can run again

Loading chunks is rarely a one-time job. A document gets a new paragraph, a bug in the splitting is fixed, or the load simply crashes halfway and is started again. Each time, the same chunks are loaded once more. The load should be idempotent: running it a second time with the same documents leaves the table exactly as the first run did, and running it after an edit brings the changed rows up to date without adding any.

That depends on the key. A table whose key is a number the database generates for each insert, such as a bigserial column, gives the same chunk a new key every time, so every load adds a fresh copy of every chunk. Searches then return the same passage several times. The fix is a stable key: one computed from what the chunk is, such as its document and its position or heading in it (leave.md#2), so the same chunk gets the same key on every run.

Rows in the table after each load of the same 3 chunks
  • Load 1
  • Load 2
  • Load 3
  • Generated id
  • Stable key

A stable key alone only turns the second load into errors, because the primary key refuses a repeated value. PostgreSQL's INSERT ... ON CONFLICT says what to do instead. With DO UPDATE, a row whose key already exists is updated in place with the new values, and a row whose key is new is inserted. This is often called an upsert. In the statement below, the conflict target (id) names the key that decides whether a row already exists. Inside DO UPDATE, the special table EXCLUDED holds the incoming values, the ones the insert would have written.

UPSERT = """
    INSERT INTO chunks (id, source, content, embedding)
    VALUES (%s, %s, %s, %s)
    ON CONFLICT (id) DO UPDATE
    SET source    = EXCLUDED.source,
        content   = EXCLUDED.content,
        embedding = EXCLUDED.embedding
"""

rows = [
    ("leave.md#1", "leave.md", "Staff get 25 days of paid leave.", Vector([0.12, -0.40, 0.91])),
    ("leave.md#2", "leave.md", "Leave is booked in the HR portal.", Vector([0.31, 0.05, -0.77])),
]

with psycopg.connect("dbname=notes user=postgres") as conn:
    register_vector(conn)
    with conn.cursor() as cur:
        cur.executemany(UPSERT, rows)

executemany runs the statement once for each tuple in the list. Run this twice and the table still holds two rows; edit the first chunk's text and run it again, and that row now holds the new text and vector.

Three details decide whether the load really stays repeatable:

  • ON CONFLICT DO NOTHING also avoids duplicates, but it skips existing keys entirely, so an edited chunk keeps its old text and vector. For a reload, DO UPDATE is the one that keeps the table current.
  • Keys must be unique across the chunks of one load. Two chunks that share a key overwrite each other, and inside a single multi-row INSERT the statement fails with a cardinality violation error.
  • An upsert only adds and updates. A chunk that disappears from the documents keeps its row until it is deleted.

True or false?

Reloading the same chunks with INSERT ... ON CONFLICT (id) DO NOTHING keeps the row count steady and also picks up edited chunk text.

False. DO NOTHING keeps the row count steady but skips every existing key, so edited text and new vectors are ignored. DO UPDATE writes them.

An upsert into a table keyed by a generated bigserial id still adds a new row for every chunk on each load.

True. A freshly generated id never matches an existing one, so there is never a conflict and every row is inserted again.