elasticsearch dsl python unpack q查询

时间:2017-03-31 10:10:22

标签: python elasticsearch elasticsearch-dsl elasticsearch-dsl-py q-query

如何在elasticsearch dsl python中动态创建组合Q查询? 我经历了docsSO post。我构建了一个包含所有必需信息的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与一个或运算符或运算符组合?对于上述内容,相应的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的同一查询,并且获得的结果是相同的。因此,在我的情况下,过滤器不会由elasticsearch执行。 非常感谢任何帮助。

TIA

1 个答案:

答案 0 :(得分:2)

在探索elasticsearch dsl python多一段时间之后,this piece of documentation帮助我解决了上述问题。下面发布的是我为解决此问题而编写的函数。

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的格式,以便根据andor等多个运算符执行链接。

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

             ]