'elasticsearch'에 해당되는 글 420건

  1. 2022.05.18 [Elastic] Elasticsearch, Kibana, Filebeat, Logstash 8.2.0 구성하기
  2. 2022.05.11 [Elasticsearch] 8.2.0 Docker Compose 예제.
  3. 2022.05.09 [Elastic] Enterprise Search 8.2 구성 해 보기
  4. 2022.03.28 [Elasticsearch] Plugin transport-netty4 MVN Repo Missing!!
  5. 2022.03.24 [Elasticsearch] Terms + Sub Sum Aggs 사례.
  6. 2022.03.23 [Elasticsearch] 8.0 살펴 봤던 거
  7. 2022.02.15 [Elasticsearch] Arirang classpath 미등록 시.
  8. 2022.01.28 [Elasticsearch] Exists Query...
  9. 2022.01.28 [Elasticsearch] Aggs - Cardinality, Derivative, Cumulative...
  10. 2021.12.30 [Elasticsearch] TotalHits.Relation 알아보기.

[Elastic] Elasticsearch, Kibana, Filebeat, Logstash 8.2.0 구성하기

Elastic 2022. 5. 18. 13:05

가볍게 Elastic Stack 8.2.0 을 기준으로 설치 및 구성 하는 방법을 기술 합니다.

xpack basic 버전 이지만 security 기능은 사용 하지 않습니다.

security 사용을 적용해 보고 싶으신 분은 아래 글을 참고해 보시면 될 것 같습니다.

 

참고 글)

[Elastic] Enterprise Search 8.2 구성 해 보기

 

[Elastic] Enterprise Search 8.2 구성 해 보기

Enterprise Search (App Search) 를 사용하기 위해서는 먼저 선행 되어야 하는 것들이 있습니다. https://www.elastic.co/guide/en/app-search/current/getting-started.html App Search 이외 Workspace Search 도..

jjeong.tistory.com

 

1. Elasticsearch Setup

$ vi config/elasticsearch.yml
# xpack basic security feature disable.
xpack.security.enabled: false
xpack.security.enrollment.enabled: false
xpack.security.http.ssl.enabled: false
xpack.security.transport.ssl.enabled: false
ingest.geoip.downloader.enabled: false

# JDK 17 ES_JAVA_HOME 설정
$ bin/elasticsearch

xpack.security 기능을 사용하지 않을 거라서 위와 같이 설정을 먼저 진행 합니다.

여기서 출가로 geoip 도 disabled 했습니다. 이유는 보안상 이유로 다운로드가 막혀 있는 경우 에러가 나는데 이게 보기 싫으신 분들은 저렇게 끄고 사용 하시면 됩니다.

 

2. Kibana Setup

$ vi config/kibana.yml
xpack.security.audit.enabled: false

$ bin/kibana

kibana 는 간단 합니다.

어차피 로컬 개발 장비에서 모두 설치 하는 거라 기본 연결 설정 정보는 모두 localhost:9200, localhost:5601 이렇게 구성 됩니다.

 

3. Filebeat Setup

가장 많이 사용 했던 것이 input type log 였는데요.

이게 filestream 으로 개선되어 추가 되었습니다.

아래 문서 참고 하세요.

https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-input-filestream.html

# 기본 설정 예시

