콘텐츠로 이동

Django

이 예제는 standalone script입니다. django_example.py로 저장한 뒤 python django_example.py로 실행합니다.

설치

pip install "akasicdb[django]" Django

예제

from urllib.parse import urlparse

import django
from django.conf import settings
from django.db import connection, models

from akasicdb.django import L2Distance, VamanaIndex, VectorField

DB_URL = "postgresql://postgres:mysecretpassword@localhost:5432/postgres"
parsed = urlparse(DB_URL)

settings.configure(
    DATABASES={
        "default": {
            "ENGINE": "django.db.backends.postgresql",
            "NAME": parsed.path.lstrip("/") or "postgres",
            "USER": parsed.username or "postgres",
            "PASSWORD": parsed.password or "",
            "HOST": parsed.hostname or "localhost",
            "PORT": str(parsed.port or 5432),
        }
    },
    INSTALLED_APPS=[],
)
django.setup()


class Document(models.Model):
    text = models.TextField()
    embedding = VectorField(dim=3)

    class Meta:
        app_label = "django_example"
        db_table = "django_example_documents"
        indexes = [
            VamanaIndex(
                name="django_example_embedding_idx",
                fields=["embedding"],
                opclasses=["vector_l2_ops"],
                threads=1,
            )
        ]


with connection.cursor() as cursor:
    cursor.execute("CREATE EXTENSION IF NOT EXISTS akasicdb")
    cursor.execute("SELECT akasicdb_admin.initialize()")
    cursor.execute("DROP TABLE IF EXISTS django_example_documents CASCADE")

with connection.schema_editor() as schema_editor:
    schema_editor.create_model(Document)

try:
    Document.objects.bulk_create(
        [
            Document(text="hello world", embedding=[1.0, 2.0, 3.0]),
            Document(text="hello postgres", embedding=[1.0, 2.0, 4.0]),
            Document(text="hello akasicdb", embedding=[1.0, 3.0, 4.0]),
        ]
    )

    distance = L2Distance("embedding", [1.0, 2.0, 5.0])
    documents = Document.objects.annotate(distance=distance).order_by("distance")

    for document in documents:
        print(document.text, document.distance)
finally:
    with connection.cursor() as cursor:
        cursor.execute("DROP TABLE IF EXISTS django_example_documents CASCADE")