core/services/search.py

155 lines
4.9 KiB
Python
Raw Normal View History

2022-11-17 19:53:58 +00:00
import json
2023-12-19 12:18:58 +00:00
import logging
2024-01-29 00:27:30 +00:00
import os
2023-12-17 20:30:20 +00:00
2024-01-29 02:00:54 +00:00
from opensearchpy import OpenSearch
2023-12-17 20:30:20 +00:00
2024-01-29 01:09:54 +00:00
from services.rediscache import redis
2022-10-04 00:32:29 +00:00
2024-01-29 00:27:30 +00:00
logger = logging.getLogger('[services.search] ')
logger.setLevel(logging.DEBUG)
ELASTIC_HOST = os.environ.get('ELASTIC_HOST', 'localhost').replace('https://', '').replace('http://', '')
ELASTIC_USER = os.environ.get('ELASTIC_USER', '')
ELASTIC_PASSWORD = os.environ.get('ELASTIC_PASSWORD', '')
ELASTIC_PORT = os.environ.get('ELASTIC_PORT', 9200)
ELASTIC_AUTH = f'{ELASTIC_USER}:{ELASTIC_PASSWORD}' if ELASTIC_USER else ''
2024-01-29 01:09:54 +00:00
ELASTIC_URL = os.environ.get('ELASTIC_URL', f'https://{ELASTIC_AUTH}@{ELASTIC_HOST}:{ELASTIC_PORT}')
ELASTIC_REINDEX = os.environ.get('ELASTIC_REINDEX', '')
REDIS_TTL = 86400 # 1 day in seconds
2024-01-29 00:27:30 +00:00
2024-01-29 01:09:54 +00:00
class SearchService:
2024-01-29 01:41:46 +00:00
async def __init__(self, index_name='search_index'):
2024-01-29 01:43:02 +00:00
logger.info('initialized')
2024-01-29 00:27:30 +00:00
self.index_name = index_name
2024-01-29 01:47:53 +00:00
self.disabled = False
try:
2024-01-29 02:00:54 +00:00
self.client = OpenSearch(
hosts = [{'host': ELASTIC_HOST, 'port': ELASTIC_PORT}],
http_compress = True,
http_auth = (ELASTIC_USER, ELASTIC_PASSWORD),
use_ssl = True,
verify_certs = False,
ssl_assert_hostname = False,
ssl_show_warn = False,
# ca_certs = ca_certs_path
)
2024-01-29 01:47:53 +00:00
except Exception as exc:
logger.error(exc)
self.disabled = True
2024-01-29 00:27:30 +00:00
self.check_index()
2024-01-29 01:09:54 +00:00
if ELASTIC_REINDEX:
self.recreate_index()
2024-01-29 01:41:46 +00:00
def info(self):
2024-01-29 02:00:54 +00:00
logging.info(f'{self.client}')
2024-01-29 01:41:46 +00:00
2024-01-29 00:27:30 +00:00
def delete_index(self):
2024-01-29 02:00:54 +00:00
self.client.indices.delete(index=self.index_name, ignore_unavailable=True)
2024-01-29 00:27:30 +00:00
def create_index(self):
index_settings = {
'settings': {
'index': {
'number_of_shards': 1,
'auto_expand_replicas': '0-all',
},
'analysis': {
'analyzer': {
'ru': {
'tokenizer': 'standard',
'filter': ['lowercase', 'ru_stop', 'ru_stemmer'],
}
},
'filter': {
'ru_stemmer': {
'type': 'stemmer',
'language': 'russian',
},
'ru_stop': {
'type': 'stop',
'stopwords': '_russian_',
},
},
},
},
'mappings': {
'properties': {
2024-01-29 01:09:54 +00:00
'body': {'type': 'text', 'analyzer': 'ru'},
2024-01-29 00:27:30 +00:00
'text': {'type': 'text'},
'author': {'type': 'text'},
}
},
}
2024-01-29 02:00:54 +00:00
self.client.indices.create(index=self.index_name, body=index_settings)
self.client.indices.close(index=self.index_name)
self.client.indices.open(index=self.index_name)
2024-01-29 00:27:30 +00:00
def put_mapping(self):
mapping = {
'properties': {
2024-01-29 01:09:54 +00:00
'body': {'type': 'text', 'analyzer': 'ru'},
2024-01-29 00:27:30 +00:00
'text': {'type': 'text'},
'author': {'type': 'text'},
}
}
2024-01-29 02:00:54 +00:00
self.client.indices.put_mapping(index=self.index_name, body=mapping)
2024-01-29 00:27:30 +00:00
def check_index(self):
2024-01-29 02:00:54 +00:00
if not self.client.indices.exists(index=self.index_name):
2024-01-29 00:27:30 +00:00
logger.debug(f'Creating {self.index_name} index')
self.create_index()
self.put_mapping()
2024-01-29 01:09:54 +00:00
def recreate_index(self):
self.delete_index()
self.check_index()
2024-01-29 00:27:30 +00:00
def index_post(self, shout):
id_ = str(shout.id)
logger.debug(f'Indexing post id {id_}')
2024-01-29 02:00:54 +00:00
self.client.index(index=self.index_name, id=id_, body=shout)
2024-01-29 00:27:30 +00:00
def search_post(self, query, limit, offset):
2024-01-29 01:09:54 +00:00
logger.debug(f'query: {query}')
2024-01-29 00:27:30 +00:00
search_body = {
2024-01-29 01:09:54 +00:00
'query': {'match': {'_all': query}},
2024-01-29 00:27:30 +00:00
}
2024-01-29 02:00:54 +00:00
search_response = self.client.search(
2024-01-29 00:27:30 +00:00
index=self.index_name, body=search_body, size=limit, from_=offset
)
hits = search_response['hits']['hits']
return [
{
**hit['_source'],
'score': hit['_score'],
}
for hit in hits
]
2024-01-29 01:41:46 +00:00
search = SearchService()
async def search_text(text: str, limit: int = 50, offset: int = 0):
payload = []
try:
# Use a key with a prefix to differentiate search results from other Redis data
redis_key = f'search:{text}'
2024-01-29 01:47:53 +00:00
if not search.disabled:
# Use OpenSearchService.search_post method
payload = search.search_post(text, limit, offset)
# Use Redis as cache with TTL
await redis.execute('SETEX', redis_key, REDIS_TTL, json.dumps(payload))
2024-01-29 01:41:46 +00:00
except Exception as e:
logging.error(f'Error during search: {e}')
return payload