From 5aa8258f167e5fb88d7e708e3abeddd89a76112d Mon Sep 17 00:00:00 2001 From: Untone Date: Tue, 19 Dec 2023 15:18:58 +0300 Subject: [PATCH] search-result-schema-fix --- schemas/core.graphql | 8 +++++++- services/search.py | 25 ++++++++++++++----------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/schemas/core.graphql b/schemas/core.graphql index 046bad76..14b19180 100644 --- a/schemas/core.graphql +++ b/schemas/core.graphql @@ -290,6 +290,12 @@ type Result { communities: [Community] } +type SearchResult { + slug: String! + title: String! + score: Float! +} + # Мутации type Mutation { @@ -354,7 +360,7 @@ type Query { get_shout(slug: String, shout_id: Int): Shout load_shouts_followed(follower_id: Int!, limit: Int, offset: Int): [Shout] # userReactedShouts load_shouts_by(options: LoadShoutsOptions): [Shout] - load_shouts_search(text: String!, limit: Int, offset: Int): [Shout] + load_shouts_search(text: String!, limit: Int, offset: Int): [SearchResult] load_shouts_feed(options: LoadShoutsOptions): [Shout] load_shouts_unrated(limit: Int, offset: Int): [Shout] load_shouts_random_top(options: LoadShoutsOptions): [Shout] diff --git a/services/search.py b/services/search.py index 8c66e74f..9b901edf 100644 --- a/services/search.py +++ b/services/search.py @@ -1,21 +1,21 @@ import asyncio import json +import logging from typing import List import aiohttp -from orm.shout import Shout -from services.rediscache import redis +from orm.shout import Shout # Adjust the import as needed +from services.rediscache import redis # Adjust the import as needed class SearchService: lock = asyncio.Lock() - cache = {} @staticmethod async def init(session): async with SearchService.lock: - print("[services.search] did nothing") + logging.info("[services.search] Initializing SearchService") SearchService.cache = {} @staticmethod @@ -26,12 +26,15 @@ class SearchService: # Use aiohttp to send a request to ElasticSearch async with aiohttp.ClientSession() as session: search_url = f"https://search.discours.io/search?q={text}" - async with session.get(search_url) as response: - if response.status == 200: - payload = await response.json() - await redis.execute("SET", text, json.dumps(payload)) - return payload[offset : offset + limit] - else: - print(f"[services.search] response: {response.status} {response.text}") + 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}") else: return json.loads(cached)[offset : offset + limit]