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(...)
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
