1

我是弹性搜索的新手,我正在使用elasticsearch-dsl库在 python 中实现它。

我坚持动态创建查询。

例如,我可以简单地直接做这样的事情,

q = (Q('match', age=21) | Q('match', gender='male')) & (~Q('match', name='Stevens'))

但是我怎样才能动态地进行这样的查询呢?

我试过这样的事情:

# simple json input, based on which query should be changed
json_input = {'fields': ['age', 'gender'], 'values': {'age': 21, 'gender': 'male'}}

age_query = None
gender_query = None
name_query = None

if 'age' in json_input['fields']:
    age_query = Q('match', age=json_input['values']['age'])

if 'gender' in json_input['fields']:
    gender_query = Q('match', age=json_input['values']['gender'])

if 'name' in json_input['fields']:
    name_query = ~Q('match', age=json_input['values']['name'])

q = Q()
if gender_query or age_query:
    q = (age_query | gender_query)
if name_query:
    q &= name_query

但是当我执行搜索时:

s = Search(using=client, index=index)
s = s.query(q)
response = s.execute()

它在执行搜索时出错,

RequestError: RequestError(400, u'search_phase_execution_exception', u'failed to create query: {\n  "bool" : {\n    "should" : [\n      {\n        "match" : {\n          "age" : {\n            "query" : 21,\n            "operator" : "OR",\n            "prefix_length" : 0,\n            "max_expansions" : 50,\n            "fuzzy_transpositions" : true,\n            "lenient" : false,\n            "zero_terms_query" : "NONE",\n            "auto_generate_synonyms_phrase_query" : true,\n            "boost" : 1.0\n          }\n        }\n      },\n      {\n        "match" : {\n          "age" : {\n            "query" : "male",\n            "operator" : "OR",\n            "prefix_length" : 0,\n            "max_expansions" : 50,\n            "fuzzy_transpositions" : true,\n            "lenient" : false,\n            "zero_terms_query" : "NONE",\n            "auto_generate_synonyms_phrase_query" : true,\n            "boost" : 1.0\n          }\n        }\n      }\n    ],\n    "adjust_pure_negative" : true,\n    "boost" : 1.0\n  }\n}')

我想知道这个查询生成有什么问题,还有更合适的方法吗?

PS如果我这样做,它会生成正确的JSON s.to_dict(),如下所示:

{'query': {'bool': {'should': [{'match': {'age': 21}},
                           {'match': {'age': 'male'}}]}}}
4

1 回答 1

1

我认为第二个和第三个 if 没有使用正确的字段:

if 'gender' in json_input['fields']:
    gender_query = Q('match', gender=json_input['values']['gender'])
                                ^
                                |
                      change this field name


if 'name' in json_input['fields']:
    name_query = ~Q('match', name=json_input['values']['name'])
                               ^
                               |
                     change this field name
于 2019-07-09T07:03:51.733 回答