Python elasticsearchdsl动态查询

2024-06-17 13:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我一直致力于动态创建查询。

例如,我可以直接这样做

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

但是我如何动态地进行这样的查询呢?在

我试过这样的方法:

^{pr2}$

但当我执行搜索时:

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}')

I want to know what's wrong with this query generation, and is there any more appropriate way to do so?

p.S。 如果我执行s.to_dict()操作,它将生成正确的JSON,如下所示:

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

Tags: ortotrueageprefixindexmatchquery
1条回答
网友
1楼 · 发布于 2024-06-17 13:35:51

我认为第二个和第三个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

相关问题 更多 >