0

如何在elasticsearch dsl python中动态创建组合Q查询?我浏览了文档和这篇SO 帖子。我构建了一个包含所有必需信息的 q_query 字典。

ipdb> q_queries
{'queries': [{'status': 'PASS'}, {'status': 'FAIL'}, {'status': 'ABSE'}, {'status': 'WITH'}], 'operation': 'or'}

我想执行以下 q_query

qq=Q("match", status='PASS') | Q("match", status="FAIL") | Q("match", status="ABSE") | Q("match", status="WITH")

对于以下的 dict 列表

ipdb> [Q('match', **z) for z in q_queries['queries']]
[Match(status='PASS'), Match(status='FAIL'), Match(status='ABSE'), Match(status='WITH')]

但是如何将多个 Q 与 or 运算符或 and 运算符结合起来呢?上面对应elasticsearch raw query的是什么?我尝试了以下,因为我必须根据 test_id 进行过滤。

{
  "query": {
    "bool": {
      "must":     [
        { "match": { "test_id": "7" }},
        {
          "range": {
            "created": {
              "gte": "2016-01-01",
              "lte": "2016-01-31"
            }
          }
        }
        ],
      "should": [
                  { "match": { "status": "PASS"}},
                  { "match": { "status": "FAIL"}}
      ]
    }
  }
}

但是结果并不像我预期的那样我没有相同的查询,should filter并且获得的结果是相同的。所以在我的情况下,过滤器应该不是由弹性搜索执行的。任何帮助深表感谢。

TIA

4

1 回答 1

2

在探索了 elasticsearch dsl python 一段时间后,这篇文档帮助我解决了上述问题。下面发布的是我为解决此问题而编写的函数。

def create_q_queries(self, q_queries, search_query):
    """
    create q queries and chain if multiple q queries.
    :param q_queries: Q queries with operation and query params as a dict.
    :param search_query: Search() object.
    :return: search_query updated with q queries.
    """
    if q_queries:
        logical_operator_mappings = {'or': 'should', 'and': 'must'}
        for query in q_queries:
            queries = [Q('match', **query) for query in query['queries']]
            search_query = search_query.query(Q('bool', **{
                logical_operator_mappings.get(query.get('operation')): queries
            }))
    return search_query  

我更改了 q_queries 的格式以执行基于多个运算符(如and等)的链接or

q_queries = [
              {
                "operation": "or",
                "queries":
                  [
                    {"status": "PASS"}, {"status": "FAIL"}, {"status": "ABSE"}, {"status": "WITH"}
                  ]
                }

             ]
于 2017-03-31T17:42:01.363 回答