Database / pgvector basics Interview Questions
How do you use pgvector with Python and psycopg2?
The standard Python path for pgvector uses psycopg2 (or psycopg3) as the PostgreSQL driver, with the pgvector Python package providing type adapters that automatically convert Python lists to vector literals and back.
# Install dependencies # pip install pgvector psycopg2-binary openai import psycopg2 from pgvector.psycopg2 import register_vector from openai import OpenAI # Connect and register the vector type adapter conn = psycopg2.connect("postgresql://user:pass@localhost/mydb") register_vector(conn) # allows Python lists <-> vector column cur = conn.cursor() # Create the schema cur.execute(""" CREATE TABLE IF NOT EXISTS documents ( id BIGSERIAL PRIMARY KEY, content TEXT NOT NULL, embedding VECTOR(1536) ) """) conn.commit() # Generate embedding and insert oai = OpenAI() text = "How does pgvector work?" response = oai.embeddings.create(model="text-embedding-3-small", input=text) embedding = response.data[0].embedding # list of 1536 floats cur.execute( "INSERT INTO documents (content, embedding) VALUES (%s, %s)", (text, embedding) # psycopg2 + register_vector handles the conversion ) conn.commit() # Query: find 5 most similar documents query_text = "What is the pgvector extension?" query_embedding = oai.embeddings.create( model="text-embedding-3-small", input=query_text ).data[0].embedding cur.execute( "SELECT id, content, embedding <=> %s AS distance" " FROM documents ORDER BY distance LIMIT 5", (query_embedding,) ) results = cur.fetchall() for row in results: print(f"id={row[0]}, dist={row[2]:.4f}: {row[1]}") cur.close() conn.close()
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...
