Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add a full example for sqlmodel and fix error in README.md. #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,13 @@ session.exec(text('CREATE EXTENSION IF NOT EXISTS vector'))
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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another approach is

id: int = Field(primary_key=True, sa_column_kwargs={"autoincrement": True})

They both seem to have same effect, from what I can tell, so maybe something is autoincrementing behind the scenes.

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

Expand All @@ -237,6 +240,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.

Get the distance

```python
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)