Skip to content

Commit

Permalink
feat: add a full example for sqlmodel and fix error in README.md.
Browse files Browse the repository at this point in the history
  • Loading branch information
FFengIll committed Sep 18, 2023
1 parent b421a54 commit a3e08bb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,13 @@ Use `vector_ip_ops` for inner product and `vector_cosine_ops` for cosine distanc
Add a vector column

```python
from typing import List, Optional

from pgvector.sqlalchemy import Vector
from sqlalchemy import Column
from sqlmodel import Column, Field, Session, SQLModel, create_engine, select

class Item(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
embedding: List[float] = Field(sa_column=Column(Vector(3)))
```

Expand All @@ -209,6 +212,8 @@ session.exec(select(Item).order_by(Item.embedding.l2_distance([3, 1, 2])).limit(

Also supports `max_inner_product` and `cosine_distance`

See [examples/simple_sqlmodel_vector.py](examples/simple_sqlmodel_vector.py) for full code.

## Psycopg 3

Register the vector type with your connection
Expand Down
34 changes: 34 additions & 0 deletions examples/simple_sqlmodel_vector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
A simple sqlmodel vector demo via pgvector.
For mac, if depdency missing or error, try `pip install pgvector-binary`
"""

from typing import List, Optional

from pgvector.sqlalchemy import Vector
from sqlmodel import Column, Field, Session, SQLModel, create_engine, select


class Item(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)

embedding: List[float] = Field(sa_column=Column(Vector(3)))

sqlite_url = f"postgresql://testuser:testuser@localhost:5432/testdb"

engine = create_engine(sqlite_url, echo=False)

SQLModel.metadata.create_all(engine)

with Session(engine) as session:
item = Item(embedding=[1, 2, 3])
session.add(item)
session.commit()

res = session.exec(
select(Item).order_by(Item.embedding.l2_distance([3, 1, 2])).limit(5)
)

for i in res:
print(i)

0 comments on commit a3e08bb

Please sign in to comment.