如何使用python对两个Elasticsearch查询进行布尔或运算

时间:2018-10-03 19:51:13

标签: python elasticsearch

我有这段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查询,因此我想检查的是是否可以将上述两个查询-ESphrase合并为一个{{1} }查询。因此,只有在第一个查询(best_fields查询)未返回匹配项的情况下,ES的单个ES查询函数将两个查询合并并执行第二个查询(data查询) 。

我在best_fields中注意到有一个bool query,但是我无法弄清楚它是否可以满足我的要求,如果可以,那么我该怎么办。

0 个答案:

没有答案