Database / pgvector basics Interview Questions
How do you use pgvector with asyncpg or asyncio in Python?
Modern Python web frameworks (FastAPI, Starlette, aiohttp) use async I/O. pgvector works with asyncpg (the high-performance async PostgreSQL driver) using the pgvector codec registration.
# pip install asyncpg pgvector import asyncio import asyncpg from pgvector.asyncpg import register_vector from openai import AsyncOpenAI async def main(): # Connect with asyncpg conn = await asyncpg.connect( "postgresql://user:pass@localhost/mydb" ) # Register the vector codec (required for asyncpg) await register_vector(conn) # Create schema await conn.execute(""" CREATE TABLE IF NOT EXISTS documents ( id BIGSERIAL PRIMARY KEY, content TEXT, embedding VECTOR(1536) ) """) # Generate and insert embedding client = AsyncOpenAI() text = "pgvector is a PostgreSQL extension" response = await client.embeddings.create( model="text-embedding-3-small", input=text ) embedding = response.data[0].embedding await conn.execute( "INSERT INTO documents (content, embedding) VALUES ($1, $2)", text, embedding ) # Query: async KNN search query_text = "vector search in PostgreSQL" q_emb = (await client.embeddings.create( model="text-embedding-3-small", input=query_text )).data[0].embedding rows = await conn.fetch( "SELECT id, content, embedding <=> $1 AS dist" " FROM documents ORDER BY dist LIMIT 5", q_emb ) for row in rows: print(f"dist={row['dist']:.4f}: {row['content']}") await conn.close() asyncio.run(main()) # For connection pooling with FastAPI: # async with asyncpg.create_pool(dsn) as pool: # async with pool.acquire() as conn: # await register_vector(conn) # rows = await conn.fetch(...)
More Related questions...