-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_request.py
74 lines (63 loc) · 2.16 KB
/
test_request.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
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer
import torch
import sys
device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "all-mpnet-base-v2" # "multi-qa-MiniLM-L6-cos-v1" (smaller and faster, but less accurate)
encoder_model = SentenceTransformer(model_name)
encoder_model.to(device)
query_string = sys.argv[1]
semantic = sys.argv[2] == "semantic"
es = Elasticsearch()
query_vector = encoder_model.encode(query_string)
# add an highligher to the title and description fields
if semantic:
query = {
"query": {
"script_score": {
"query": {
"multi_match": {
"query": query_string,
"fields": ["episode_title", "episode_description_clean"]
}
},
"script": {
"source": "cosineSimilarity(params.query_vector, 'episode_embedding') + 1",
"params": {"query_vector": query_vector}
}
}
},
"highlight": {
"fields": {
"episode_title": {},
"episode_description_clean": {}
}
}
}
else:
query = {
"query": {
"multi_match": {
"query": query_string,
"fields": ["episode_title", "episode_description_clean"]
}
},
"highlight": {
"fields": {
"episode_title": {},
"episode_description_clean": {}
}
}
}
res = es.search(index="podmagic-episodes", body=query)
print("Got %d Hits:" % res['hits']['total']['value'])
# print the score, id, title and link of the first 5 hits
for hit in res['hits']['hits'][:5]:
# print score, id, and title and link and highlights
print(f"Title: {hit['_source']['episode_title']} - score: {hit['_score']}")
print(f"Description: {hit['_source']['episode_description_clean']}")
try:
print(f"Highlights: {hit['highlight']}")
except:
print ("No highlights")
print("------------------------------------------------------------------")