gpt4 book ai didi

Python elasticsearch-dsl 动态查询

转载 作者:行者123 更新时间:2023-12-01 07:37:01 25 4
gpt4 key购买 nike

我是 Elasticsearch 的新手,我正在使用 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}')

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

附注如果我执行 s.to_dict() ,它会生成正确的 JSON,如下所示:

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

最佳答案

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

关于Python elasticsearch-dsl 动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com