如何在嵌套聚合中使用过滤器?

时间:2019-07-18 09:42:16

标签: elasticsearch

如何从嵌套对象中过滤多个字段以进行Elasticsearch?

现在我只能对Elasticsearch嵌套对象做一个字段过滤器。

POST / blog / blog / 1

{
  "title": "Invest Money",
  "body": "Please start investing money as soon...",
  "tags": ["money", "invest"],
  "published_on": "18 Oct 2017",
  "comments": [
    {
      "name": "William",
      "age": 34,
      "rating": 8,
      "comment": "Nice article..",
      "commented_on": "30 Nov 2017"
    },
    {
      "name": "John",
      "age": 38,
      "rating": 9,
      "comment": "I started investing after reading this.",
      "commented_on": "25 Nov 2017"
    },
    {
      "name": "Smith",
      "age": 33,
      "rating": 7,
      "comment": "Very good post",
      "commented_on": "20 Nov 2017"
    }
  ]
}

POST / blog / blog / 2

{
  "title": "Hero",
  "body": "Hero test body...",
  "tags": ["Heros", "happy"],
  "published_on": "6 Oct 2018",
  "comments": [
    {
      "name": "steve",
      "age": 24,
      "rating": 18,
      "comment": "Nice article..",
      "commented_on": "3 Nov 2018"
    }
  ]
}

ES查询:

{
    "size": 0,
    "aggs": {
        "comments": {
            "nested": {
                "path": "comments"
            },

            "aggs": {
                "groups": {

                    "terms": {
                        "field": "comments.name",
"include": "William",
                        "order": {
                            "rate": "desc"
                        }
                    },

                    "aggs": {
                        "rate": {
                            "min": {
                                "field": "comments.age"
                            }
                        }
                    }
                }
            }
        }
    }
}

我可以获取发表评论的每个人的最小年龄汇总。评论作者,我可以包含/排除comments.name。我想为评分低于8的评论添加过滤器。谁可以帮助我获得dsl?

1 个答案:

答案 0 :(得分:0)

您必须使用filter aggregation来基于等级过滤评论。

{
  "size": 0,
  "aggs": {
    "comments": {
      "nested": {
        "path": "comments"
      },
      "aggs": {
        "filterByRating": {
          "filter": {
            "range": {
              "comments.rating": {
                "lt": 8
              }
            }
          },
          "aggs": {
            "groups": {
              "terms": {
                "field": "comments.name",
                "include": "William",
                "order": {
                  "rate": "desc"
                }
              },
              "aggs": {
                "rate": {
                  "min": {
                    "field": "comments.age"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}