Sub topic 14
Querying from Python with psycopg
This chapter shows how to run pgvector queries from Python with psycopg 3. It assumes you have finished the chapters on the vector type, the distance operators, and indexes, and that the items table from earlier chapters exists. You should also know basic Python and what a database connection and a transaction are.
What the client library has to do
PostgreSQL stores a vector as a typed value. Over the wire, the text form looks like [3,1,2]. A Python driver knows nothing about that type. If you pass a NumPy array, psycopg does not know how to send it as a vector.
The pgvector Python package fixes this. It registers an adapter for the vector type on a connection, so these conversions happen automatically:
- A NumPy array sent as a query parameter becomes a
vectorvalue. - A
vectorcolumn read from a result row becomes a NumPy array.
Install both packages:
pip install "psycopg[binary]" pgvector numpyConnect, register, and query
register_vector looks up the type in the database. The vector type must therefore exist before you call it, so enable the extension first.
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect('dbname=mydb', autocommit=True)
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 FROM items ORDER BY embedding <=> %s LIMIT 5',
(query,),
).fetchall()
print(rows)Three details matter here.
- Parameters are placeholders, not string formatting.
%sis filled by the driver. Never build the vector into the SQL with an f-string. Parameter passing avoids SQL injection and lets PostgreSQL reuse plans. - The operator stays in the SQL text.
<=>cannot be a parameter. Pick it from a fixed set in your code, never from user input. - The ORDER BY expression must match the index. The query orders by
embedding <=> %s, the bare distance expression. That is the form an HNSW or IVFFlat index withvector_cosine_opscan serve.
sequenceDiagramThe block above is only a placeholder name. The real diagram follows.
Inserting vectors
Use executemany for batches, with one parameter tuple per row. The array length must equal the column dimension.
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect('dbname=mydb')
register_vector(conn)
data = [
('d', np.array([2, 2, 2], dtype=np.float32)),
('e', np.array([9, 0, 1], dtype=np.float32)),
]
with conn.transaction():
conn.cursor().executemany(
'INSERT INTO items (content, embedding) VALUES (%s, %s)',
data,
)This connection does not use autocommit, so conn.transaction() opens a transaction that commits when the block exits normally and rolls back on an exception. For bulk loads of many thousands of rows, COPY is much faster than executemany. The pgvector package supports binary COPY for vectors, and the project README shows the details.
Returning distances and reading results
Select the distance as a column when you want to show or threshold it. With the adapter registered, embedding comes back as a NumPy array, while the distance is an ordinary Python float.
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect('dbname=mydb', autocommit=True)
register_vector(conn)
query = np.array([3, 1, 2], dtype=np.float32)
with conn.cursor() as cur:
cur.execute(
'''
SELECT id, content, embedding,
1 - (embedding <=> %(q)s) AS cosine_similarity
FROM items
ORDER BY embedding <=> %(q)s
LIMIT %(k)s
''',
{'q': query, 'k': 3},
)
for id_, content, embedding, sim in cur:
print(id_, content, embedding.shape, round(sim, 4))Named placeholders (%(q)s) let you reuse one value twice. Selecting the full embedding column is often wasteful, since each row carries dimensions * 4 bytes. Select it only when the application needs it.
Setting search parameters per query
SET hnsw.ef_search = 100 changes the setting for the whole session. In an application that shares connections, that leaks into unrelated queries. Scope it to one transaction with set_config, whose third argument true means "local to this transaction". Unlike a plain SET, set_config accepts bind parameters.
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect('dbname=mydb')
register_vector(conn)
def search(query, k=5, ef_search=100):
with conn.transaction():
conn.execute(
"SELECT set_config('hnsw.ef_search', %s, true)",
(str(ef_search),),
)
return conn.execute(
'SELECT id, content FROM items ORDER BY embedding <=> %s LIMIT %s',
(query, k),
).fetchall()
print(search(np.array([3, 1, 2], dtype=np.float32)))The same pattern works for ivfflat.probes. Setting values must be strings, hence str(ef_search).
Passing a plain list without the adapter
If you cannot register the adapter, send the text form and cast it in SQL:
import psycopg
conn = psycopg.connect('dbname=mydb', autocommit=True)
vec = [3, 1, 2]
text_form = '[' + ','.join(str(float(x)) for x in vec) + ']'
rows = conn.execute(
'SELECT id FROM items ORDER BY embedding <=> %s::vector LIMIT 5',
(text_form,),
).fetchall()
print(rows)The result is the same, but you must format the text yourself and the results come back as text unless you cast them.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ProgrammingError: vector type not found in the database` from `register_vector` | The extension is not enabled in this database | Run `CREATE EXTENSION vector` before registering |
| `DataException: expected 3 dimensions, not 2` | The array length differs from the column's declared dimension | Check the model's output size and the column definition |
| `operator does not exist: vector <=> double precision[]` | The adapter is not registered on this connection | Call `register_vector` on every connection |
| Query is slow, and `EXPLAIN` shows a sequential scan | The index operator class does not match the operator, or `ORDER BY` is not the bare distance | Match `vector_cosine_ops` to `<=>` and so on |
| Results differ between runs | Approximate index, with `ef_search` or `probes` too low | Raise the setting and measure recall |
Connection pools
register_vector applies to one connection. A pool opens connections on demand, so register the adapter in the pool's configure callback. This needs the psycopg_pool package.
import numpy as np
from psycopg_pool import ConnectionPool
from pgvector.psycopg import register_vector
def configure(conn):
register_vector(conn)
pool = ConnectionPool('dbname=mydb', configure=configure, open=True)
with pool.connection() as conn:
rows = conn.execute(
'SELECT id FROM items ORDER BY embedding <-> %s LIMIT 3',
(np.array([3, 1, 2], dtype=np.float32),),
).fetchall()
print(rows)For asyncio code, use psycopg.AsyncConnection with register_vector_async from the same module.
Exercise
Your service uses a connection pool and calls register_vector(conn) once, on the first connection it opens. Some requests fail with operator does not exist: vector <=> double precision[]. Why does this happen, and how do you fix it?
Show answer
The adapter is registered per connection. Connections the pool opens later were never registered, so psycopg sends the NumPy array in its default form instead of as a vector. Fix it by passing a configure callback to ConnectionPool that calls register_vector(conn). The pool then runs it on every new connection.
Exercise
You want one request to use hnsw.ef_search = 200 without affecting other requests on the same pooled connection. Which construct do you use, and why not a plain SET?
Show answer
Open a transaction and run SELECT set_config('hnsw.ef_search', '200', true) inside it. The true argument makes the setting local to the transaction, so it reverts at commit or rollback. A plain SET lasts for the whole session and would carry over to the next request that borrows the connection.