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}, )
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...
