elasticsearch学习笔记(七)——快速入门案例实战之电商网站商品管理:嵌套聚合,下钻分析,聚合分析

为了描述ES是如何进行嵌套聚合、下钻分析,聚合分析。下面通过五个业务需求来进行描述。

1、计算每个tag下的商品数量

由于tag是一个数组,所以其实统计的就是针对tag数组中的每个值,所有文档中tag字段中包含这个值的文档数量。

GET /product/_search
{
  "size": 0,
  "aggs": {
    "all_tags": {
      "terms": {
        "field": "tags",
        "size": 10
      }
    }
  }
}
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "all_tags" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "fangzhu",
          "doc_count" : 2
        },
        {
          "key" : "meibai",
          "doc_count" : 1
        },
        {
          "key" : "qingxin",
          "doc_count" : 1
        }
      ]
    }
  }
}

2、对名称中包含yagao的商品,计算每个tag下的商品数量

GET /product/_search
{
  "query": {
    "match": {
      "name": "yagao"
    }
  },
  "size": 0,
  "aggs": {
    "all_tags": {
      "terms": {
        "field": "tags",
        "size": 10
      }
    }
  }
}

3、计算每个tag下的商品的平均价格

GET /product/_search
{
  "size": 0, 
  "aggs": {
    "group_by_tags": {
      "terms": {
        "field": "tags",
        "size": 10
      },
      "aggs": {
        "avg_price": {
          "avg": {
            "field": "price"
          }
        }
      }
    }
  }
}

4、计算每个tag下商品的平均价格,并且按照平均价格降序排列

GET /product/_search
{
  "size": 0, 
  "aggs": {
    "group_by_tags": {
      "terms": {
        "field": "tags",
        "size": 10,
        "order": {
          "avg_price": "desc"
        }
      },
      "aggs": {
        "avg_price": {
          "avg": {
            "field": "price"
          }
        }
      }
    }
  }
}

5、按照指定的价格范围区间进行分组,然后在每组内在按照tag进行分组,最后在计算每组的平均价格

GET /product/_search
{
  "size": 0,
  "aggs": {
    "group_by_price": {
      "range": {
        "field": "price",
        "ranges": [
          {
            "from": 0,
            "to": 20
          },
          {
            "from": 20,
            "to": 40
          },
          {
            "from": 40,
            "to": 50
          }
        ]
      },
      "aggs": {
        "group_by_tags": {
          "terms": {
            "field": "tags",
            "size": 10
          },
          "aggs": {
            "avg_price": {
              "avg": {
                "field": "price"
              }
            }
          }
        }
      }
    }
  }
}

你可能感兴趣的:(elasticsearch)