ElasticSearch 기본 CRUD
Posted by Albert 625Day 22Hour 20Min 24Sec ago [2023-08-03]
Elasticsearch 기본 사용법
ElasticSearch 의 문법은 간단히 RDB와 아래의 내용처럼 사용된다.
curl -XPOST http://172.30.1.105:9200/users/class/1/_update?pretty -H'Content-Type: application/json' -d '
{"doc":{"unit":1}}'
빨간색으로 칠한 부분 순서대로 1,2,3,4 라고 보면
1. XPOST 부분은 Rest Api 메소드이다 새로운 문서를 입력할 때는 PUT, 기존 문서를 수정 할 때는 POST, 삭제할때는 Delete, 조회시는 GET
Elastic Search | Relational DB | CRUD |
GET | Select | Read |
PUT | Update | Update |
POST | Insert | Create |
DELETE | Delete | Delete |
2. 문서를 색인한 인덱스 이름으로서 문서를 저장하는 가장 큰 논리적인 단위를 의미한다. RDB에서 데이터베이스 라고 생각하면 될것같다
3.문서의 타입 이름이다. ElasticSearch 5 버전 이하에서는 멀티 타입을 지원해서 하나의 인덱스 안에 다양한 타입 데이터를 저장할 수 있었지만 이후부터는 하나의 인덱스상 하나의 타입만 저장 하도록 변경되었다
4. 문서의 ID이다. 인덱스내에 유일해야 하며 같은 id가 입력되면 해당 문서가 수정된다고 생각하면 된다.
간단 사용법
[kafka@localhost ~]$ curl -XGET http://172.30.1.105:9200/bb/aa/1?pretty
{
"_index" : "bb",
"_type" : "aa",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"title" : "aabb2",
"ctt" : "contents2"
}
}
[kafka@localhost ~]$ curl -XPUT http://172.30.1.105:9200/idx2?pretty
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "idx2"
}
[kafka@localhost ~]$ curl -XPOST http://172.30.1.105:9200/bb/aa/3?pretty -H'Content-Type: application/json' -d '
{"title":"aabb2","ctt":"contents2"}'
{
"_index" : "bb",
"_type" : "aa",
"_id" : "3",
"_version" : 2,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1
}
[kafka@localhost ~]$ curl -XDELETE http://172.30.1.105:9200/idx2?pretty
{
"acknowledged" : true
}
대용량 json 파일(class.json)을 직접 넣어줄때
[kafka@localhost elastic]$ curl -XPOST http://172.30.1.105:9200/_bulk?pretty -H'Content-Type: application/json' --data-binary @class.json
등록된 값 update
[kafka@localhost elastic]$ curl -XPOST http://172.30.1.105:9200/classes/class/1/_update?pretty -H'Content-Type: application/json' -d '
{"doc":{"unit":1}}'
{
"_index" : "classes",
"_type" : "class",
"_id" : "1",
"_version" : 7,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 31,
"_primary_term" : 1
}
script 를 통하여 항목 변경
[kafka@localhost elastic]$ curl -XPOST http://172.30.1.105:9200/classes/class/1/_update?pretty -H'Content-Type: application/json' -d '
{"script":"ctx._source.unit+=3"}'
{
"_index" : "classes",
"_type" : "class",
"_id" : "1",
"_version" : 8,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 32,
"_primary_term" : 1
}