Package: pgvector
pgvector-pythonpgvectorsupport for PythonSupportsDjango,SQLAlchemy,SQLModel,Psycopg 3,Psycopg 2,asyncpg, andPeeweeInstallationRun:pipinstallpgvectorAnd follow the instructions for your database library:DjangoSQLAlchemySQLModelPsycopg 3Psycopg 2asyncpgPeeweeOr check out some examples:Embeddingswith OpenAISentence embeddingswith SentenceTransformersHybrid searchwith SentenceTransformers (Reciprocal Rank Fusion)Hybrid searchwith SentenceTransformers (cross-encoder)Image searchwith PyTorchImplicit feedback recommendationswith ImplicitExplicit feedback recommendationswith SurpriseRecommendationswith LightFMHorizontal scalingwith CitusDjangoCreate a migration to enable the extensionfrompgvector.djangoimportVectorExtensionclassMigration(migrations.Migration):operations=[VectorExtension()]Add a vector field to your modelfrompgvector.djangoimportVectorFieldclassItem(models.Model):embedding=VectorField(dimensions=3)Insert a vectoritem=Item(embedding=[1,2,3])item.save()Get the nearest neighbors to a vectorfrompgvector.djangoimportL2DistanceItem.objects.order_by(L2Distance('embedding',[3,1,2]))[:5]Also supportsMaxInnerProductandCosineDistanceGet the distanceItem.objects.annotate(distance=L2Distance('embedding',[3,1,2]))Get items within a certain distanceItem.objects.alias(distance=L2Distance('embedding',[3,1,2])).filter(distance__lt=5)Average vectorsfromdjango.db.modelsimportAvgItem.objects.aggregate(Avg('embedding'))Also supportsSumAdd an approximate indexfrompgvector.djangoimportIvfflatIndex,HnswIndexclassItem(models.Model):classMeta:indexes=[IvfflatIndex(name='my_index',fields=['embedding'],lists=100,opclasses=['vector_l2_ops']),# orHnswIndex(name='my_index',fields=['embedding'],m=16,ef_construction=64,opclasses=['vector_l2_ops'])]Usevector_ip_opsfor inner product andvector_cosine_opsfor cosine distanceSQLAlchemyEnable the extensionsession.execute(text('CREATE EXTENSION IF NOT EXISTS vector'))Add a vector columnfrompgvector.sqlalchemyimportVectorclassItem(Base):embedding=mapped_column(Vector(3))Insert a vectoritem=Item(embedding=[1,2,3])session.add(item)session.commit()Get the nearest neighbors to a vectorsession.scalars(select(Item).order_by(Item.embedding.l2_distance([3,1,2])).limit(5))Also supportsmax_inner_productandcosine_distanceGet the distancesession.scalars(select(Item.embedding.l2_distance([3,1,2])))Get items within a certain distancesession.scalars(select(Item).filter(Item.embedding.l2_distance([3,1,2])<5))Average vectorsfromsqlalchemy.sqlimportfuncsession.scalars(select(func.avg(Item.embedding))).first()Also supportssumAdd an approximate indexindex=Index('my_index',Item.embedding,postgresql_using='ivfflat',postgresql_with={'lists':100},postgresql_ops={'embedding':'vector_l2_ops'})# orindex=Index('my_index',Item.embedding,postgresql_using='hnsw',postgresql_with={'m':16,'ef_construction':64},postgresql_ops={'embedding':'vector_l2_ops'})index.create(engine)Usevector_ip_opsfor inner product andvector_cosine_opsfor cosine distanceSQLModelEnable the extensionsession.exec(text('CREATE EXTENSION IF NOT EXISTS vector'))Add a vector columnfrompgvector.sqlalchemyimportVectorfromsqlalchemyimportColumnclassItem(SQLModel,table=True):embedding:List[float]=Field(sa_column=Column(Vector(3)))Insert a vectoritem=Item(embedding=[1,2,3])session.add(item)session.commit()Get the nearest neighbors to a vectorsession.exec(select(Item).order_by(Item.embedding.l2_distance([3,1,2])).limit(5))Also supportsmax_inner_productandcosine_distancePsycopg 3Enable the extensionconn.execute('CREATE EXTENSION IF NOT EXISTS vector')Register the vector type with your connectionfrompgvector.psycopgimportregister_vectorregister_vector(conn)Forasync connections, usefrompgvector.psycopgimportregister_vector_asyncawaitregister_vector_async(conn)Create a tableconn.execute('CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))')Insert a vectorembedding=np.array([1,2,3])conn.execute('INSERT INTO items (embedding) VALUES (%s)',(embedding,))Get the nearest neighbors to a vectorconn.execute('SELECT * FROM items ORDER BY embedding <->%sLIMIT 5',(embedding,)).fetchall()Psycopg 2Enable the extensioncur=conn.cursor()cur.execute('CREATE EXTENSION IF NOT EXISTS vector')Register the vector type with your connection or cursorfrompgvector.psycopg2importregister_vectorregister_vector(conn)Create a tablecur.execute('CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))')Insert a vectorembedding=np.array([1,2,3])cur.execute('INSERT INTO items (embedding) VALUES (%s)',(embedding,))Get the nearest neighbors to a vectorcur.execute('SELECT * FROM items ORDER BY embedding <->%sLIMIT 5',(embedding,))cur.fetchall()asyncpgEnable the extensionawaitconn.execute('CREATE EXTENSION IF NOT EXISTS vector')Register the vector type with your connectionfrompgvector.asyncpgimportregister_vectorawaitregister_vector(conn)or your poolasyncdefinit(conn):awaitregister_vector(conn)pool=awaitasyncpg.create_pool(...,init=init)Create a tableawaitconn.execute('CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))')Insert a vectorembedding=np.array([1,2,3])awaitconn.execute('INSERT INTO items (embedding) VALUES ($1)',embedding)Get the nearest neighbors to a vectorawaitconn.fetch('SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5',embedding)PeeweeAdd a vector columnfrompgvector.peeweeimportVectorFieldclassItem(BaseModel):embedding=VectorField(dimensions=3)Insert a vectoritem=Item.create(embedding=[1,2,3])Get the nearest neighbors to a vectorItem.select().order_by(Item.embedding.l2_distance([3,1,2])).limit(5)Also supportsmax_inner_productandcosine_distanceGet the distanceItem.select(Item.embedding.l2_distance([3,1,2]).alias('distance'))Get items within a certain distanceItem.select().where(Item.embedding.l2_distance([3,1,2])<5)Average vectorsfrompeeweeimportfnItem.select(fn.avg(Item.embedding)).scalar()Also supportssumAdd an approximate indexItem.add_index('embedding vector_l2_ops',using='hnsw')Usevector_ip_opsfor inner product andvector_cosine_opsfor cosine distanceHistoryView thechangelogContributingEveryone is encouraged to help improve this project. Here are a few ways you can help:Report bugsFix bugs andsubmit pull requestsWrite, clarify, or fix documentationSuggest or add new featuresTo get started with development:gitclonehttps://github.com/pgvector/pgvector-python.gitcdpgvector-python
pipinstall-rrequirements.txt
createdbpgvector_python_test
pytest