弹性搜索词查询两个相互依赖的属性的 AND 条件

use*_*503 5 elasticsearch-5

所以我有一个查询来获取记录,过滤条件是这样的

 GET  tenantforsneha55/permits/_search/ 
    {
      "from":0,
      "size":10,
      "sort":[
        {
          "permitNumber.keyword":{
            "order":"asc"
          }
        }
      ],
      "query":{
        "bool":{
          "must":[
            {
              "terms":{
                "workClassId":[
                  "1",
                  "2"
                ]
              }
            },
            {
              "terms":{
                "typeId":[
                  "1",
                  "2"
                ]
              }
            }
          ]
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

这显示了这样的过滤器的结果获取记录,其中 ["1","2"] 中的 typeId 和 ["1","2"] 中的 classId

但我希望过滤条件像这样 typeId = 1 and classId = 1 OR typeId = 2 and classId = 2。

有没有办法拥有这个?我正在使用 NEST,这个查询是从它生成的,如果你能给我 C#、Elastic v 5.5 中的代码,那就太好了

max*_*s ツ 5

您可以使用如下所示的嵌套shouldmust查询,

   {
      "from":0,
      "size":10,
      "sort":[
        {
          "permitNumber.keyword":{
            "order":"asc"
          }
        }
      ],
      "query":{
        "bool":{
          "should":[
            {
              "bool": {
                "must": [
                  {
                    "term":{ "workClassId":"1" }
                  },
                  {
                    "term":{ "typeId":"1" }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "term":{ "workClassId":"2" }
                  },
                  {
                    "term":{ "typeId":"2" }
                  }
                ]
              }
            }
          ]
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

这不是最简单的方法,但应该这样做。在https://www.elastic.co/blog/lost-in-translation-boolean-operations-and-filters-in-the-bool-query阅读更多相关信息

您也可以以类似的方式使用过滤器。查看https://www.elastic.co/guide/en/elasticsearch/guide/current/combining-filters.html了解更多详情。