forked from o19s/elasticsearch-learning-to-rank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeatures.py
92 lines (76 loc) · 2.85 KB
/
features.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""
Gather relevance scores for given
"""
import json
baseQuery = {
"query": {
"bool": {
"filter": {
"ids": {
"values": [
# list of ids goes here
]
}
},
"should": {
# query goes here
}
}
}
}
def kwDocFeatures(es, index, searchType, judgements):
for qid, judgements in judgements.items():
docIds = [judgement.docId for judgement in judgements]
keywords = judgements[0].keywords
bulkSearchReq = []
for query in featureQueries(keywords, docIds):
bulkSearchReq.append(json.dumps({'index': index, 'type': searchType}))
bulkSearchReq.append(json.dumps(query))
res = es.msearch(body="\n".join(bulkSearchReq))
ftrId = 1
for featureResp in res['responses']:
featuresByDoc = {}
for docScored in featureResp['hits']['hits']:
print("%s => %s" % (docScored['_id'], docScored['_score']))
featuresByDoc[docScored['_id']] = docScored['_score']
for judgement in judgements:
try:
judgement.features.append(featuresByDoc[judgement.docId])
except KeyError:
judgement.features.append(0.0)
ftrId += 1
def formatFeature(ftrId, keywords):
from jinja2 import Template
template = Template(open("%s.json.jinja" % ftrId).read())
jsonStr = template.render(keywords=keywords)
return json.loads(jsonStr)
def featureQueries(keywords, docIds):
from copy import deepcopy
thisBase = deepcopy(baseQuery)
thisBase['query']['bool']['filter']['ids']['values'] = docIds
try:
ftrId = 1
while True:
parsedJson = formatFeature(ftrId, keywords)
if not 'query' in parsedJson:
raise ValueError("%s.json.jinja should be an ES query with root of {\"query..." % ftrId)
thisBase['query']['bool']['should'] = parsedJson['query']
yield thisBase
ftrId+=1
except IOError:
pass
def buildFeaturesJudgmentsFile(judgmentsWithFeatures, filename):
with open(filename, 'w') as judgmentFile:
for qid, judgmentList in judgmentsWithFeatures.items():
for judgment in judgmentList:
judgmentFile.write(judgment.toRanklibFormat() + "\n")
if __name__ == "__main__":
from elasticsearch import Elasticsearch
from judgments import judgmentsFromFile, judgmentsByQid
esUrl="http://localhost:9200"
es = Elasticsearch()
judgements = judgmentsByQid(judgmentsFromFile(filename='sample_judgements.txt'))
kwDocFeatures(es, index='tmdb', searchType='movie', judgements=judgements)
for qid, judgmentList in judgements.items():
for judgment in judgmentList:
print(judgment.toRanklibFormat())