[ES] 엘라스틱 서치 데이터 입력 조회 삭제

Posted by 김성철

Elasticsearch - 엘라스틱 서치 데이터 입력 조회 삭제(GET,POST,PUT,DELETE)

RDBMS 와 엘리스틱 서치의 맵핑

Database		: Index  
Table			: Type  
Row				: Document  
Column			: Field  
Schema			: Mapping  
  
SELECT			: GET  
INSERT			: POST  
UPDATE			: PUT  
DELETE			: DELETE  

index 목록 조회

http://localhost:9200/_cat/indices?v  
- health  
인덱스의 전반적인 상태를 나타냅니다.  
green: 모든 샤드가 정상적으로 작동하고 있음을 의미합니다.  
yellow: 일부 복제본 샤드가 작동하지 않고 있지만, 기본 샤드는 정상적으로 작동하고 있음을 의미합니다.  
red: 기본 샤드 중 일부가 작동하지 않고 있음을 의미합니다. 이 경우 데이터 손실의 위험이 있습니다.  
  
- status  
인덱스의 현재 상태를 나타냅니다.  
open: 인덱스가 정상적으로 작동하고 있음을 의미합니다.  
close: 인덱스가 닫혀있음을 의미합니다. 닫힌 인덱스는 검색이나 쓰기 작업을 수행할 수 없습니다.  
red: 인덱스에 문제가 있음을 의미합니다.  
  
- index  
인덱스의 이름을 나타냅니다.  
  
- uuid  
인덱스의 고유 식별자를 나타냅니다.  
  
- pri  
기본 샤드(primary shard)의 개수를 나타냅니다.  
  
- rep  
복제본 샤드(replica shard)의 개수를 나타냅니다.  
  
- docs.count  
인덱스에 저장된 문서의 총 개수를 나타냅니다.  
  
- docs.deleted  
인덱스에 삭제된 문서의 개수를 나타냅니다.  
  
- store.size  
인덱스가 사용하고 있는 디스크 공간의 크기를 나타냅니다.  
  
- pri.store.size  
기본 샤드(primary shard)가 사용하고 있는 디스크 공간의 크기를 나타냅니다.  

index 데이터 조회

https://{ES 주소}/{index 명}/_search  

index 조회

curl -XGET http://localhost:9200/classes  
=====================================================================  
{"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such index [classes]","resource.type":"index_or_alias","resource.id":"classes","index_uuid":"_na_","index":"classes"}],"type":"index_not_found_exception","reason":"no such index [classes]","resource.type":"index_or_alias","resource.id":"classes","index_uuid":"_na_","index":"classes"},"status":404}  
=====================================================================  
  
현재 데이터가 없기에 error가 발생  

index 조회 - 결과값 이쁘게 보기

조회시 뒤에 ?pretty 붙여서 전송  
curl -XGET http://localhost:9200/classes?pretty  
=====================================================================  
{  
  "error" : {  
	"root_cause" : [  
	  {  
		"type" : "index_not_found_exception",  
		"reason" : "no such index [classes]",  
		"resource.type" : "index_or_alias",  
		"resource.id" : "classes",  
		"index_uuid" : "_na_",  
		"index" : "classes"  
	  }  
	],  
	"type" : "index_not_found_exception",  
	"reason" : "no such index [classes]",  
	"resource.type" : "index_or_alias",  
	"resource.id" : "classes",  
	"index_uuid" : "_na_",  
	"index" : "classes"  
  },  
  "status" : 404  
}  
=====================================================================  

index 생성

curl -XPUT http://localhost:9200/classes  
=====================================================================  
{"acknowledged":true,"shards_acknowledged":true,"index":"classes"}  
=====================================================================  

생성된 index 조회

curl -XGET http://localhost:9200/classes?pretty  
=====================================================================  
{  
  "classes" : {  
	"aliases" : { },  
	"mappings" : { },  
	"settings" : {  
	  "index" : {  
		"routing" : {  
		  "allocation" : {  
			"include" : {  
			  "_tier_preference" : "data_content"  
			}  
		  }  
		},  
		"number_of_shards" : "1",  
		"provided_name" : "classes",  
		"creation_date" : "1711984711754",  
		"number_of_replicas" : "1",  
		"uuid" : "NhY_9hrZRXKjRf1y_stCPA",  
		"version" : {  
		  "created" : "8503000"  
		}  
	  }  
	}  
  }  
}  
=====================================================================  

index 삭제

curl -XDELETE http://localhost:9200/classes  
=====================================================================  
{"acknowledged":true}  
=====================================================================  

index 삭제 후 조회

curl -XGET http://localhost:9200/classes?pretty  
=====================================================================  
{  
  "error" : {  
	"root_cause" : [  
	  {  
		"type" : "index_not_found_exception",  
		"reason" : "no such index [classes]",  
		"resource.type" : "index_or_alias",  
		"resource.id" : "classes",  
		"index_uuid" : "_na_",  
		"index" : "classes"  
	  }  
	],  
	"type" : "index_not_found_exception",  
	"reason" : "no such index [classes]",  
	"resource.type" : "index_or_alias",  
	"resource.id" : "classes",  
	"index_uuid" : "_na_",  
	"index" : "classes"  
  },  
  "status" : 404  
}  
=====================================================================  

Document 생성

index가 있던, 없던 생성이 가능하며 index가 없는 경우 index명과 타입명을 명시해주면 바로 생성할 수 있음  
  
=====================================================================  
curl -XPOST http://localhost:9200/classes/_doc/ -d "{\"title\" : \"Algorithm\", \"professor\" : \"john\"}" -H "Content-Type: application/json"  
=====================================================================  
  
