Database / pgvector basics Interview Questions
How do you use pgvector with SQLAlchemy and Python ORMs?
SQLAlchemy is the most popular Python ORM and supports pgvector through the pgvector package, which provides a SQLAlchemy column type and custom operators. This allows defining vector columns declaratively and using Pythonic query expressions.
# pip install pgvector sqlalchemy psycopg2-binary from sqlalchemy import create_engine, Column, Integer, Text, select from sqlalchemy.orm import declarative_base, Session from pgvector.sqlalchemy import Vector engine = create_engine("postgresql+psycopg2://user:pass@localhost/mydb") Base = declarative_base() # Define the model with a vector column class Document(Base): __tablename__ = "documents" id = Column(Integer, primary_key=True) content = Column(Text) embedding = Column(Vector(1536)) # pgvector Vector type Base.metadata.create_all(engine) # Insert a document with Session(engine) as session: doc = Document(content="Python tutorial", embedding=[0.1, 0.2, ...]) session.add(doc) session.commit() # Query: find 5 nearest neighbours using cosine distance from pgvector.sqlalchemy import cosine_distance query_vector = [0.1, 0.2, ...] with Session(engine) as session: results = session.scalars( select(Document) .order_by(cosine_distance(Document.embedding, query_vector)) .limit(5) ).all() for doc in results: print(doc.content) # Create HNSW index via SQLAlchemy: from sqlalchemy import Index, text Index( "ix_documents_embedding_hnsw", Document.embedding, postgresql_using="hnsw", postgresql_ops={"embedding": "vector_cosine_ops"}, postgresql_with={"m": 16, "ef_construction": 64}, )
More Related questions...