mingming

ElasticSearch - REST API 본문

ELK

ElasticSearch - REST API

mingming_96 2023. 12. 9. 17:58

REST API 

Elasticsearch는 RESTful API를 사용하여 상호작용할 수 있습니다. 자원별로 고유 URL로 접근이 가능하며 HTTP 메서드(PUT, POST, GET, DELETE) 를 이용해 자원을 처리할 수 있습니다. 

HTTP 메서드

  • GET : 리소스를 요청하는데 사용됩니다. 주로 데이터를 가져올 때 사용합니다. 
  • POST : 서버에 새로운 리소스를 생성하는데 사용됩니다. 
  • PUT : 특정 리소스를 업데이트하거나 생성하는데 사용됩니다. 
  • DELETE : 특정 리소스를 삭제하는데 사용됩니다. 

Elaticsearch 유용한 경로

Status & Stats 

  • / : cluster 정보 
  • /_cluster/health : 클러스터의 상태를 확인하는데 사용되는 경로 입니다. 
  • /_nodes/status : node 레벨의 상태정보를 확인하는 경로입니다.

Settings

  • /_cluster/settings : 클러스터의 설정 정보를 확인할 수 있는 경로입니다. 
  • /<indenx_name>/settings : 인덱스의 설정 정보를 확인할 수 있는 경로입니다.

cat api 

  • /_cat/indices/<index_name> : 인덱스에 대한 정보를 보여줍니다. 
  • /_cat/nodes : 클러스터의 노드 목록과 각 노드의 상태를 제공합니다. 
  • /_cat/shards : 샤드에 대한 정보를 제공합니다.
  • /_cat_allocation : 각 노드에서 샤드의 할당 정보를 제공합니다. 

Document

/<Index_name>/_doc/<doc_id> : index의 도큐먼트를 조회하는 경로입니다.

 

GET method ( 조회 ) 

elastcisearch 클러스터 조회 

curl -XGET "https://10.44.0.6:9200" --cacert ca.crt -k -u elastic
CUD6S9qiBBY02kvQ
{
  "name" : "elasticsearch-master-0",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "uAEPMB30TbSo9ALpgV5Dhw",
  "version" : {
    "number" : "8.5.1",
    "build_flavor" : "default",
    "build_type" : "docker",
    "build_hash" : "c1310c45fc534583afe2c1c03046491efba2bba2",
    "build_date" : "2022-11-09T21:02:20.169855900Z",
    "build_snapshot" : false,
    "lucene_version" : "9.4.1",
    "minimum_wire_compatibility_version" : "7.17.0",
    "minimum_index_compatibility_version" : "7.0.0"
  },
  "tagline" : "You Know, for Search"
}

 

elastcisearch 클러스터 상태 조회 

curl -XGET "https://10.44.0.1:9200/_cluster/health" --cacert ca.crt -k -u elastic


{
  "cluster_name": "elasticsearch",
  "status": "yellow",
  "timed_out": false,
  "number_of_nodes": 1,
  "number_of_data_nodes": 1,
  "active_primary_shards": 3,
  "active_shards": 3,
  "relocating_shards": 0,
  "initializing_shards": 0,
  "unassigned_shards": 1,
  "delayed_unassigned_shards": 0,
  "number_of_pending_tasks": 0,
  "number_of_in_flight_fetch": 0,
  "task_max_waiting_in_queue_millis": 0,
  "active_shards_percent_as_number": 75.0
}

 

인덱스 확인 

curl -XGET "https://10.44.0.3:9200/_cat/indices?v" --cacert ca.crt -k -u elastic

health status index                                      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   .ds-logs-generic-default-2023.12.06-000001 cbqFZy_qTGuMECq_FkKR5w   1   1         41            0     12.8kb         12.8kb
  • health: 인덱스의 상태를 나타냅니다. "yellow"는 일부 리플리카가 할당되지 않았음을 나타냅니다. 다른 상태로는 "green" (모든 샤드가 할당된 상태)과 "red" (모든 샤드가 할당되지 않은 상태)가 있습니다.
  • status: 인덱스의 상태를 나타냅니다. "open"은 인덱스가 열려 있음을 나타냅니다.
  • index: 각 인덱스의 이름입니다.
  • uuid: 각 인덱스의 고유 식별자입니다.
  • pri: 프라이머리 샤드의 수입니다.
  • rep: 리플리카 샤드의 수입니다.
  • docs.count: 인덱스에 저장된 문서의 총 개수입니다.
  • docs.deleted: 삭제된 문서의 수입니다.
  • store.size: 디스크에 저장된 총 용량입니다.
  • pri.store.size: 프라이머리 샤드의 디스크 저장 크기입니다.

 

인덱스 설정 정보 확인

 curl -XGET "https://10.44.0.3:9200/.ds-logs-generic-default-2023.12.06-000001" --cacert ca.crt -k -u elastic