※ 참고 사항  
	https://www.sysnet.pe.kr/2/0/11426  
	"curl의 JSON 텍스트를 명시할 때 작은따옴표를 이용해서는 안 되고 다음과 같이 큰따옴표를 사용하되, 내부의 인용 부호는 esacpe 처리해야 올바로 전달이 됩니다."  
	나는 윈도우에 엘라스틱 서치를 설치 하고, 윈도우의 CMD로 curl 명령어를 날리고 있음.  
	cmd 에서 json 타입을 넣어서 post 나 put 호출시 정상적으로 작동하지 않음  
	=====================================================================  
	curl -XPOST http://localhost:9200/classes/_doc/?pretty -d "{"title" : "Algorithm", "professor" : "john"}" -H "Content-Type: application/json"  
	{  
	  "error" : {  
		"root_cause" : [  
		  {  
			"type" : "document_parsing_exception",  
			"reason" : "[1:1] failed to parse: [1:3] Unexpected character ('t' (code 116)): was expecting double-quote to start field name\n at [Source: (byte[])\"{title : Algorithm, professor : john}\"; line: 1, column: 3]"  
		  }  
		],  
		"type" : "document_parsing_exception",  
		"reason" : "[1:1] failed to parse: [1:3] Unexpected character ('t' (code 116)): was expecting double-quote to start field name\n at [Source: (byte[])\"{title : Algorithm, professor : john}\"; line: 1, column: 3]",  
		"caused_by" : {  
		  "type" : "x_content_parse_exception",  
		  "reason" : "[1:3] Unexpected character ('t' (code 116)): was expecting double-quote to start field name\n at [Source: (byte[])\"{title : Algorithm, professor : john}\"; line: 1, column: 3]",  
		  "caused_by" : {  
			"type" : "json_parse_exception",  
			"reason" : "Unexpected character ('t' (code 116)): was expecting double-quote to start field name\n at [Source: (byte[])\"{title : Algorithm, professor : john}\"; line: 1, column: 3]"  
		  }  
		}  
	  },  
	  "status" : 400  
	}  
	=====================================================================  
  
※ 참고 사항  
	https://discuss.elastic.co/t/no-handler-found-for-uri-icsne-emails-and-method-post-version-8-4-3/316192/2  
	https://stackoverflow.com/questions/71477876/no-handler-found-for-uri-elasticsearch  
	내가 보고 있는 강의는 5.1.x 버전의 엘라스틱 서치를 사용함,  
	해당 강의에서는 아래의 명령어로 index를 생성할수 있지만, 내가 사용하고 있는 8.13.0 버전에서는 사용이 불가능함  
	=====================================================================  
	curl -XPOST http://localhost:9200/classes/class/1/ -d '{"title":"Algorithm","professor":"john"}'  
  
	{"error":"no handler found for uri [/classes/class/1/] and method [POST]"}  
	=====================================================================  
  
	참고링크를 확인해보면 8버전부터는 해당 명령어를 사용할 수 없으며, 아래와 같이 입력해야 함  
	=====================================================================  
	curl -XPOST http://localhost:9200/classes/_doc/ -d "{\"title\" : \"Algorithm\", \"professor\" : \"john\"}" -H "Content-Type: application/json"  
	=====================================================================  

Document 생성 후 조회

=====================================================================  
curl -XGET http://localhost:9200/classes?pretty  
{  
  "classes" : {  
	"aliases" : { },  
	"mappings" : {  
	  "properties" : {  
		"professor" : {  
		  "type" : "text",  
		  "fields" : {  
			"keyword" : {  
			  "type" : "keyword",  
			  "ignore_above" : 256  
			}  
		  }  
		},  
		"title" : {  
		  "type" : "text",  
		  "fields" : {  
			"keyword" : {  
			  "type" : "keyword",  
			  "ignore_above" : 256  
			}  
		  }  
		}  
	  }  
	},  
	"settings" : {  
	  "index" : {  
		"routing" : {  
		  "allocation" : {  
			"include" : {  
			  "_tier_preference" : "data_content"  
			}  
		  }  
		},  
		"number_of_shards" : "1",  
		"provided_name" : "classes",  
		"creation_date" : "1711985648147",  
		"number_of_replicas" : "1",  
		"uuid" : "EJPs6ReNQYmqdGmwPxQcng",  
		"version" : {  
		  "created" : "8503000"  
		}  
	  }  
	}  
  }  
}  
=====================================================================  

파일로 Docunemt 생성

※ 위의 "Document 생성" 부분과 같이 컨텐트 타입을 명시해 줘야함  
  
cmd의 경로와 일치하는곳에 아래의 파일 생성  
파일명 : oneclass.json  
파일 내용 :  
=====================================================================  
{  
	"title" : "Machine Learning",  
	"professor" : "Minsuk Heo",  
	"major" : "Computer Science",  
	"semester" : ["spring" , "fall"],  
	"student_count" : "aaa",  
	"unit" : 3,  
	"rating" : 5  
}  
=====================================================================  
  
생성  
=====================================================================  
curl -XPOST http://localhost:9200/classes/_doc/ -d @oneclass.json  -H "Content-Type: application/json"  
{"_index":"classes","_id":"kZ5Ymo4Bd1uTHJSdW3VD","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}  
=====================================================================  
  
조회  
=====================================================================  
curl -XGET http://localhost:9200/classes?pretty  
{  
  "classes" : {  
	"aliases" : { },  
	"mappings" : {  
	  "properties" : {  
		"major" : {  
		  "type" : "text",  
		  "fields" : {  
			"keyword" : {  
			  "type" : "keyword",  
			  "ignore_above" : 256  
			}  
		....중략...  
=====================================================================