-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
63 lines (51 loc) · 1.65 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from elasticsearch_dsl import Completion
from elasticsearch_dsl import Date
from elasticsearch_dsl import DocType
from elasticsearch_dsl import String
from elasticsearch_dsl import Text
from elasticsearch_dsl import Keyword
from elasticsearch_dsl import Q
from elasticsearch_dsl.connections import connections
from elasticsearch_dsl import Search
connections.create_connection(hosts=['http://elastic:changeme@localhost:9200'])
def search(author_id, keywords):
s = Search(index='trydemocracy')
query = Q("multi_match", fields=["answers.text", "question"], query=keywords, fuzziness="AUTO") & \
Q("term", author_id=author_id)
response = s.query(query)
hits = [hit for hit in response]
return hits
class Poll(DocType):
question = Text()
type = Text()
author_id = String()
db_id = String()
question_suggest = Completion(payloads=True)
created_at = Date()
answers = Text(
fields={'raw': Keyword()}
)
class Meta:
index = 'trydemocracy'
def index(poll):
elastic_poll = Poll(**poll)
elastic_poll.save()
def index_all(polls):
"""
:param polls: List
:return:
"""
for poll in polls:
elastic_poll = Poll(**{
"author_id": poll["author_id"],
"question": poll["question"],
"answers": [{"text": answer["text"]} for answer in poll["answers"]],
"db_id": poll["poll_id"]
})
print({
"author_id": poll["author_id"],
"question": poll["question"],
"answers": [answer["text"] for answer in poll["answers"]],
"db_id": poll["poll_id"]
})
elastic_poll.save()