{
    ".ds-logs-generic-default-2023.12.06-000001": {
        "aliases": {},
        "mappings": {
            "_data_stream_timestamp": { "enabled": true },
            "dynamic_templates": [
                {
                    "match_ip": {
                        "match": "ip",
                        "match_mapping_type": "string",
                        "mapping": { "type": "ip" }
                    }
                },
                {
                    "match_message": {
                        "match": "message",
                        "match_mapping_type": "string",
                        "mapping": { "type": "match_only_text" }
                    }
                },
                {
                    "strings_as_keyword": {
                        "match_mapping_type": "string",
                        "mapping": {
                            "ignore_above": 1024,
                            "type": "keyword"
                        }
                    }
                }
            ],
            "date_detection": false,
            "properties": {
                "@timestamp": { "type": "date" },
                "@version": { "type": "keyword", "ignore_above": 1024 },
                "data_stream": {
                    "properties": {
                        "dataset": { "type": "constant_keyword", "value": "generic" },
                        "namespace": { "type": "constant_keyword", "value": "default" },
                        "type": { "type": "constant_keyword", "value": "logs" }
                    }
                },
                "ecs": {
                    "properties": { "version": { "type": "keyword", "ignore_above": 1024 } }
                },
                "event": {
                    "properties": { "original": { "type": "keyword", "ignore_above": 1024 } }
                },
                "host": {
                    "properties": { "name": { "type": "keyword", "ignore_above": 1024 } }
                },
                "message": { "type": "match_only_text" },
                "process": {
                    "properties": {
                        "command_line": { "type": "keyword", "ignore_above": 1024 },
                        "exit_code": { "type": "long" }
                    }
                }
            }
        },
        "settings": {
            "index": {
                "lifecycle": { "name": "logs" },
                "codec": "best_compression",
                "routing": {
                    "allocation": { "include": { "_tier_preference": "data_hot" } }
                },
                "hidden": "true",
                "number_of_shards": "1",
                "provided_name": ".ds-logs-generic-default-2023.12.06-000001",
                "query": { "default_field": ["message"] },
                "creation_date": "1701879202891",
                "number_of_replicas": "1",
                "uuid": "cbqFZy_qTGuMECq_FkKR5w",
                "version": { "created": "8050199" }
            }
        },
        "data_stream": "logs-generic-default"
    }
}

 

 

PUT method ( 입력 )

인덱스 생성

curl -X PUT "https://10.44.0.3:9200/my_new_index" --cacert ca.crt -k -u elastic -H 'Content-Type: application/json' -d'
{
  "settings": {            ### settings : Elasticseasrch의 인덱스 설정으로 샤드의 수 , 레플리카의 수 등을 설정합니다.
    "number_of_shards": 1,
    "number_of_replicas": 1
  }
}
'
curl -X PUT "https://10.44.0.3:9200/my_new_index/_mapping" --cacert ca.crt -k -u elastic -H 'Content-Type: application/json' -d'
{
  "properties": {  ### properites : 인덱스에 저장되는 데이터의 구조를 정의합니다. 
    "title": { "type": "text" },
    "description": { "type": "text" },
    "category": { "type": "keyword" },
    "timestamp": { "type": "date" }
  }
}
'

 

response

{
  "acknowledged": true,
  "shards_acknowledged": true,
  "index": "my_new_index"
}

{"acknowledged":true}

 

 

Document 생성

curl -X PUT "https://10.44.0.3:9200/my_new_index/_doc/1" --cacert ca.crt -k -u elastic -H 'Content-Type: application/json' -d'
{
  "title": "Sample Title",
  "description": "Sample Description",
  "category": "Sample Category",
  "timestamp": "2023-12-31T00:00:00"
}
'

 

response

{
  "_index": "my_new_index",
  "_id": "1",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 0,
  "_primary_term": 1
}

 

POST method ( 입력, 업데이트 )

post method는 업데이트 혹은 생성에 사용되는 메서드입니다. 생성할 떈 put 메서드와 동일하지만 <doc_id>를 지정하지 않아도 임의의 <doc_id>값을 지정해준다는 특징이 있습니다. update 시에는 _update 경로를 사용합니다.

 

document update

curl -X POST "https://10.44.0.3:9200/my_new_index/_update/1" --cacert ca.crt -k -u elastic -H 'Content-Type: application/json' -d'
{
  "doc": {
    "title": "Updated Title",
    "description": "Updated Description",
    "category": "Updated Category",
    "timestamp": "2023-12-31T00:00:00"
  }
}
'

 

reponse

update 시 version이 변경된 것을 확인할 수 있습니다.

{
  "_index": "my_new_index",
  "_id": "1",
  "_version": 2,  
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 1,
  "_primary_term": 1
}

 

document create

curl -X POST "https://10.44.0.3:9200/my_new_index/_doc/" --cacert ca.crt -k -u elastic -H 'Content-Type: application/json' -d'
{
  "doc": {
    "title": "second document",
    "description": "post create document",
    "category": "Updated Category",
    "timestamp": "2023-12-10T00:00:00"
  }
}
'

 

response

임의의 id 값이 생성된것을 확인할 수 있습니다.

{
  "_index": "my_new_index",
  "_id": "nLVMT4wB3gbygovoEm6s",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 2,
  "_primary_term": 1
}

 

DELETE method ( 삭제 )

Document 삭제

curl -X DELETE "https://10.44.0.3:9200/my_new_index/_doc/1" --cacert ca.crt -k -u elastic

 

response

{
  "_index": "my_new_index",
  "_id": "1",
  "_version": 3,
  "result": "deleted",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 3,
  "_primary_term": 1
}

 

'ELK' 카테고리의 다른 글

Apache Tomcat & ELK Stack  (1) 2024.02.08
ElaticSearch - cluster 설정 및 role  (1) 2023.12.09
ELK on Kubernetes - Kibana  (0) 2023.12.07
ELK on Kubernetes - Logstash  (4) 2023.12.07
ELK on Kubernetes - ElasticSearch  (2) 2023.12.06