跟我学Elasticsearch(7) es的嵌套聚合,下钻分析,聚合分析

[Toc]

演示前先往es写入三条商品数据用来演示查询

PUT /product/book/1
{
    "product_name": "yuwen shu",
    "price": 20,
    "all_tags": ["bad","ugly"]
}
PUT /product/book/2
{
    "product_name": "shuxue shu",
    "price": 10,
    "all_tags": ["good","ugly"]
}

1、统计每个标签对应的商品数量

对all_tags字段做聚合/排序/脚本访问我们需要先把all_tags字段默认关闭的fielddata开启

PUT /product/_mapping/book
{
  "properties": {
    "all_tags": {
      "type": "text",
      "fielddata": true
    }
  }
}

开始演示

GET /product/book/_search
{
  "size": 0,
  "aggs": {
    "terms_all_tags": {
      "terms": { "field": "all_tags" }
    }
  }
}

aggregations.terms_all_tags.buckets.key:标签

aggregations.terms_all_tags.buckets.doc_count:该标签对应的商品数量

2、对商品名称包含shu的商品,统计每个标签对应的商品数量

GET /product/book/_search
{
  "size": 0,
  "query": {
    "match": {
      "product_name": "shu"
    }
  },
  "aggs": {
    "terms_all_tags": {
      "terms": {
        "field": "all_tags"
      }
    }
  }
}

3、计算每个标签对应的商品的平均价格

GET /product/book/_search
{
    "size": 0,
    "aggs" : {
        "terms_all_tags" : {
            "terms" : { "field" : "all_tags" },
            "aggs" : {
                "avg_price" : {
                    "avg" : { "field" : "price" }
                }
            }
        }
    }
}

4、计算每个标签对应的商品的平均价格并按平均价格降序排序

GET /product/book/_search
{
    "size": 0,
    "aggs" : {
        "terms_all_tags" : {
            "terms" : { "field" : "all_tags", "order": { "avg_price": "desc" } },
            "aggs" : {
                "avg_price" : {
                    "avg" : { "field" : "price" }
                }
            }
        }
    }
}

5、按价格区间进行分组,然后在每组内计算每个标签对应的商品的平均价格

GET /product/book/_search
{
  "size": 0,
  "aggs": {
    "range_price": {
      "range": {
        "field": "price",
        "ranges": [
          {
            "from": 0,
            "to": 50
          },
          {
            "from": 50,
            "to": 100
          }
        ]
      },
      "aggs": {
        "terms_all_tags": {
          "terms": {
            "field": "all_tags"
          },
          "aggs": {
            "average_price": {
              "avg": {
                "field": "price"
              }
            }
          }
        }
      }
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容