我是弹性搜索的新手,我正在使用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}')
我想知道此查询生成有什么问题,并且在那里 还有其他合适的方法吗?
P.S。
如果执行s.to_dict()
,它将生成正确的JSON,如下所示:
{'query': {'bool': {'should': [{'match': {'age': 21}},
{'match': {'age': 'male'}}]}}}
答案 0 :(得分: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