ELK 스택 찍먹하기 (ElasticSearch, Logstash, Kibana) - 1편 ElasticSearch

이재훈·2024년 2월 20일
0

ELK

목록 보기
1/1

해당 시리즈는 인프런 강의를 듣고 정리한 내용입니다.
ELK 스택 (ElasticSearch, Logstash, Kibana)으로 데이터 분석

학습 목표 : 아래 그림의 내용을 이해하고, 찍먹해보자


데이터를 수집하여 elasticsearch에 넣어주는 logstash
elasticsearch 데이터를 보기 좋게 보여주는 kibana를 사용합니다.
elasticsearch의 빠른 검색으로 빅데이터도 kibana로 빠르게 시각화 할 수 있게 됩니다.

1. 우분투에 엘라스틱 서치 설치하기

Ubuntu 22.04 LTS 버전을 기준입니다.

JDK는 알아서 설치해주세요!!!

  1. 보안키 서명
curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
  1. apt 리스트 추가
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
  1. apt update
sudo apt update
  1. ElasticSearch 서치 설치
sudo apt install elasticsearch
  1. ElasticSearch 서치 실행
service elasticsearch start
  1. 잘 설치되었는지 확인
service elasticsearch status
  1. 버전 확인
curl localhost:9200

2. elasticsearch 기본 개념 정리

용어1

Elastic SearchRDB
IndexDatabase
TypeTable
DocumentRow
FieldColumn
MappingSchema

용어2

Elastic SearchRDB
GETSelect
PUTUpdate
POSTInsert
DELETEDelete

예시

curl -XGET localhost:9200/classes/class/1
-> select * from class where id = 1

curl -XPOST localhost:9200/classes/class/1 -d '{xxx}'
-> Insert into class values (xxx)

curl -XPUT localhost:9200/classes/class/1 -d ' {xxx}'
-> update class set xxx where id = 1

curl -XDELETE localhost:9200/classes/class/1
-> delete from class where id = 1

여기서 classes 는 index, class는 테이블, 1은 id를 뜻합니다.


엘라스틱 서치 결과값을 눈에 보기 좋게 하기 위해 뒤에 파라미터로 pretty를 붙히면 보기 좋게 출력됩니다.

POST / content-type 에러 (잘못된 예시)

curl -XPOST localhost:9200/classes/class/1 -d '{"titile": "me", "professor" : "홍길동"}'


ES6.0 이후 부터는 content-type을 기재해주어야 합니다. (아... 귀찮아)

POST / content-type 삽입 후 성공

curl -XPOST localhost:9200/classes/class/1 -d '{"titile": "me", "professor" : "홍길동"}' -H "Content-Type: application/json"


데이터가 잘 들어가진 것을 확인할 수 있습니다.

POST / .json 파일 insert 하기

curl -XPOST http://localhost:9200/classes/class/1/ -d @oneclass.json -H "Content-Type: application/json"

BULK POST

curl -XPOST http://localhost:9200/_bulk?pretty --data-binary @class.json -H "Content-Type: application/json"

3. Mapping

curl -XPUT http://localhost:9200/classes/class/_mapping -d @classRating_mapping.json -H "Content-Type: application/json"

매핑을 추가하게 되면 데이터를 뽑아낼 때 도움이 됩니다. 아래에 예제가 존재합니다!

record document 전체 조회

crul -XGET localhost:9200/basketball/record/_search?pretty

points가 30인 데이터만 출력

curl -XGET localhost:9200/basketball/record/_search?q=points:30&pretty

curl -XGET localhost:9200/basketball/record/_search -d '
{
	"query" : {
    	"term" : {"points" : 30}
    }
}'

5. 메트릭 어그리게이션

어그리게이션 : 엘라스틱 서치의 도큐먼트에서 값을 도출할 때 쓰이는 방법입니다. 그 중에서 메트릭 어그리게이션은 산수값을 구할 때 사용합니다.

simple_basketball.json

{"index" : { "_index" : "basketball", "_type" : "record", "_id" : "1"}}
{"team": "chicago bulls", "name": "micheal Jordan", "points": 30, "rebound": 3, "assists": 4, "submit_date": "1996-10-11"}
{"index" : { "_index" : "basketball", "_type" : "record", "_id" : "2"}}
{"team": "chicago bulls", "name": "micheal Jordan", "points": 20, "rebound": 5, "assists": 8, "submit_date": "1996-10-10"}

해당 데이터를 먼저 elasticsearch에 넣도록 하겠습니다.

curl -XPOST localhost:9200/_bulk --data-binary @simple_basketball.json -H "Content-Type: application/json"

avg_points_aggs.json

{
        "size": 0,
        "aggs": {
                "avg_score": {
                        "avg": {
                                "field": "points"
                        }
                }
        }
}

간단한 어그리게이션 파일을 작성했습니다.
size: 0 -> 결과값에 원하는 값만 보겠다.
aggs -> 어그리게이션 파일이다.
avg_score -> 어그리게이션 이름
avg -> 평균값을 구하겠다.
field -> points의 평균값을 구하겠다.

어그리게이션 파일 실행

curl -XGET localhost:9200/_search?pretty --data-binary @avg_points.json -H "Content-Type: application/json"

