|
| 1 | +# pgvector-python |
| 2 | + |
| 3 | +[pgvector](https://github.com/ankane/pgvector) support for Python |
| 4 | + |
| 5 | +Supports [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy) and [Psycopg 2](https://github.com/psycopg/psycopg2) |
| 6 | + |
| 7 | +[](https://github.com/ankane/pgvector-python/actions) |
| 8 | + |
| 9 | +## Installation |
| 10 | + |
| 11 | +Run: |
| 12 | + |
| 13 | +```sh |
| 14 | +pip install pgvector |
| 15 | +``` |
| 16 | + |
| 17 | +And follow the instructions for your database library: |
| 18 | + |
| 19 | +- [SQLAlchemy](#sqlalchemy) |
| 20 | +- [Psycopg 2](#psycopg-2) |
| 21 | + |
| 22 | +## SQLAlchemy |
| 23 | + |
| 24 | +Use the vector type |
| 25 | + |
| 26 | +```python |
| 27 | +from pgvector.sqlalchemy import Vector |
| 28 | + |
| 29 | +# Core |
| 30 | +item_table = Table( |
| 31 | + 'item', |
| 32 | + metadata, |
| 33 | + Column('factors', Vector(3)) |
| 34 | +) |
| 35 | + |
| 36 | +# ORM |
| 37 | +class Item(Base): |
| 38 | + factors = Column(Vector(3)) |
| 39 | +``` |
| 40 | + |
| 41 | +Add an index |
| 42 | + |
| 43 | +```python |
| 44 | +index = Index( |
| 45 | + 'my_index', |
| 46 | + item_table.c.factors, # or Item.factors for ORM |
| 47 | + postgresql_using='ivfflat', |
| 48 | + postgresql_with={'lists': 100} |
| 49 | +) |
| 50 | +index.create(engine) |
| 51 | +``` |
| 52 | + |
| 53 | +## Psycopg 2 |
| 54 | + |
| 55 | +Register the vector type with your connection or cursor |
| 56 | + |
| 57 | +```python |
| 58 | +from pgvector.psycopg2 import register_vector |
| 59 | + |
| 60 | +register_vector(conn) |
| 61 | +``` |
| 62 | + |
| 63 | +Insert a Numpy array as a vector |
| 64 | + |
| 65 | +```python |
| 66 | +factors = np.array([1, 2, 3]) |
| 67 | +cur.execute('INSERT INTO item (factors) VALUES (%s)', (factors,)) |
| 68 | +``` |
| 69 | + |
| 70 | +Get the nearest neighbors |
| 71 | + |
| 72 | +```python |
| 73 | +cur.execute('SELECT * FROM item ORDER BY factors <-> %s LIMIT 5', (factors,)) |
| 74 | +cur.fetchall() |
| 75 | +``` |
| 76 | + |
| 77 | +## History |
| 78 | + |
| 79 | +View the [changelog](https://github.com/ankane/pgvector-python/blob/master/CHANGELOG.md) |
| 80 | + |
| 81 | +## Contributing |
| 82 | + |
| 83 | +Everyone is encouraged to help improve this project. Here are a few ways you can help: |
| 84 | + |
| 85 | +- [Report bugs](https://github.com/ankane/pgvector-python/issues) |
| 86 | +- Fix bugs and [submit pull requests](https://github.com/ankane/pgvector-python/pulls) |
| 87 | +- Write, clarify, or fix documentation |
| 88 | +- Suggest or add new features |
| 89 | + |
| 90 | +To get started with development: |
| 91 | + |
| 92 | +```sh |
| 93 | +git clone https://github.com/ankane/pgvector-python.git |
| 94 | +cd pgvector-python |
| 95 | +pip install -r requirements.txt |
| 96 | +pytest |
| 97 | +``` |
0 commit comments