본문 바로가기
Elasticsearch

ES의 기본 API (CRUD)

by suychoi 2022. 3. 1.

index 조회

cluster에 존재하는 index 조회

curl -XGET 'localhost:9200/_cat/indices?v'

index 가 없는 경우
index가 있는 경우


index 추가

# curl -XPUT 'localhost:9200/customer?pretty'

customer라는 index를 추가합니다.

acknowledged : true 결과를 통해 작업이 성공적이라는 것을 알 수 있습니다. 

 

추가적으로 ?pretty 를 추가하면 결과를 정리된 상태로 볼 수 있습니다.


document 추가

문서를 색인화 하는 작업으로

어떤 type 인지, 

몇번 _id 에 색인화할것인지 명시해야 합니다. 

# curl -XPOST 'localhost:9200/customer3/info/1?pretty' -H 'Content-Type: application/json' -d '{
"name": "victolee"
}'

customer3 인덱스에서 info 타입의 id_는 1번에 색인화 하는 명령어 입니다. 

[ -d ] 옵션은 --data-binary의 약어이며, 추가할 데이터를 명시합니다. 

여기서 customer3 와 info 타입은 생성한 적이 없지만, 자동으로 생성하면서 색인화가 되었다는점이 중요합니다. 

 

또한 _id 값을 명시하지 않으면, 임의의 문자열을 할당합니다. 


json 형식으로 호출하기

추가하려는 필드가 여러가지인 경우, 명령어에 데이터를 모두 입력하기 번거롭습니다. 

이때, 데이터를 json 형식의 파일로 만들어서 API를 호출하는 방법을 사용합니다. 

 

위의 색인화 명령어에서 -d 옵션에 json형식의 [ @파일경로 ]를 작성하여 명령어를 실행합니다. 

# vi data.json

{
"name": "victory",
"address": "경기도",
"phone": "010-123-1234",
"reg_date": "2019-03-31"
}

# curl -XPOST 'localhost:9200/customer2/info/2?pretty' -H 'Content-Type: application/json' -d @data.json

 


document 조회

  • 인덱스 내에서 조회

customer2 인덱스의 모든 documnet를 조회하는 방법입니다. 

URL의 _search 는 query DSL을 위해 사용하는 API 이며, 원래는 뒤에 query를 명시해야 합니다. 

# curl -XGET 'localhost:9200/customer2/_search?pretty'
  • 모든 인덱스에서 조회
# curl -XGET 'localhost:9200/_all/_search?pretty'
  • _id 를 이용한 검색
curl -XGET 'localhost:9200/customer2/info/1?pretty'

 


filter_path 를 이용한 응답 결과 줄이기

# curl -XGET 'localhost:9200/customer2/info/2?pretty&filter_path=_source'

# curl -XGET 'localhost:9200/customer2/info/2?pretty&filter_path=_source.name'

 

다음과 같이 원하는 필터만 뽑아서 볼 수 있다. 


document 수정

# curl -XPUT 'localhost:9200/customer2/info/1?pretty' -H 'Content-Type: application/json' -d '{
"name": "victolee_update"
}'

추가작업과 유사하며 데이터를 update 한다.

추가적으로 _verion 정보도 함께 업데이트 된다. 


index 및 document 삭제

  • document 삭제
# curl -XDELETE 'localhost:9200/customer2/info/1?pretty'
  • index 삭제
# curl -XDELETE 'localhost:9200/customer2?pretty'

 


참고

링크1

'Elasticsearch' 카테고리의 다른 글

ES의 status  (0) 2022.02.25