Elastic Search:一般和条件过滤器

Elastic Search : General and conditional filters

我正在使用 Elastic Search,带有查询 match_all 和过滤。在我的情况下,我想应用一般过滤器并按条件过滤。

此处为伪:

  1. 查询:匹配所有(工作正常)
  2. 在 d1 和 d2 之间过滤范围日期(没有项目符号 3 也能正常工作)
  3. 过滤器(仅当字段存在时应用,但如何?)
  4. 等等

看下面的代码。如果 "groups" 字段存在,我只想应用 "groups" 过滤器! "exists" 过滤器在这种情况下不会生效。

    "query":
    {
        "filtered":
        {
            "query":
            {
                "match_all": {}
            },
            "filter":
            {
                "bool":
                {
                    "must":
                    {
                        "range":
                        {
                            "date": {
                                "from": "2015-06-01",
                                "to": "2015-06-30"
                            }
                        }

                    },
                    "must_not":
                    {
                        "term":
                        {
                            "e.state": 0
                        }
                    }
                }
            },
            "filter":
            {
                "bool":
                {
                    "must":
                    {
                        "exists": {"field": "groups"},
                        "filter":
                        {
                            "bool":
                            {
                                "must":
                                {
                                    "term": {"groups.sex": "w"}
                                },
                                "should":
                                {
                                    "terms": {"groups.categories.id": [7,10]}
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

试试这个

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "must": [
            {
              "range": {
                "date": {
                  "from": "2015-06-01",
                  "to": "2015-06-30"
                }
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "missing": {
                      "field": "groups"
                    }
                  },
                  {
                    "bool": {
                      "must": {
                        "term": {
                          "groups.sex": "w"
                        }
                      },
                      "should": {
                        "terms": {"groups.categories.id": [7,10]}
                      }
                    }
                  }
                ]
              }
            }
          ],
          "must_not": {
            "term": {
              "e.state": 0
            }
          }
        }
      }
    }
  }
}