我有这段python
代码,分别在其中执行两个Elasticsearch
查询:
def search_es_phrase():
es = Elasticsearch([{'host': str(es_host), 'port': int(es_port)}])
data = {
"query": {
"function_score": {
"query": {
"multi_match": {
"type": "phrase",
"query": "Who am I?",
"fields": ["q"]
}
},
"field_value_factor": {
"field": "votes",
"modifier": "log2p"
}
}
}
}
response = es.search(index=str(index_name).lower(), body=data)
score_answer = []
for items in response['hits']['hits']:
score = items['_score']
source = items['_source']
id = items['_id']
answer = source['a']
score_answer.append([score,id, source, answer])
return score_answer
def search_es_best_fields():
es = Elasticsearch([{'host': str(es_host), 'port': int(es_port)}])
data = {
"query": {
"function_score": {
"query": {
"multi_match": {
"type": "best_fields",
"query": "Who am I?",
"fields": ["q"]
}
},
"field_value_factor": {
"field": "votes",
"modifier": "log2p"
}
}
}
}
response = es.search(index=str(index_name).lower(), body=data)
score_answer = []
for items in response['hits']['hits']:
score = items['_score']
source = items['_source']
id = items['_id']
answer = source['a']
score_answer.append([score,id, source, answer])
return score_answer
if __name__ == '__main__':
es_response = search_es_phrase() # Run phrase ES query
if not es_response:
es_response = search_es_best_fields() # Run best_fields
print(es_response)
如您所见,当前我正在执行的是phrase
Elasticsearch
查询,如果返回空的response
(即没有短语匹配),则执行{ {1}}个查询。请注意,只有在best_fields
匹配查询什么都不返回的情况下,才执行best_fields
查询。
由于当前我执行两个单独的phrase
查询,因此我想检查的是是否可以将上述两个查询-ES
和phrase
合并为一个{{1} }查询。因此,只有在第一个查询(best_fields
查询)未返回匹配项的情况下,ES
的单个ES
查询函数将两个查询合并并执行第二个查询(data
查询) 。
我在best_fields
中注意到有一个bool query,但是我无法弄清楚它是否可以满足我的要求,如果可以,那么我该怎么办。