Sub topic 14
Querying from Python with psycopg
This chapter assumes that you know basic SQL, PostgreSQL connections, and Python functions. It also assumes that PostgreSQL has the pgvector extension enabled and that the items table from the earlier chapters already contains an embedding vector(3) column.
The psycopg package is a Python database driver. It sends SQL to PostgreSQL and returns query results. The pgvector Python package teaches psycopg how to convert between PostgreSQL vector values and Python or NumPy values.
Install the client packages in your Python environment:
pip install "psycopg[binary]" pgvector numpyRegistering the vector type
A connection must register the vector type before it sends NumPy arrays as query parameters. The following example uses a database URL stored in the DATABASE_URL environment variable.
import os
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
dsn = os.environ["DATABASE_URL"]
with psycopg.connect(dsn, autocommit=True) as conn:
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)
query = np.array([3, 1, 2], dtype=np.float32)
rows = conn.execute(
"""
SELECT id,
content,
1 - (embedding <=> %s) AS cosine_similarity
FROM items
ORDER BY embedding <=> %s
LIMIT 5
""",
(query, query),
).fetchall()
for row in rows:
print(row)The %s markers are parameter placeholders. The values in the tuple are sent separately from the SQL text. This prevents malformed SQL and SQL injection. Do not build the query by joining a vector into a string.
The <=> operator returns cosine distance. Ordering by that distance puts the nearest rows first. Subtracting the distance from 1 produces cosine similarity for display.
The query uses the same vector twice. PostgreSQL needs one parameter for the SELECT expression and another for the ORDER BY expression. Some drivers support numbered or named parameters, but psycopg uses %s for positional parameters.
Transactions and connections
The with statement closes the connection when the block ends. With the default transaction behavior, leaving the block commits successful work or rolls back an error. The example uses autocommit=True because enabling an extension is setup work, not application data. In a web service, create the extension during deployment and use normal transactions for application queries.
Request flow
Exercise
Why should the query vector be passed as a parameter instead of concatenated into the SQL string?
Show answer
Parameter binding keeps data separate from SQL syntax, avoids injection risks, and lets pgvector convert the vector value correctly.