core/services/search.py

162 lines
5.2 KiB
Python
Raw Normal View History

2024-02-29 11:04:24 +00:00
import asyncio
2022-11-17 19:53:58 +00:00
import json
2024-06-02 13:36:12 +00:00
import logging
2024-06-02 14:01:22 +00:00
import os
import httpx
2023-12-17 20:30:20 +00:00
2024-08-07 06:51:09 +00:00
from services.redis import redis
2024-08-09 06:37:06 +00:00
from utils.encoders import CustomJSONEncoder
2022-10-04 00:32:29 +00:00
2024-06-02 13:36:12 +00:00
# Set redis logging level to suppress DEBUG messages
logger = logging.getLogger("search")
logger.setLevel(logging.WARNING)
REDIS_TTL = 86400 # 1 day in seconds
2024-01-29 00:27:30 +00:00
# Configuration for search service
SEARCH_ENABLED = bool(os.environ.get("SEARCH_ENABLED", "true").lower() in ["true", "1", "yes"])
2025-03-12 16:07:27 +00:00
TXTAI_SERVICE_URL = os.environ.get("TXTAI_SERVICE_URL")
2024-05-18 08:52:17 +00:00
2024-02-29 11:09:50 +00:00
2024-01-29 01:09:54 +00:00
class SearchService:
def __init__(self):
logger.info("Initializing search service...")
self.available = SEARCH_ENABLED
self.client = httpx.AsyncClient(timeout=30.0, base_url=TXTAI_SERVICE_URL)
if not self.available:
logger.info("Search disabled (SEARCH_ENABLED = False)")
2024-05-18 08:22:13 +00:00
async def info(self):
"""Return information about search service"""
if not self.available:
2024-11-22 17:32:14 +00:00
return {"status": "disabled"}
2024-12-11 20:02:14 +00:00
2024-11-22 17:23:45 +00:00
try:
response = await self.client.get("/info")
response.raise_for_status()
return response.json()
2024-11-22 17:32:14 +00:00
except Exception as e:
logger.error(f"Failed to get search info: {e}")
return {"status": "error", "message": str(e)}
2024-01-29 01:41:46 +00:00
def is_ready(self):
"""Check if service is available"""
return self.available
2024-01-29 00:27:30 +00:00
2024-01-29 03:42:02 +00:00
def index(self, shout):
"""Index a single document"""
if not self.available:
2024-11-22 17:32:14 +00:00
return
2024-12-11 20:02:14 +00:00
logger.info(f"Indexing post {shout.id}")
# Start in background to not block
asyncio.create_task(self.perform_index(shout))
async def perform_index(self, shout):
"""Actually perform the indexing operation"""
if not self.available:
return
try:
# Combine all text fields
text = " ".join(filter(None, [
shout.title or "",
shout.subtitle or "",
shout.lead or "",
shout.body or "",
shout.media or ""
]))
# Send to txtai service
response = await self.client.post(
"/index",
json={"id": str(shout.id), "text": text}
)
response.raise_for_status()
logger.info(f"Post {shout.id} successfully indexed")
except Exception as e:
logger.error(f"Indexing error for shout {shout.id}: {e}")
2024-04-08 07:23:54 +00:00
async def bulk_index(self, shouts):
"""Index multiple documents at once"""
if not self.available or not shouts:
return
documents = []
for shout in shouts:
text = " ".join(filter(None, [
shout.title or "",
shout.subtitle or "",
shout.lead or "",
shout.body or "",
shout.media or ""
]))
documents.append({"id": str(shout.id), "text": text})
try:
response = await self.client.post(
"/bulk-index",
json={"documents": documents}
)
response.raise_for_status()
logger.info(f"Bulk indexed {len(documents)} documents")
except Exception as e:
logger.error(f"Bulk indexing error: {e}")
2024-01-29 00:27:30 +00:00
2024-01-29 06:45:00 +00:00
async def search(self, text, limit, offset):
"""Search documents"""
if not self.available:
2024-11-22 17:32:14 +00:00
return []
# Check Redis cache first
redis_key = f"search:{text}:{offset}+{limit}"
cached = await redis.get(redis_key)
if cached:
return json.loads(cached)
logger.info(f"Searching: {text} {offset}+{limit}")
try:
response = await self.client.post(
"/search",
json={"text": text, "limit": limit, "offset": offset}
)
response.raise_for_status()
result = response.json()
formatted_results = result.get("results", [])
# Cache results
if formatted_results:
2024-05-18 08:00:01 +00:00
await redis.execute(
"SETEX",
redis_key,
REDIS_TTL,
json.dumps(formatted_results, cls=CustomJSONEncoder),
2024-05-18 08:00:01 +00:00
)
return formatted_results
except Exception as e:
logger.error(f"Search error: {e}")
return []
2024-01-29 00:27:30 +00:00
2024-02-29 11:09:50 +00:00
# Create the search service singleton
2024-01-29 03:42:02 +00:00
search_service = SearchService()
2024-01-29 01:41:46 +00:00
2024-02-29 11:09:50 +00:00
# Keep the API exactly the same to maintain compatibility
2024-01-29 01:41:46 +00:00
async def search_text(text: str, limit: int = 50, offset: int = 0):
payload = []
if search_service.available:
2024-01-29 07:48:36 +00:00
payload = await search_service.search(text, limit, offset)
2024-01-29 01:41:46 +00:00
return payload
2024-11-22 17:23:45 +00:00
2024-12-11 20:02:14 +00:00
# Function to initialize search with existing data
async def initialize_search_index(shouts_data):
"""Initialize search index with existing data during application startup"""
if SEARCH_ENABLED:
logger.info("Initializing search index with existing data...")
await search_service.bulk_index(shouts_data)
logger.info(f"Search index initialized with {len(shouts_data)} documents")