core/services/search.py

43 lines
1.5 KiB
Python
Raw Normal View History

2022-10-04 00:32:29 +00:00
import asyncio
2022-11-17 19:53:58 +00:00
import json
2023-12-19 12:18:58 +00:00
import logging
2023-12-17 20:30:20 +00:00
from typing import List
2023-11-29 07:23:41 +00:00
import aiohttp
2023-12-17 20:30:20 +00:00
2023-12-19 12:18:58 +00:00
from orm.shout import Shout # Adjust the import as needed
from services.rediscache import redis # Adjust the import as needed
2022-10-04 00:32:29 +00:00
class SearchService:
lock = asyncio.Lock()
@staticmethod
2022-10-04 09:25:59 +00:00
async def init(session):
async with SearchService.lock:
2023-12-19 12:18:58 +00:00
logging.info("[services.search] Initializing SearchService")
2022-10-04 00:32:29 +00:00
@staticmethod
2023-12-19 12:28:55 +00:00
async def search(text: str, limit: int = 50, offset: int = 0) -> List[Shout]:
2023-12-19 12:42:46 +00:00
payload = []
2023-12-19 12:28:55 +00:00
try:
2023-12-19 12:42:46 +00:00
cached = await redis.execute("GET", text)
2023-12-19 12:28:55 +00:00
2023-12-19 12:42:46 +00:00
if not cached:
2023-12-19 12:28:55 +00:00
async with SearchService.lock:
# Use aiohttp to send a request to ElasticSearch
async with aiohttp.ClientSession() as session:
search_url = f"https://search.discours.io/search?q={text}"
2023-12-19 12:18:58 +00:00
async with session.get(search_url) as response:
if response.status == 200:
payload = await response.json()
await redis.execute("SET", text, json.dumps(payload)) # use redis as cache
else:
logging.error(f"[services.search] response: {response.status} {await response.text()}")
2023-12-19 12:42:46 +00:00
else:
payload = json.loads(cached)
2023-12-19 12:28:55 +00:00
except Exception as e:
logging.error(f"[services.search] Error during search: {e}")
return payload[offset : offset + limit]