Skip to content

SQLAlchemy

This example defines an ORM model with an AkasicDB vector column, creates a vector index, and orders rows by L2 distance.

Install

pip install "akasicdb[sqlalchemy]"

Example

from sqlalchemy import Index, create_engine, insert, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column

from akasicdb.sqlalchemy import VECTOR
from akasicdb.types import Hnsw, IndexOption

DB_URL = "postgresql+psycopg://postgres:mysecretpassword@localhost:5432/postgres"


class Base(DeclarativeBase):
    pass


class Document(Base):
    __tablename__ = "documents"

    id: Mapped[int] = mapped_column(primary_key=True)
    embedding = mapped_column(VECTOR(3))


engine = create_engine(DB_URL)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

with Session(engine) as session:
    session.execute(insert(Document).values(embedding=[1.0, 2.0, 3.0]))
    session.execute(insert(Document).values(embedding=[1.0, 3.0, 4.0]))
    session.commit()

    index = Index(
        "documents_embedding_idx",
        Document.embedding,
        postgresql_using="vectoron",
        postgresql_with={
            "options": f"$${IndexOption(index=Hnsw(), threads=1).dumps()}$$"
        },
        postgresql_ops={"embedding": "vector_l2_ops"},
    )
    index.create(session.bind)

    rows = session.scalars(
        select(Document).order_by(Document.embedding.l2_distance([1.0, 2.0, 3.5]))
    ).all()

    for row in rows:
        print(row.id, row.embedding)