qotnews/apiserver/search.py

65 lines
2.0 KiB
Python
Raw Normal View History

import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG)
import requests
2022-03-05 21:58:35 +00:00
import settings
2022-03-05 21:58:35 +00:00
SEARCH_ENABLED = bool(settings.MEILI_URL)
def meili_api(method, route, json=None, params=None, parse_json=True):
try:
2022-03-05 21:58:35 +00:00
r = method(settings.MEILI_URL + route, json=json, params=params, timeout=4)
if r.status_code > 299:
raise Exception('Bad response code ' + str(r.status_code))
if parse_json:
return r.json()
else:
return r.text
except KeyboardInterrupt:
raise
except BaseException as e:
logging.error('Problem with MeiliSearch api route: %s: %s', route, str(e))
return False
def create_index():
json = dict(uid='qotnews', primaryKey='id')
return meili_api(requests.post, 'indexes', json=json)
2020-07-06 21:43:57 +00:00
def update_rankings():
2022-03-05 21:33:07 +00:00
json = ['typo', 'words', 'proximity', 'date:desc', 'exactness']
return meili_api(requests.post, 'indexes/qotnews/settings/ranking-rules', json=json)
2020-07-06 21:43:57 +00:00
def update_attributes():
json = ['title', 'url', 'author']
r = meili_api(requests.post, 'indexes/qotnews/settings/searchable-attributes', json=json)
json = ['id', 'ref', 'source', 'author', 'author_link', 'score', 'date', 'title', 'link', 'url', 'num_comments']
2022-03-05 21:33:07 +00:00
r = meili_api(requests.post, 'indexes/qotnews/settings/displayed-attributes', json=json)
return r
2020-07-06 21:43:57 +00:00
def init():
2022-03-05 21:58:35 +00:00
if not SEARCH_ENABLED:
logging.info('Search is not enabled, skipping init.')
return
print(create_index())
2020-07-06 21:43:57 +00:00
update_rankings()
update_attributes()
def put_story(story):
2022-03-05 21:58:35 +00:00
if not SEARCH_ENABLED: return
return meili_api(requests.post, 'indexes/qotnews/documents', [story])
def search(q):
2022-03-05 21:58:35 +00:00
if not SEARCH_ENABLED: return []
params = dict(q=q, limit=250)
r = meili_api(requests.get, 'indexes/qotnews/search', params=params, parse_json=False)
return r
if __name__ == '__main__':
init()
2022-03-05 21:33:07 +00:00
print(update_rankings())
print(search('facebook'))