Skip to content

Commit 93ec9a9

Browse files
docs: add async SQLAlchemy + HNSW full example
Add a complete working example showing async SQLAlchemy with HNSW indexing and cosine distance queries. The README documents async driver registration and HNSW index creation separately, but lacks a combined example showing the most common production pattern (async engine + HNSW index + cosine nearest-neighbor queries).
1 parent 5b06584 commit 93ec9a9

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

README.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,62 @@ def connect(dbapi_connection, connection_record):
348348
register_vector(dbapi_connection)
349349
```
350350

351+
#### Async Full Example
352+
353+
Here's a complete example using async SQLAlchemy with an HNSW index and cosine distance queries:
354+
355+
```python
356+
import asyncio
357+
358+
from pgvector.sqlalchemy import Vector
359+
from sqlalchemy import select, text
360+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
361+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
362+
363+
engine = create_async_engine('postgresql+asyncpg://localhost/pgvector_example')
364+
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
365+
366+
class Base(DeclarativeBase):
367+
pass
368+
369+
class Item(Base):
370+
__tablename__ = 'items'
371+
id: Mapped[int] = mapped_column(primary_key=True)
372+
embedding = mapped_column(Vector(3))
373+
374+
async def main():
375+
# Create tables and HNSW index
376+
async with engine.begin() as conn:
377+
await conn.execute(text('CREATE EXTENSION IF NOT EXISTS vector'))
378+
await conn.run_sync(Base.metadata.create_all)
379+
await conn.execute(text(
380+
'CREATE INDEX IF NOT EXISTS items_embedding_idx '
381+
'ON items USING hnsw (embedding vector_cosine_ops) '
382+
'WITH (m = 16, ef_construction = 64)'
383+
))
384+
385+
# Insert
386+
async with async_session() as session:
387+
session.add_all([
388+
Item(embedding=[1, 2, 3]),
389+
Item(embedding=[4, 5, 6]),
390+
])
391+
await session.commit()
392+
393+
# Query nearest neighbors by cosine distance
394+
async with async_session() as session:
395+
result = await session.execute(
396+
select(Item)
397+
.order_by(Item.embedding.cosine_distance([1, 2, 3]))
398+
.limit(5)
399+
)
400+
items = result.scalars().all()
401+
402+
asyncio.run(main())
403+
```
404+
405+
Use `vector_l2_ops` for L2 distance and `vector_ip_ops` for inner product
406+
351407
## SQLModel
352408

353409
Enable the extension

0 commit comments

Comments
 (0)