본문 바로가기
DB/Elastic Search

elasticsearch에 데이터 INSERT, UPDATE 해보기 (POST, GET)

by JiGyeong 2018. 11. 22.



1. 완전 처음 데이터 넣기!



나는 /usr/share/elasticsearch 에 설치되어있으므로 /usr/share/elasticsearch path밑에서 명령어를 날려보겠다.


# curl -H 'Content-Type: application/json' -XPOST localhost:9200/classes/class/1/ -d '{"title":"math", "professor":"Jenifer"}'


-H ~ : 헤드타입

classes : 데이터 인덱스

class : 데이터 타입

1 : 1번째 데이터


-d : document


 curl -H 'Content-Type: application/json' -XPOST localhost:9200/classes/class/1/ -d '{"title":"math", "professor":"Jenifer"}'


이렇게 치고나면


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


이렇게 데이터가 들어갔음을 알 수 있다.







2. 데이터 조회해보기 !


# curl -XGET localhost:9200/classes/class/1?pretty



이렇게 데이터가 들어갔음을 확인할 수 있다.


여기서 pretty는 json 데이터 정렬 기능이다. 깔끔하게 나오도록 도와주는 역할!


만약 pretty를 없애게 된다면?



이렇게 데이터가 길게 떨어진다.





3. Json 으로 데이터 넣기 !


# curl -H 'Content-Type: application/json' -XPOST localhost:9200/classes/class/2/ -d @harrypotter.json



먼저 json 파일을 만든다.


vi harrypother.json



curl -H 'Content-Type: application/json' -XPOST localhost:9200/classes/class/2/ -d @harrypotter.json


위 명령어로 2번째 데이터를 json으로 넣어준다.


그러면 로그가 이렇게 남는다.

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



데이터가 잘 들어갔는지 확인해보자


curl -XGET localhost:9200/classes/class/2?pretty




잘 들어간 것 같다.





4. update를 해보자!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[root@localhost elasticsearch]# curl -H 'Content-Type: application/json' -XPOST http://localhost:9200/classes/class/1/_update?pretty -d '{"doc":{"unit":1}}'
{
  "_index" : "classes",
  "_type" : "class",
  "_id" : "1",
  "_version" : 2,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 1,
  "_primary_term" : 1
}
[root@localhost elasticsearch]# curl -H 'Content-Type: application/json' -XPOST http://localhost:9200/classes/class/1/_update?pretty -d '{"doc":{"test":"test1"}}'
{
  "_index" : "classes",
  "_type" : "class",
  "_id" : "1",
  "_version" : 3,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 2,
  "_primary_term" : 1
}
[root@localhost elasticsearch]#  curl -XGET http://localhost:9200/classes/class/1?pretty
{
  "_index" : "classes",
  "_type" : "class",
  "_id" : "1",
  "_version" : 3,
  "found" : true,
  "_source" : {
    "title" : "math",
    "professor" : "Jenifer",
    "unit" : 1,
    "test" : "test1"
  }
}
cs