Fix pgvector (#6591)

This commit is contained in:
Anthony Stirling
2026-06-15 13:09:40 +01:00
committed by GitHub
parent 085ad6c784
commit d6a5777c69
@@ -4,6 +4,7 @@ import json
from datetime import datetime from datetime import datetime
import psycopg import psycopg
from pgvector import Vector
from pgvector.psycopg import register_vector_async from pgvector.psycopg import register_vector_async
from stirling.contracts.documents import Page, PageRange from stirling.contracts.documents import Page, PageRange
@@ -45,6 +46,13 @@ class PgVectorStore(DocumentStore):
async def _ensure_schema(self) -> None: async def _ensure_schema(self) -> None:
if self._initialized: if self._initialized:
return return
# The `vector` type must exist before register_vector_async (called inside
# _connect) can resolve it. On a fresh database it doesn't yet, so create the
# extension first on a raw connection that hasn't registered the type.
async with await psycopg.AsyncConnection.connect(self._dsn) as bootstrap:
async with bootstrap.cursor() as cur:
await cur.execute("CREATE EXTENSION IF NOT EXISTS vector")
await bootstrap.commit()
async with await self._connect() as conn: async with await self._connect() as conn:
async with conn.cursor() as cur: async with conn.cursor() as cur:
await cur.execute("CREATE EXTENSION IF NOT EXISTS vector") await cur.execute("CREATE EXTENSION IF NOT EXISTS vector")
@@ -206,7 +214,7 @@ class PgVectorStore(DocumentStore):
metadata = EXCLUDED.metadata, metadata = EXCLUDED.metadata,
embedding = EXCLUDED.embedding embedding = EXCLUDED.embedding
""", """,
(doc.id, collection, owner_id, doc.text, json.dumps(doc.metadata), emb), (doc.id, collection, owner_id, doc.text, json.dumps(doc.metadata), Vector(emb)),
) )
await conn.commit() await conn.commit()
@@ -283,6 +291,7 @@ class PgVectorStore(DocumentStore):
owner_id = await self._readable_owner_for(cur, collection, principals) owner_id = await self._readable_owner_for(cur, collection, principals)
if owner_id is None: if owner_id is None:
return [] return []
query_vec = Vector(query_embedding)
await cur.execute( await cur.execute(
""" """
SELECT id, text, metadata, 1 - (embedding <=> %s) AS score SELECT id, text, metadata, 1 - (embedding <=> %s) AS score
@@ -291,7 +300,7 @@ class PgVectorStore(DocumentStore):
ORDER BY embedding <=> %s ORDER BY embedding <=> %s
LIMIT %s LIMIT %s
""", """,
(query_embedding, collection, owner_id, query_embedding, top_k), (query_vec, collection, owner_id, query_vec, top_k),
) )
rows = await cur.fetchall() rows = await cur.fetchall()