$ vi filebeat.yml
# 아래 설정에서 inode_marker 파일은 미리 생성이 되어 있어야 에러가 발생 하지 않습니다.
filebeat.inputs:
- type: filestream
  id: fb-filestream
  enabled: true
  paths:
    - $[PATH}/logs/*.log
  file_identity.inode_marker.path: $[PATH}/logs/.filebeat-marker
  
  encoding: utf-8

processors:
  - decode_json_fields:
      fields: [ "message" ]
      target: "json"

output.elasticsearch:
  hosts: ["localhost:9200"]

# 실행
$ ./filebeat -c filebeat.yml -e

 

4. Logstash Setup

filebeat 연동 시 filebeat.yml 의 output 에 logstash 설정을 합니다.

# filebeat 설치 경로에 가서 수정 합니다.
$ vi filebeat.yml
output.logstash:
  hosts: ["localhost:5044"]

# 이제 logstash 와 filebeat 연동을 위한 설정을 합니다.
$ vi config/logstash-sample.conf
input {
  beats {
    port => 5044
  }
}

output {
  elasticsearch {
    hosts => ["http://localhost:9200"]
    index => "logstash-%{+YYYY.MM.dd}"
  }
}

# 이제 logtash 와 filebeat 를 실행 해서 정상적으로 색인이 되었는지 확인 합니다.
$ bin/logstash -f config/logstash-sample.conf

# pipeline.yml 을 사용하기 위해서는 아래 설정 후 실행 하면 됩니다.
# 기본 설정이기 때문에 한번은 해야 합니다.
$ vi config/logstash.yml
node.name: ${NODE-NAME}
path.data: ${PATH}/data/logstash
path.logs: ${PATH}/logs/logstash
config.reload.automatic: true
config.reload.interval: 60s
http.port: 9600

$ vi config/pipeline.yml
- pipeline.id: filebeat-log-pipeline
  pipeline.workers: 4
  pipeline.batch.size: 20
  path.config: "${PATH}/config/logstash-sample.conf"

# 이제 실행 합니다.
$ bin/logstash

자, 여기까지 Elastic Stack 8.2.0 구성 맛보기 였습니다.

:

[Elasticsearch] 8.2.0 Docker Compose 예제.

Elastic/Elasticsearch 2022. 5. 11. 16:42

Elasticsearch 7.x 와 다르게 8.x 에서는 기본 xpack.security.enabled: true 로 실행이 됩니다.

그래서 docker container 구성 시 보안 기능을 사용 하지 않고 예전 처럼 7.x 에서 사용 하듯이 사용 하고자 한다면 아래 예제를 참고해서 사용 하시기 바랍니다.

version: '3.7'
services:
  es-singlenode:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.2.0
    container_name: es-singlenode
    environment:
      - xpack.security.enabled=false
      - node.name=single-node
      - cluster.name=es-singlenode-c
      - discovery.type=single-node
    ports:
      - 9200:9200
      - 9300:9300
    networks:
      - es-bridge
networks:
  es-bridge:
    driver: bridge

저 같은 경우 xpack basic 을 사용 하기는 하지만 보안 기능을 사용 하지는 않습니다.

모두 private subnet 에서 구성해서 사용중이기도 하고 별도 ACL 통제를 통해서 접근 제어도 이루어 지고 있어서 인데요.

판단은 각자가 알아서 하셔야 할 것 같습니다.

 

:

[Elastic] Enterprise Search 8.2 구성 해 보기

Elastic 2022. 5. 9. 13:56

Enterprise Search (App Search) 를 사용하기 위해서는 먼저 선행 되어야 하는 것들이 있습니다.

https://www.elastic.co/guide/en/app-search/current/getting-started.html

 

App Search 이외 Workspace Search 도 있습니다.

여기서는 App Search 만 다뤘습니다.

 

1. Elasticsearch 가 설치 되어 있어야 합니다.

Enterprise Search 는 Elasticsearch 를 포함 하고 있지 않습니다.

구성 되어 있는 Elasticsearch Cluster 에 연결 해서 Enterprise Search 를 사용 할 수 있도록 해줍니다.

 

2. Kibana 가 설치 되어 있어야 합니다.

Kibana 가 필요한 이유는 Enterprise Search 의 Web UI 가 Kibana 로 통합 되었기 때문 입니다.

 

3. Enterprise Search 가 설치 되어 있어야 합니다.

Enterprise Search 를 사용하기 위해 필요 하며, Elasticsearch 는 JDK 17 을 요구 하지만, Enterprise Search JDK 11 을 요구 합니다.

사용 하는 JDK 버전을 꼭 확인 하셔야 합니다.

 

 

Elasticsearch 8.2 설치 및 실행)

기본 tar ball 을 다운로드 받고 압축을 해제 한 후 바로 실행 합니다.

전에도 설명 했지만 8.x 부터는 기본 xpack security 기능이 enabled 입니다.

$ bin/elasticsearch
 Elasticsearch security features have been automatically configured!
✅ Authentication is enabled and cluster connections are encrypted.

ℹ️  Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
  0*LbX+orEfOCQx2GPRRy

ℹ️  HTTP CA certificate SHA-256 fingerprint:
  961aea7f1014ee94966ed79be09f3f550236389049d41b41c4dbe196e2bf7a22

ℹ️  Configure Kibana to use this cluster:
• Run Kibana and click the configuration link in the terminal when Kibana starts.
• Copy the following enrollment token and paste it into Kibana in your browser (valid for the next 30 minutes):
  eyJ2ZXIiOiI4LjIuMCIsImFkciI6WyIxOTIuMTY4LjAuNzo5MjAwIl0sImZnciI6Ijk2MWFlYTdmMTAxNGVlOTQ5NjZlZDc5YmUwOWYzZjU1MDIzNjM4OTA0OWQ0MWI0MWM0ZGJlMTk2ZTJiZjdhMjIiLCJrZXkiOiJpNWRvcG9BQkhoU20tOF9wY1FVYTpwdUZTMFMtM1J4aVZZUmoyaGJzajZnIn0=

ℹ️  Configure other nodes to join this cluster:
• On this node:
  ⁃ Create an enrollment token with `bin/elasticsearch-create-enrollment-token -s node`.
  ⁃ Uncomment the transport.host setting at the end of config/elasticsearch.yml.
  ⁃ Restart Elasticsearch.
• On other nodes:
  ⁃ Start Elasticsearch with `bin/elasticsearch --enrollment-token <token>`, using the enrollment token that you generated.


Kibana 8.2 설치 및 실행)

기본 tar ball 을 다운로드 받고 압축을 해제 한 후 바로 실행 합니다.

Security Enabled 이기 때문에 Kibana 실행 시 Elasticsearch 에서 생성해 준 코드를 입력해서 연결 합니다.

등록 후 ID, PWD 를 입력 하고 로그인 합니다.

$ bin/kibana
i Kibana has not been configured.

Go to http://localhost:5601/?code=917177 to get started.

# elasticsearch 실행 하면서 생성된 코드를 등록 하고 kibana 구성을 완료 합니다.
# id/pwd 를 입력 하고 로그인 합니다. (역시 elasticsearch 실행 시 생성된 코드를 입력 합니다.)

 

Enterprise Search 8.2 설치 및 실행)

기본 tar ball 을 다운로드 받고 압축을 해제 한 후 바로 실행 합니다.

Enterprise Search 의 경우 필요한 정보는 Elasticsearch 와 Kibana 정보 입니다.

Elasticsearch 의 경우 SSL 연동을 위한 정보도 함께 등록 합니다.

$ bin/enterprise-search
# java 11 버전을 요구 하기 때문에 맞춰서 실행 합니다.

--------------------------------------------------------------------------------

Invalid config file (/Users/henry/Workspace/apps/es8.2.0/enterprise-search-8.2.0/config/enterprise-search.yml):
The setting '#/secret_management/encryption_keys' is not valid
No secret management encryption keys were provided.
Your secrets cannot be stored unencrypted.
You can use the following generated encryption key in your config file to store new encrypted secrets:
todd
secret_management.encryption_keys: [37697db0e75459e7c5e55e6c492c36fde2dc31dcc7b9db9fcc44c702d0a3b9f5]


--------------------------------------------------------------------------------

$ vi config/enterprise-search.yml
secret_management.encryption_keys: [37697db0e75459e7c5e55e6c492c36fde2dc31dcc7b9db9fcc44c702d0a3b9f5]
allow_es_settings_modification: true
elasticsearch.username: elastic
elasticsearch.password: 0*LbX+orEfOCQx2GPRRy
elasticsearch.host: https://127.0.0.1:9200
elasticsearch.ssl.enabled: true
elasticsearch.ssl.certificate_authority: /Users/henry/Workspace/apps/es8.2.0/elasticsearch-8.2.0/config/certs/http_ca.crt
kibana.external_url: http://localhost:5601


# enterprise-search 연동을 위해 kibana 설정을 합니다.
$ vi config/kibana.yml
enterpriseSearch.host: http://localhost:3002


$ bin/enterprise-search
#########################################################

Success! Elastic Enterprise Search is starting successfully.

Advanced tooling and management interfaces are available via Kibana. Learn more about configuring and running
Kibana with Enterprise Search at https://www.elastic.co/guide/en/enterprise-search/master/user-interfaces.html.

In a few moments, you'll be able to access Enterprise Search from Kibana at the following address:

  * Kibana URL: http://localhost:5601/app/enterprise_search/overview

If this is your first time starting Enterprise Search, check the console output above for your user authentication credentials.

Visit the documentation: https://www.elastic.co/guide/en/enterprise-search/master/index.html


WARNING: A new secret session key has been generated.

Set the key in your config file to persist user sessions through process restarts:

secret_session_key: 5c6b7e6034c36ab0753033889e977624e362990f210adac99348e0e94aefb9b758ef8799d8d111b7d7c5c11383a254a50ca5322ed916ce185b2141617aa5924e


#########################################################


Kibana 에 접속해서 Enterprise Search 를 사용해 봅니다.)

# kibana 에 접속 해서 enterprise search 에서 app search 를 생성 합니다.
# app search 에서 engine 생성을 한 후 json 파일을 등록 합니다.
# [ {...}, {...} ] 형태의 개별 문서가 등록이 되어 있어야 하며, bulk request json 과 형식이 다릅니다.
# 문서 등록을 했으면 생성한 엔진으로 접근해서 검색을 실행해 봅니다.
# Relevance Tuning 이나 Search UI 에서 실행 합니다. 또는 Postman 에서 실행 하고자 할 때는
https://www.elastic.co/guide/en/app-search/8.2/search-guide.html
각각의 인증키는 Credentials 에 들어 가면, private-key 와 search-key 가 존재 합니다.

# Endpoint rule
http://localhost:3002/api/as/v1/engines/${ENGINE-NAME}/query_suggestion
http://localhost:3002/api/as/v1/engines/${ENGINE-NAME}/search.json

# Suggestion
curl --location --request POST 'http://localhost:3002/api/as/v1/engines/disney-poc/query_suggestion' \
--header 'Authorization: Bearer search-dupjgg5jdgafcj4cqoykq39k' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"서울"}'

# Search
curl --location --request POST 'http://localhost:3002/api/as/v1/engines/disney-poc/search.json' \
--header 'Authorization: Bearer search-dupjgg5jdgafcj4cqoykq39k' \
--header 'Content-Type: application/json' \
--data-raw '{
    "query":"서울"
}'

# enterprise search 에서 제공 하는 query 에는 QueryDSL 을 사용 할 수 없습니다.
https://www.elastic.co/guide/en/app-search/8.2/search.html#search-api-request-body

# enterprise search 에서 제공 하는 synonyms 기능은 질의 시점에 적용 되는 기능입니다.
https://www.elastic.co/guide/en/app-search/8.2/synonyms.html
Kibana UI 에서 등록 시 처음에 등록 하는 동의어가 원본 동의어가 되며, 이후 등록 하는 value 들이 원본 동의어와 같이 처리가 되어야 하는 동의어가 됩니다.

통신 방법에 따라 사용 유형을 정리해 보면,

Case 1)

Elasticsearch Cluster <--> Enterprise Search <--> Kibana

 

Case 2)

Elasticsearch Cluster <--> Enterprise Search <--> External Search API

 

Vertical Search Engine 으로도 사용이 가능 합니다.

Elasticsearch Cluster <--> Enterprise Search (각 서비스 또는 도메인 별 Enigne 생성) <--> External Search API (Engine 별 Endpoint)

 

단일 클러스터 운영을 하고 여러 Collection(Index) 을 사용하고자 할 때 유용하게 사용 가능해 보입니다.

:

[Elasticsearch] Plugin transport-netty4 MVN Repo Missing!!

Elastic/Elasticsearch 2022. 3. 28. 16:04

elasticsearch 8.x 에서 plugin 개발 시 주의 사항!!

기본적으로 plugin 을 만들기 위한 몇몇 dependency lib 들이 maven repository 에 등록이 안된 것 같습니다.
플로그인 빌드 시 아래와 같은 에러가 발생 하는 경우 꼭 관련 lib 들이 등록 되어 있는지 확인 하고 사용하시기 바랍니다.

 

빌드 시 에러 메시지)

Could not find artifact org.elasticsearch.plugin:transport-netty4:jar:8.0.0 in central
(https://repo.maven.apache.org/maven2)

 

org.elasticsearch.plugin:transport-netty4:jar 는 8.1.1 부터 등록이 되어 있습니다.
그래서 빌드 하실 때 8.0.0 이나 8.1.0 은 빌드 실패를 하게 되는데요.

꼭 확인을 해보셔야 합니다.

 

Maven Repository)
https://mvnrepository.com/artifact/org.elasticsearch.plugin
https://mvnrepository.com/artifact/org.elasticsearch.plugin/transport-netty4

 

:

[Elasticsearch] Terms + Sub Sum Aggs 사례.

Elastic/Elasticsearch 2022. 3. 24. 18:13

문제)

하루 동안 데이터 요청을 가장 많이한 IP Top 5 를 구하시오.

 

해결)

GET /kibana_sample_data_logs/_search
{
  "size":0,
  "aggs": {
    "ip_aggs": {
      "terms": {
        "field": "ip"
      },
      "aggs": {
        "sum_aggs": {
          "sum": {
            "field": "bytes"
          }
        },
        "sum_aggs_sort": {
          "bucket_sort": {
            "sort": [
              { "sum_aggs": { "order": "desc" } } 
            ],
            "size": 5
          }
        }
      }
    }
  }
}

 

관련 문서)

https://www.elastic.co/guide/en/elasticsearch/reference/8.1/search-aggregations-bucket-terms-aggregation.html

https://www.elastic.co/guide/en/elasticsearch/reference/8.1/search-aggregations-pipeline-bucket-sort-aggregation.html

 

Elasticsearch 를 설치 하고 Kibana 를 이용해서 Sample Data 를 이용하였습니다.

그냥 Single node 로 구성 해서 테스트 해보실 수 있습니다.

:

[Elasticsearch] 8.0 살펴 봤던 거

Elastic/Elasticsearch 2022. 3. 23. 10:04

시간이 없어서 전체적으로 다 살펴 보지는 못했네요.

우선 확인 한것만 그냥 올려 놓습니다.

 

Elasticsearch 8.0 

- path.data 다중 설정이 deprecated.
7.13.0 부터 deprecated 되었으나 아직까지는 기능을 제공 하고 있음.
디스크를 추가 하기 보다 data node 를 늘리는 것을 추천함.
단일 경로 설정 사용을 권장함.

- system index 에 접근 제어.
allow_restricted_indices: true 로 하면 접근 가능함.

- 8.0 실행 시 jdk 17 을 요구함.
warning: ignoring JAVA_HOME=/Users/henry/.jenv/versions/11.0; using ES_JAVA_HOME
The minimum required Java version is 17; your Java version from [/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home] does not meet this requirement

https://adoptium.net/ 에서 다운로드 받아 설치 합니다. (pkg)

/Library/Java/JavaVirtualMachines/temurin-17.jdk
$ jenv add /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home
$ ES_JAVA_HOME='/Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home' bin/elasticsearch

- 8.0 부터는 보안이 기본 적용 됩니다.
관련 security 기능을 사용하고 싶지 않을 경우 xpack.security.enable: false 로 설정 하면 됩니다.


✅ Elasticsearch security features have been automatically configured!
✅ Authentication is enabled and cluster connections are encrypted.

ℹ️  Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
  5mZOrRjTURT=V90LqU5N

ℹ️  HTTP CA certificate SHA-256 fingerprint:
  24d263ef19a4e66de19ab35dbd8a0cbf4ca303598123d3ee6acbb96852e25421

ℹ️  Configure Kibana to use this cluster:
• Run Kibana and click the configuration link in the terminal when Kibana starts.
• Copy the following enrollment token and paste it into Kibana in your browser (valid for the next 30 minutes):
  eyJ2ZXIiOiI4LjAuMCIsImFkciI6WyIxOTIuMTY4LjAuMTA0OjkyMDAiXSwiZmdyIjoiMjRkMjYzZWYxOWE0ZTY2ZGUxOWFiMzVkYmQ4YTBjYmY0Y2EzMDM1OTgxMjNkM2VlNmFjYmI5Njg1MmUyNTQyMSIsImtleSI6Imd0R2g1bjRCc3hnWEYtbV92bU43OnlwVDhOaXNaU2ZXejRhdEhTaExfS0EifQ==

ℹ️  Configure other nodes to join this cluster:
• On this node:
  ⁃ Create an enrollment token with `bin/elasticsearch-create-enrollment-token -s node`.
  ⁃ Uncomment the transport.host setting at the end of config/elasticsearch.yml.
  ⁃ Restart Elasticsearch.
• On other nodes:
  ⁃ Start Elasticsearch with `bin/elasticsearch --enrollment-token <token>`, using the enrollment token that you generated.


- elasticsearch.yml 내부에 환경 변수 설정이 가능 합니다.
node.name:    ${HOSTNAME}
network.host: ${ES_NETWORK_HOST}

export HOSTNAME="host1,host2"

- transient 설정을 더 이상 추천 하지 않습니다.
영구 설정을 사용 하세요.

- data directory 에 대한 어떠한 조작, 수정도 하지 마십시오.


- lucene-analyzers-common 이 lucene 9.0.0 으로 넘어 가면서 lucene-analysis-common 으로 변경 되었습니다.
import org.apache.lucene.analysis.util.TokenizerFactory;
to
import org.apache.lucene.analysis.TokenizerFactory;
로 변경 되었습니다.

import org.apache.lucene.analysis.standard.ClassicFilter;
to
import org.apache.lucene.analysis.classic.ClassicFilter;
로 변경 되었습니다.

- node 단독 실행 시 아래 설정이 꼭 되어야 합니다.
discovery.type: single-node
or
cluster.initial_master_nodes, discovery.seed_hosts, discovery.seed_providers 중 하나는 꼭 설정 되어야 합니다.

- mapping 파라미터 중 boost 파라미터가 삭제 되었습니다.
.The `boost` parameter on field mappings has been deprecated
.The `boost` parameter on field mappings has been removed

- jdk 변경 된 점
Remove support for JAVA_HOME
Require Java 17 for running Elasticsearch

- exist action some removed.
Remove aliases exist action
Remove indices exists action
Remove types exists action

- Enable LZ4 transport compression by default

:

[Elasticsearch] Arirang classpath 미등록 시.

Elastic/Elasticsearch 2022. 2. 15. 10:11

arirang plugin 을 사용 하면서 사전 데이터에 대한 classpath 설정은 했는데 config/dictionary path 생성을 하지 않았을 경우 reload api 가 동작 하지 않는다고 합니다.

 

이럴 경우 config/dictionary path 생성 하고 사전 데이터 배포 후 node 를 재시작 해주셔야 하는 번거로움이 있으니 초기 설치 시 꼭 사전 데이터에 대한 배포 후 실행을 해주시면 좋을 것 같습니다.

 

혹시 같은 실수 반복 할 수도 있어서 기록합니다.

:

[Elasticsearch] Exists Query...

Elastic/Elasticsearch 2022. 1. 28. 11:44

공식 문서)

Exists query | Elasticsearch Guide [7.16] | Elastic

 

exists query 는 field 자체가 아래 이유등으로 인해 생성 되자 않는 문서를 찾습니다.

즉, 

- null 또는 empty array (빈문자열 "" 은 해당 되지 않습니다.)

- index: false

- ignore_above 설정 값을 넘었을 때

- ignore_malformed 설정에 걸렸을 때

 

검색 엔진 특성상 null, empty string 에 대해서는 전처리를 통해서 명확히 제거 하거나 목적에 맞게 변형 하는 것이 좋습니다.

 

검색엔진을 이용해서 field:"" 또는 field: " " 과 같은 질의를 작성 하는 것은 좋지 않습니다.

 

:

[Elasticsearch] Aggs - Cardinality, Derivative, Cumulative...

Elastic/Elasticsearch 2022. 1. 28. 11:37

공식 문서)

Cardinality aggregation | Elasticsearch Guide [7.16] | Elastic

Derivative aggregation | Elasticsearch Guide [7.16] | Elastic

Cumulative cardinality aggregation | Elasticsearch Guide [7.16] | Elastic

 

현재 값과 직전 값에 대한 차이를 구합니다.

공식 문서에 자세한 내용들이 나와 있으니 보시면 좋습니다.

 

제가 사용 했던 예제는 공식 문서에 있는 거 활용 했습니다.

 

DAU 를 cardinality aggs 로 구하고 

Daily DAU 에 대한 누적 카운트를 cumulative_cardinality aggs 로 구하고 (여기서 buckets_path 는 cardinality aggs) 

Daily DAU 에 대한 변화를 derivative aggs 로 구했습니다. (여기서 buckets_path 는 cumulative_cardinality aggs)

 

아래는 공식 문서 예제 올려 둔 내용입니다.

GET /user_hits/_search
{
  "size": 0,
  "aggs": {
    "users_per_day": {
      "date_histogram": {
        "field": "timestamp",
        "calendar_interval": "day"
      },
      "aggs": {
        "distinct_users": {
          "cardinality": {
            "field": "user_id"
          }
        },
        "total_new_users": {
          "cumulative_cardinality": {
            "buckets_path": "distinct_users" 
          }
        }
      }
    }
  }
}

 

:

[Elasticsearch] TotalHits.Relation 알아보기.

Elastic/Elasticsearch 2021. 12. 30. 16:45

Elasticsearch 에서 질의 후 매칭된 문서의 수를 알아 내는 방법은 두 가지가 있습니다.

 

1. track_total_hits

2. _count API

 

여기서 WAS 의 에러로그 발생에 대한 알람을 구성 할 경우 어떤걸 사용 하면 좋을까요?

 

1. track_total_hits

false

true

numeric

이와 같이 값을 설정 할 수 있는데요.

false 이면 total hits 값을 구할 수 없습니다.

true 이면 total hits 값을 구할 수 있습니다.

특정 값을 넣게 되면 그 값 보다 작거나, 같은 값을 구할 수 있으며, relation 을 통해서 실제 매칭 문서의 규모를 파악 할 수 있습니다.

 

2. _count API

기본적으로 non-scoring API 이며, 어떤 데이터도 요청 하지 않기 때문에 빠릅니다.

 

Lucene Core 에 TotalHits.Relation 이 들어 있습니다.

  public enum Relation {
    /**
     * The total hit count is equal to {@link TotalHits#value}.
     */
    EQUAL_TO,
    /**
     * The total hit count is greater than or equal to {@link TotalHits#value}.
     */
    GREATER_THAN_OR_EQUAL_TO
  }

보시는 것 처럼 eq 아니면 gte 가 리턴 됩니다.

그래서 특정 수치 이상을 점검 하기 위해서는 relation:gte 로 조건을 잡으셔야 합니다.

 

그냥 위에서 처럼 1,2 번을 놓고 보면 _count API 를 사용하는게 일반적입니다.

그러나 대상 문서의 규모가 넓고 많을 경우 track_total_hits 에 특정 임계 값을 넣어서 질의 하는게 더 빠를 수 있습니다.

 

: