1. 程式人生 > >簡單聚合查詢

簡單聚合查詢

ice 屬性設置 ext pri arch mat term gpo div

首先將文本field的fielddata屬性設置為true,否則會報錯
PUT /ecommerce/_mapping/product
{
  "properties" : {
    "tags" : {
      "type" : "text",
      "fielddata" : true
    }
  }
}

1、計算每個tag下的商品數量
GET /ecommerce/product/_search
{
  "size" : 0,
  "aggs" : {
    "all_tags" : {
      "terms" : { "field" : "tags" }
    }
  }
}

2、對名稱中包含yagao的商品,計算每個tag下的商品數量
GET /ecommerce/product/_search
{
  "size" : 0,
  "query" : {
    "match" : {"name" : "yagao"}
  },
  "aggs" : {
    "all_tags" : {
      "terms" : { "field" : "tags"}
    }
  }
}

3、先分組,再計算每組的平均值。計算每個tag下的商品的平均價格
GET /ecommerce/product/_search
{
  "size" : 0,
  "aggs" : {
    "group_by_tags" : {
      "terms" : { "field" : "tags" },
      "aggs" : {
        "avg_price" : {
          "avg" : { "field" : "price" }
        }
      }
    }
  }
}

4、計算每個tag下的商品的平均價格,並且按照平均價格降序排序
GET /ecommerce/product/_search
{
  "size" : 0,
  "aggs" : {
    "all_tags" : {
      "terms" : {"filed" : "tags","order" : {"avg_price" : "desc"}},
      "aggs" : {
        "avg_price" : {
          "avg" : {"field" : "price" }
        }
      }
    }
  }
}

5、按照指定的價格範圍區間進行分組,然後在每組內再按照tag進行分組,最後計算每組的平均價格
GET /ecommerce/product/_search
{
  "size" : 0,
  "aggs" : {
    "group_by_price" : {
      "range" : {
        "field" : "price",
        "ranges" : [
          {
            "from" : 0,
            "to" : 20
          },{
           "from" : 20,
           "to" : 40
          },{
            "from" : 40,
            "to" : 60
          }
        ]
      },
      "aggs" : {
        "group_by_tags" : {
          "terms" : {"field" : "tags"},
          "aggs" : {
            "avg_price" : {
              "avg" : {
                "field" : "price"
              }
            }
          }
        }
      }
    }
  }
}

簡單聚合查詢