결과가 잘 나오는 것을 확인할 수 있습니다.

{
  "took" : 100,
  "timed_out" : false,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "avg_score" : {
      "value" : 25.0
    }
  }
}

max_points.json

{
        "size": 0,
        "aggs": {
                "max_score" : {
                        "max" : {
                                "field" : "points"
                        }
                }
        }
}

어그리게이션 파일 실행

curl -XGET localhost:9200/_search?pretty --data-binary @max_points.json -H "Content-Type: application/json"

결과가 잘 나오는 것을 확인할 수 있습니다.

{
  "took" : 7,
  "timed_out" : false,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "max_score" : {
      "value" : 30.0
    }
  }
}

min, sum, stats도 가능합니다.
stats는 count, min, max, avg, sum을 한번에 보여줍니다.

stats_points.json

{
        "size": 0,
        "aggs": {
                "max_score" : {
                        "stats" : {
                                "field" : "points"
                        }
                }
        }
}

어그리게이션 파일 실행

curl -XGET localhost:9200/_search?pretty --data-binary @stats_points.json -H "Content-Type: application/json"

결과가 잘 나오는 것을 확인할 수 있습니다.

{
  "took" : 23,
  "timed_out" : false,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "max_score" : {
      "count" : 2,
      "min" : 20.0,
      "max" : 30.0,
      "avg" : 25.0,
      "sum" : 50.0
    }
  }
}

6. 버킷 어그리게이션

RDB에 GROUP BY라고 보면 됩니다.

1. 기존 인덱스 삭제

curl -XDELETE localhost:9200/basketball

2. 인덱스 추가

curl -XPUT localhost:9200/basketball?pretty

3. 매핑 추가

basketball_mapping.json

{
	"record" : {
    	"properties" : {
        	"team" : {
            	"type" : "text",
                "fielddata" : true
            },
            "name" : {
            	"type" : "text",
                "fielddata" : true
            },
        	"points" : {
            	"type" : "long"
            },
        	"rebounds" : {
            	"type" : "long"
            },            
        	"assists" : {
            	"type" : "long"
            },
        	"blocks" : {
            	"type" : "long"
            },
        	"submit_date" : {
            	"type" : "date",
                "format" : "yyyy-MM-dd"
            }               
        }
    }
}
curl -XPUT 'localhost:9200/basketball/record/_mapping?include_type_name=true&pretty' -d @basketball_mapping.json -H "Content-Type:application/json"

4. 도큐먼트 추가

twoteam_basketball.json

{"index" : { "_index" : "basketball", "_type" : "record", "_id" : "1"}}
{"team": "chicago", "name": "micheal Jordan", "points": 30, "rebound": 3, "assists": 4, "submit_date": "1996-10-11"}
{"index" : { "_index" : "basketball", "_type" : "record", "_id" : "2"}}
{"team": "chicago", "name": "micheal Jordan", "points": 20, "rebound": 5, "assists": 8, "submit_date": "1996-10-10"}
{"index" : { "_index" : "basketball", "_type" : "record", "_id" : "1"}}
{"team": "LA", "name": "kobe", "points": 30, "rebound": 3, "assists": 4, "submit_date": "1996-10-11"}
{"index" : { "_index" : "basketball", "_type" : "record", "_id" : "2"}}
{"team": "LA", "name": "kobe", "points": 40, "rebound": 5, "assists": 8, "submit_date": "1996-10-10"}

5. 데이터 추가

curl -XPOST localhost:9200/_bulk?pretty --data-binary @twoteam_basketball.json -H "Content-Type:application/json"

term_aggs.json

{
	"size" : 0,
    "aggs" : {
    	"players" : {
        	"terms" : {
            	"field" : "team"
            }
        }
    }
}

size : 0 -> 어그리게이션한 정보만 볼 수 있게
aggs -> 어그리게이션
players -> 어그리게이션 내용
terms -> terms 어그리게이션을 사용하겠다.
field : team -> 팀별로 묶겠다.

6. AGGS (group by team) 팀으로 묶어서 출력

curl -XGET localhost:9200/_search?pretty --data-binary @term_aggs.json -H 'Content-Type:application/json'

결과

결과가 잘 나온 것을 확인할 수 있습니다.

사실 이렇게 심플한 예제 보다는. 각 팀의 점수 통계 데이터를 뽑아내는 것을 많이 사용할 것 같습니다.

7. AGGS (stats group by team) 팀으로 묶어서 점수 톰계

각 팀에 대한 데이터를 보여주기 위한 예제입니다.
stats_by_team.json

{
	"size" : 0,
    "aggs" : {
    	"team_stats" : {
        	"terms" : {
            	"field" : "team"
            },
            "aggs" : {
            	"stats_score" : {
                	"stats" : {
                    	"field" : "points"
                    }
                }
            }
        }
    }
}

AGGS (group by team)

curl -XGET localhost:9200/_search?pretty --data-binary @stats_by_team.json -H 'Content-Type:application/json'

간단한 예제로 엘라스틱 서치를 찍먹해봤습니다. 다음 게시글에서는 키바나를 찍먹해보도록 하겠습니다.

어우 맛있따!🔥🔥🔥🔥

profile
부족함을 인정하고 노력하자

0개의 댓글