Semantic search compares the meaning of a question with stored documents rather than requiring the same words. On Ubuntu 26.04, Sentence Transformers produces the embeddings, while a pgvector HNSW index in PostgreSQL makes those embeddings searchable alongside their document text.

The embedding model determines the vector size and the space in which distances have meaning. The document and query embeddings here come from the same all-MiniLM-L6-v2 model, with 384 dimensions and cosine distance; the HNSW index uses the matching cosine operator class. HNSW provides approximate nearest-neighbor search, so a larger corpus can trade recall for query speed.

A PostgreSQL server with the pgvector server extension installed and a password-authenticated, non-superuser appuser role is required. The postgres administrator also needs password access from this client to create the database and enable its extension. The client uses Ubuntu 26.04, Python 3.14, and CPU inference, with a separate demonstration database to keep existing application tables untouched. The model downloads from Hugging Face on first use without an account.

Steps to build a pgvector index with Sentence Transformers:

  1. Activate a Python 3.14 project virtual environment containing Sentence Transformers.
    $ source .venv/bin/activate

    Tested with Python 3.14, Sentence Transformers 6.3.0, and CPU PyTorch on Ubuntu 26.04 ARM64.

  2. Refresh the Ubuntu package index for the PostgreSQL client.
    $ sudo apt-get update
  3. Install the PostgreSQL command-line client.
    $ sudo apt-get install --yes postgresql-client
  4. Install the Python vector adapter and binary PostgreSQL driver in the active environment.
    $ python -m pip install pgvector "psycopg[binary]"

    The binary Psycopg package includes its client libraries, so this installation needs neither a compiler nor PostgreSQL development headers.

  5. Set the connection defaults with your database server's hostname.
    $ export PGHOST=db.example.net PGPORT=5432 \
        PGUSER=appuser PGDATABASE=vector_demo

    appuser is the login created with the linked role guide; vector_demo is a new database created next. Both psql and psycopg.connect() read these settings. Passwords are entered at prompts rather than stored in source or environment variables.

    The demonstration assumes a local or trusted private connection. A remote production connection needs a certificate-verified TLS configuration before sending a password or document text.

  6. Create the demonstration database as a PostgreSQL administrator.
    $ psql --username=postgres --dbname=postgres --password \
        --command='CREATE DATABASE vector_demo OWNER appuser;'
    CREATE DATABASE

    This creates a new database owned by appuser and fails if that database name already exists. No existing database or table is dropped.

  7. Enable the vector extension in the demonstration database as the administrator.
    $ psql --username=postgres --password \
        --command='CREATE EXTENSION vector;'
    CREATE EXTENSION

    The administrator installs the extension once in this database; the Python application uses appuser. The Python pgvector package alone does not install the server extension.

  8. Create pgvector_search.py in your text editor with the initial embedding setup.
    from getpass import getpass
     
    import psycopg
    from pgvector.psycopg import register_vector
    from sentence_transformers import SentenceTransformer
     
    model = SentenceTransformer(
        "sentence-transformers/all-MiniLM-L6-v2"
    )
    documents = [
        "Reset your password.",
        "Track a parcel.",
        "Bake bread.",
    ]

    The three documents give the password question a distinct expected match. Both document and query text must use this same embedding model.

  9. Append the password-prompted connection and table definition below the corpus.
    with psycopg.connect(
        password=getpass("Database password: ")
    ) as conn:
        register_vector(conn)
        conn.execute("""
            CREATE TABLE documents (
                id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
                content text NOT NULL,
                embedding vector(384) NOT NULL
            )
        """)

    Registration lets Psycopg adapt NumPy embeddings to PostgreSQL vectors. The connection uses the exported settings and the appuser password. The connection context commits on normal exit and rolls back on an exception; an existing documents table causes an error instead of being overwritten.

  10. Append the embedding generation and inserts inside the connection block.
        embeddings = model.encode(documents)
        for content, embedding in zip(documents, embeddings):
            conn.execute(
                "INSERT INTO documents (content, embedding) "
                "VALUES (%s, %s)",
                (content, embedding),
            )

    Each 384-element embedding is stored beside its source text. The parameter placeholders pass the text and vector as values rather than interpolating them into SQL.

  11. Append the cosine HNSW index creation after the insert loop.
        conn.execute("""
            CREATE INDEX documents_embedding_hnsw
            ON documents USING hnsw (embedding vector_cosine_ops)
        """)
        conn.execute("ANALYZE documents")

    The four-space indentation keeps this inside the connection block, outside the loop. The cosine operator class matches the query's cosine distance operator. A three-row table may use a sequential scan because it is cheaper; creating the index does not force PostgreSQL to select it.

  12. Append the query embedding and nearest-neighbor search below the index creation.
        query = "forgot password"
        query_embedding = model.encode(query)
        rows = conn.execute("""
            SELECT content, embedding <=> %s AS distance
            FROM documents
            ORDER BY embedding <=> %s
            LIMIT 3
        """, (query_embedding, query_embedding)).fetchall()
        print(f"Query: {query}")
        for content, distance in rows:
            print(f"{distance:.4f}\n{content}")

    Cosine distance increases as similarity decreases, so the query orders the distance operator directly in ascending order. That ordering and LIMIT allow use of the HNSW index.

  13. Save pgvector_search.py in the active project's directory.
  14. Run the script with the appuser database password at the prompt.
    $ python pgvector_search.py

    Example output:

    Database password: 
    Query: forgot password
    0.3434
    Reset your password.
    0.8994
    Bake bread.
    0.9822
    Track a parcel.

    The first execution also downloads and loads the model; an unauthenticated Hugging Face warning concerns download rate limits. The password-reset document should be the first result, with the smallest cosine distance.

  15. Confirm the committed embeddings and HNSW index from a new database connection.
    $ psql --expanded --password --command="
    SELECT (SELECT count(*) FROM documents) AS n,
           (SELECT min(vector_dims(embedding))
            FROM documents) AS d,
           am.amname AS am, opc.opcname AS op,
           i.indisvalid AS ok
    FROM pg_index i
    JOIN pg_class c ON c.oid = i.indexrelid
    JOIN pg_am am ON am.oid = c.relam
    JOIN pg_opclass opc ON opc.oid = i.indclass[0]
    WHERE c.oid = 'documents_embedding_hnsw'::regclass;"

    Example output:

    -[ RECORD 1 ]---------
    n  | 3
    d  | 384
    am | hnsw
    op | vector_cosine_ops
    ok | t

    The result should show three stored rows, 384 dimensions, hnsw, vector_cosine_ops, and a valid index. A missing table or index raises an error; an empty table returns zero rows in the n field.

Share this guide