Skip to content

pgvector/pgvector-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pgvector-python

pgvector support for Python

Supports SQLAlchemy and Psycopg 2

Build Status

Installation

Run:

pip install pgvector

And follow the instructions for your database library:

SQLAlchemy

Use the vector type

from pgvector.sqlalchemy import Vector

# Core
item_table = Table(
    'item',
    metadata,
    Column('factors', Vector(3))
)

# ORM
class Item(Base):
    factors = Column(Vector(3))

Add an index

index = Index(
    'my_index',
    item_table.c.factors, # or Item.factors for ORM
    postgresql_using='ivfflat',
    postgresql_with={'lists': 100}
)
index.create(engine)

Insert a vector

item = Item(factors=[1, 2, 3])
session.add(item)
session.commit()

Get the nearest neighbors to a vector

session.query(Item).order_by(Item.factors.l2_distance([3, 1, 2])).limit(5).all()

Also supports max_inner_product and cosine_distance

Psycopg 2

Register the vector type with your connection or cursor

from pgvector.psycopg2 import register_vector

register_vector(conn)

Insert a vector

factors = np.array([1, 2, 3])
cur.execute('INSERT INTO item (factors) VALUES (%s)', (factors,))

Get the nearest neighbors to a vector

cur.execute('SELECT * FROM item ORDER BY factors <-> %s LIMIT 5', (factors,))
cur.fetchall()

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development:

git clone https://github.com/ankane/pgvector-python.git
cd pgvector-python
pip install -r requirements.txt
pytest

About

pgvector support for Python

Resources

License

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors