ELASTICSEARCH

[엘라스틱서치] 8. Aggregations

sejin2 2024. 3. 14. 09:59

Aggregations : 집계

  • Metrics Aggregations : 산술 min, max, sum, Avg
POST ball_index/_bulk
{ "index" : {"_id" : "1" } }
{"team" : "Golden States Warriors","name" : "Stephen Curry", "points" : 30,"rebounds" : 3,"assists" : 4, "blocks" : 5, "submit_date" : "2024-10-11"}
{ "index" : {"_id" : "2" } }
{"team" : "Golden States Warriors","name" : "Stephen Curry","points" : 20,"rebounds" : 5,"assists" : 8, "blocks" : 5, "submit_date" : "2024-10-13"}

1. avg

GET ball_index/_search
{
  "size":0,
  "aggs":{
    "avg_score":{
      "avg":{
        "field":"points"
      }
    }
  }
}
{
  "took": 15,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 2,
      "relation": "eq"
    },
    "max_score": null,
    "hits": []
  },
  "aggregations": {
    "avg_score": {
      "value": 25
    }
  }
}

2. max

GET ball_index/_search
{
  "size":0,
  "aggs":{
    "max_score":{
      "max":{
        "field":"points"
      }
    }
  }
}
{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 2,
      "relation": "eq"
    },
    "max_score": null,
    "hits": []
  },
  "aggregations": {
    "max_score": {
      "value": 30
    }
  }
}

→ min과 sum도 동일한 방식으로 구할 수 있다.

  • stats : 위의 4개 한꺼번에 확인하는 방법

GET ball_index/_search
{
  "size":0,
  "aggs":{
    "stats_score":{
      "stats":{
        "field":"points"
      }
    }
  }
}
"aggregations": {
    "stats_score": {
      "count": 2,
      "min": 20,
      "max": 30,
      "avg": 25,
      "sum": 50
    }
  }
}

- Bucket Aggregations : 그룹

GET basketball2/_search
{
  "size":0,
  "aggs":{
    "player":{
      "terms":{
        "field":"team"
      }
    }
  }
}

이렇게 "field":"team" 으로 조회하면 조회가 되지 않는다.

GET basketball2/_mapping

"team": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }

keyword를 넣어줘야 있는 그대로 나온다. 그렇지 않으면 소문자로 들어가서 조회되지 않는다.
keyword 타입은 Elasticsearch에서 원본 문자열을 그대로 저장하고, 토큰화되지 않은 상태로 인덱싱하는 데 사용된다.

GET basketball2/_search
{
  "size":0,
  "aggs":{
    "player":{
      "terms":{
        "field":"team.keyword"
      }
    }
  }
}

-> 팀별로 합계, 평균 구하기

GET basketball2/_search
{
  "size":0,
  "aggs":{
    "team_stats":{
      "terms":{
        "field":"team.keyword"
      },
      "aggs":{
        "stats_score":{
          "stats":{
            "field":"points"
          }
        }
      }
    }
  }
}