Spaces:
Sleeping
Sleeping
| """Creación de índices de MongoDB. | |
| Se ejecuta una vez al arrancar la aplicación (desde el ``lifespan``). | |
| La creación de índices es idempotente: MongoDB la ignora si el índice | |
| ya existe. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from pymongo import ASCENDING, DESCENDING | |
| from app.database import collections | |
| from app.database.mongodb import get_database | |
| logger = logging.getLogger(__name__) | |
| async def ensure_indexes() -> None: | |
| """Crea los índices necesarios para todas las colecciones.""" | |
| db = get_database() | |
| # Usuarios: username y email únicos. | |
| await db[collections.USERS].create_index("username", unique=True) | |
| await db[collections.USERS].create_index("email", unique=True) | |
| # Categorías: slug único y búsqueda por jerarquía. | |
| await db[collections.CATEGORIAS].create_index("slug", unique=True) | |
| await db[collections.CATEGORIAS].create_index("parent_id") | |
| # Negocios: filtros habituales. | |
| await db[collections.NEGOCIOS].create_index("categoria_id") | |
| await db[collections.NEGOCIOS].create_index("activo") | |
| await db[collections.NEGOCIOS].create_index([("nombre", ASCENDING)]) | |
| # Items: filtros por negocio y tipo. | |
| await db[collections.ITEMS].create_index("negocio_id") | |
| await db[collections.ITEMS].create_index([("negocio_id", ASCENDING), ("tipo", ASCENDING)]) | |
| # Reseñas: listado por negocio y orden cronológico. | |
| await db[collections.RESENAS].create_index( | |
| [("negocio_id", ASCENDING), ("fecha_creacion", DESCENDING)] | |
| ) | |
| logger.info("Índices de MongoDB verificados/creados.") | |