core/services/search.py

41 lines
1.6 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 09:25:59 +00:00
SearchService.cache = {}
2022-10-04 00:32:29 +00:00
@staticmethod
2023-12-17 20:30:20 +00:00
async def search(text, limit: int = 50, offset: int = 0) -> List[Shout]:
2022-11-17 20:29:04 +00:00
cached = await redis.execute("GET", text)
2022-11-17 19:53:58 +00:00
if not cached:
async with SearchService.lock:
2023-11-29 07:23:41 +00:00
# Use aiohttp to send a request to ElasticSearch
async with aiohttp.ClientSession() as session:
2023-11-23 23:00:28 +00:00
search_url = f"https://search.discours.io/search?q={text}"
2023-12-19 12:18:58 +00:00
try:
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
return payload[offset : offset + limit]
else:
logging.error(f"[services.search] response: {response.status} {await response.text()}")
except Exception as e:
logging.error(f"[services.search] error: {e}")
2022-11-17 19:53:58 +00:00
else:
2023-12-19 12:03:27 +00:00
return json.loads(cached)[offset : offset + limit]