1. 程式人生 > >Elasticsearch學習筆記(三) 聚合查詢

Elasticsearch學習筆記(三) 聚合查詢

聚合查詢


推薦一個好的翻譯官方文件網站 ( http://cwiki.apachecn.org/
)
聚合提供了從資料中分組和提取資料的能力。最簡單的聚合方法大致等於 SQL GROUP BY 和 SQL 聚合函式。

1. 準備資料

PUT /pigg/_doc/1
{
  "name": "三爺",
  "age": 29,
  "hometown": "鹽城",
  "gender": "male"
}

PUT /pigg/_doc/2
{
  "name": "珣爺",
  "age": 28,
  "hometown": "徐州",
  "gender": "female"
}

PUT /pigg/_doc/3
{
  "name": "米可",
  "age": 1,
  "hometown"
: "蘇州", "gender": "female" }

2. group by(舉例: 按照性別分組)

2.1 SQL描述

SELECT gender, COUNT(1) 
FROM pigg 
GROUP BY gender 
ORDER BY COUNT(1) DESC  

2.2 DSL描述

GET /pigg/_search
{
  "size": 0,
  "aggs": {
    "group_by_gender": {
      "terms": {
        "field": "gender.keyword"
      }
    }
  }
}

2.3 返回結果

{
  ...
  
  "aggregations": {
    "group_by_gender": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "female",
          "doc_count": 2
        },
        {
          "key": "male",
          "doc_count": 1
        }
      ]
    }
  }
}

3. avg(舉例: 求平均年齡)

3.1 SQL描述

SELECT AVG(age) 
FROM pigg

3.2 DSL描述

GET /pigg/_search
{
  "aggs": {
    "avg_age": {
      "avg": {
        "field": "age"
      }
    }
  }
}

3.3 返回結果

{
  ...
  
  "aggregations": {
    "avg_age": {
      "value": 19.333333333333332
    }
  }
}

4. avg和group by組合(舉例: 求不同性別的平均年齡)

4.1 SQL描述

SELECT gender, AVG(age) as 'avg_age'
FROM pigg
GROUP BY gender 
ORDER BY 'avg_age' DESC

4.2 DSL描述

GET /pigg/_search
{
  "size": 0, 
  "aggs": {
    "group_by_gender":{
      "terms": {
        "field": "gender.keyword",
        "order": {
          "avg_age": "desc"
        }
      },
      "aggs": {
        "avg_age": {
          "avg": {
            "field": "age"
          }
        }
      }
    }
  }
}

4.3 返回結果

{
  ...

  "aggregations": {
    "group_by_gender": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "male",
          "doc_count": 1,
          "avg_age": {
            "value": 29
          }
        },
        {
          "key": "female",
          "doc_count": 2,
          "avg_age": {
            "value": 14.5
          }
        }
      ]
    }
  }
}

暫時寫到這邊,ES的聚合功能非常強大,遠不止上面的例子,還需好好學習整理,加油!