应该查询里面必须elasticsearch

时间:2019-11-21 12:31:49

标签: elasticsearch elasticsearch-query

我是Elasticsearch查询DSL的新手,我的ES索引中包含以下文档

{
    "doc_id":1,
    "city_id": 1,
    "name": "test1",
    "vvip": false
},
{   
    "doc_id":2,
    "city_id": 1,
    "name": "test2",
    "vvip": false
},
{   
    "doc_id":3,
    "city_id": 1,
    "name": "test3"
}
{
    "doc_id":4,
    "city_id": 1,
    "name": "test4"
}
{
    "doc_id":5,
    "city_id": 1,
    "name": "test5",
    "vvip": true
}
{
    "doc_id":6,
    "city_id": 1,
    "name": "test6",
    "vvip": true
}

对于doc_id 3和doc_id 4,vvip字段不存在

我想以这样的方式进行查询:如果我查询vvip:true或vvip:false,则应始终返回这些文档

意思是查询city_id = 1和vvip = false 响应将包含doc_id 1,2,3,4 对于city_id = 1和vvip = true 响应将包含doc_id 3、4、5、6

我尝试了以下查询,但没有帮助

{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "city_id": "1"
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "vvip"
                    }
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "city_id": "1"
                }
              },
              {
                "match": {
                  "vvip": false
                }
              }
            ]
          }
        }
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以像这样简化查询,该查询应该可以按预期工作:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "city_id": "1"
          }
        },
        {
          "bool": {
            "should": [
              {
                "match": {
                  "vvip": true
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "vvip"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

查询意味着您匹配city_id=1 AND vvip=true OR vvip 不存在