__init__.py 1.25 KB
"""数据库模块,提供统一的向量数据库抽象层.

支持Elasticsearch和PostgreSQL两种后端,通过配置自动切换。
使用示例:
    from app.db import db_client

    # 连接数据库
    await db_client.connect()

    # 创建集合
    await db_client.create_collection("face_vectors", vector_dim=512)

    # 插入数据
    await db_client.insert("face_vectors", "user_001", vector, {"name": "张三"})

    # 向量搜索
    results = await db_client.search("face_vectors", query_vector, top_k=10)

    # 断开连接
    await db_client.disconnect()
"""

from typing import Optional

from app.core.config import settings

es_client = None
pg_client = None


async def connect():
    if settings.db_established:
        from .es_client import get_es_client
        global es_client
        es_client = get_es_client()
        await es_client.connect()
    if settings.db_postgres_enable:
        from .postgres_client import get_pg_client
        global pg_client
        pg_client = get_pg_client()
        await pg_client.connect()


async def disconnect():
    global es_client, pg_client
    if es_client is not None:
        await es_client.disconnect()
        es_client = None
    if pg_client is not None:
        await pg_client.disconnect()