mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 00:39:20 +08:00
47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
"""Mongo 连接与索引。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
|
|
|
|
from config.settings import Settings
|
|
|
|
_client: AsyncIOMotorClient | None = None
|
|
|
|
|
|
async def get_db(settings: Settings) -> AsyncIOMotorDatabase:
|
|
global _client
|
|
if _client is None:
|
|
_client = AsyncIOMotorClient(settings.mongo_uri)
|
|
return _client[settings.mongo_db]
|
|
|
|
|
|
async def ensure_indexes(db: AsyncIOMotorDatabase) -> None:
|
|
await db.agent_sessions.create_index(
|
|
[("company_id", 1), ("user_id", 1), ("thread_id", 1)], unique=True
|
|
)
|
|
await db.agent_sessions.create_index(
|
|
[("company_id", 1), ("user_id", 1), ("status", 1), ("scene", 1), ("updated_at", -1)]
|
|
)
|
|
await db.agent_sessions.create_index(
|
|
[("company_id", 1), ("user_id", 1), ("scene", 1), ("scene_ref", 1), ("status", 1)]
|
|
)
|
|
await db.agent_messages.create_index(
|
|
[("company_id", 1), ("user_id", 1), ("thread_id", 1), ("seq", 1)]
|
|
)
|
|
await db.agent_user_memory.create_index(
|
|
[("company_id", 1), ("user_id", 1), ("status", 1), ("kind", 1), ("updated_at", -1)]
|
|
)
|
|
await db.agent_user_memory.create_index(
|
|
[("company_id", 1), ("user_id", 1), ("key", 1)],
|
|
unique=True,
|
|
partialFilterExpression={"key": {"$type": "string"}},
|
|
)
|
|
|
|
|
|
async def close_mongo() -> None:
|
|
global _client
|
|
if _client is not None:
|
|
_client.close()
|
|
_client = None
|