-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
30 lines (24 loc) · 919 Bytes
/
search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from flask import current_app
def add_to_index(index, model):
if not current_app.elasticsearch:
return
payload = {}
for field in model.__searchable__:
payload[field] = getattr(model, field)
current_app.elasticsearch.index(index=index, id=model.id, body=payload)
def remove_from_index(index, model):
if not current_app.elasticsearch:
return
current_app.elasticsearch.delete(index=index, id=model.id)
def query_index(index, query, page, per_page):
if not current_app.elasticsearch:
return [], 0
search = current_app.elasticsearch.search(
index=index,
body={'query':{'multi_match':{'query':query, 'fields':['_all']}},
'from': (page-1)*per_page, 'size':per_page}
)
if not search['hits']:
return [], 0
ids = [int(hit['_id']) for hit in search['hits']['hits']]
return ids, search['hits']['total']