pgvector / pgvector-python

pgvector support for Python
MIT License
877 stars 61 forks source link

How to use SQLAlchemy's most resent PEP 484 Annotated Declarative Table style? #20

Closed mhubig closed 1 year ago

mhubig commented 1 year ago

Hi there I'm wondering how one can utilize the PEP 484 Annotated Declarative Table Style of SQLAlchemy with pgvector

See: https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#using-annotated-declarative-table-type-annotated-forms-for-mapped-column).

This is a Table definition from a small flask app I'm working on, but since I'm fairly new to SQLAlchemy, I'm not sure if this is the correct way of doing it.

from typing import Iterable

from pgvector.sqlalchemy import Vector
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column

from flask_app import db

class Product(db.Model):
    __tablename__ = "product"

    id: Mapped[str] = mapped_column(primary_key=True)
    data: Mapped[dict|list] = mapped_column(type_=JSONB)
    tokensize: Mapped[int]= mapped_column()
    checksum: Mapped[str] = mapped_column(db.String(40), index=True)
    embedding: Mapped[Iterable[float]] = db.mapped_column(Vector(1536))
ankane commented 1 year ago

Hi @mhubig, that should work. From my understanding, the type (Iterable[float]) will be discarded.

If the mapped_column() construct indicates an explicit type as passed to the mapped_column.__type argument, then the given Python type is disregarded.