elasticsearch學習筆記(七)——快速入門案例實戰之電商網站商品管理:嵌套聚合,下鑽分析,聚合分析

爲了描述ES是如何進行嵌套聚合、下鑽分析,聚合分析。下面經過五個業務需求來進行描述。數組

一、計算每一個tag下的商品數量

因爲tag是一個數組,因此其實統計的就是針對tag數組中的每一個值,全部文檔中tag字段中包含這個值的文檔數量。code

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
        }
      ]
    }
  }
}

二、對名稱中包含yagao的商品,計算每一個tag下的商品數量

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

三、計算每一個tag下的商品的平均價格

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

四、計算每一個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"
          }
        }
      }
    }
  }
}

五、按照指定的價格範圍區間進行分組,而後在每組內在按照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"
              }
            }
          }
        }
      }
    }
  }
}
相關文章
相關標籤/搜索