본문 바로가기

[Elasticsearch]

[Elasticsearch] Springboot에서 Elasticsearch구현하기 - Document

반응형
이 글은 이전 블로그에서 가져온 글입니다. (2020.10.11)

앞 단에서 테이블인 인덱스를 생성했으니 이번 장에서는 그 안에 데이터들인 Document를 생성해보자

 

1. Document 생성

1-1. Controller

@PostMapping("/insert-user")
fun insertUser(index: String,@RequestBody user: EsPostUserIn) : IndexResponse {
    println("user : $user")
    return service.insertUser(index, user)
}

1-2. Service

fun insertUser(index: String, user: EsPostUserIn): IndexResponse {
    println("==========================================================")
    println("insert document")
    println("==========================================================")
    var jsonMap: MutableMap<String, Any> = mutableMapOf()
    jsonMap["userName"] = user.userName
    jsonMap["age"] = user.age

    var request: IndexRequest = IndexRequest(index).source(jsonMap)
    println("1. request : $request")

    val response: IndexResponse = createConnection().index(request, RequestOptions.DEFAULT)
    println("2. respone  : $response")

    return response
}

생성하는 단계에서 다음 코드를 수행하면 특정 아이디 값을 부여해줄 수 있다.

IndexRequest(index).id("아이디값").source(jsonMap)

만약 아무런 id()를 사용하지 않으면 ES 자체에서 랜덤값을 부여해준다.

2. Document  조회

2-1. Controller

@GetMapping("/select-all")
fun selectDocument(index: String) : SearchResponse {
    return service.selectDocument(index)
}

// 풀텍스트 조회
@GetMapping("/select-query")
fun selectDocumentByQuery(index:String,input: String) : SearchResponse {
    return service.getQuery(index,input)
}

2-2. Service

// document 전체 조회
fun selectDocument(index:String): SearchResponse {

    val searchSourceBuilder = SearchSourceBuilder()
    searchSourceBuilder.query(QueryBuilders.matchAllQuery())
    searchSourceBuilder.from(0)
    searchSourceBuilder.size(5)

    val request = SearchRequest(index)
    request.source(searchSourceBuilder)

    //문서조회 결과
    val client = createConnection()
    val response = client.search(request, RequestOptions.DEFAULT)

    print(response)
    client.close()
    return response
}

// 풀텍스트 조회
fun getQuery(index: String, input: String): SearchResponse {
    println("==========================================================")
    println("search by query")
    println("==========================================================")

    val searchQuery = QueryBuilders.queryStringQuery(input)                     //
    val searchSourceBuilder = SearchSourceBuilder().query(searchQuery)
    println("1. searchSourceBuilder : $searchSourceBuilder")

    val request = SearchRequest(index)
    request.source(searchSourceBuilder)
    println("2. request : $request")

    val searchResponse = createConnection().search(request, RequestOptions.DEFAULT)
    println("3. searchResponse : $searchResponse")

    return searchResponse
}

3. Document 수정

3-1. Controller

@PatchMapping("/update-user")
fun updateUser(index: String, type: String,id: String, name :String) : UpdateResponse {
    return service.updateUser(index, type,id, name)
}

3-2. Service

fun updateUser(index:String, type: String, id: String, name: String): UpdateResponse {
    println("==========================================================")
    println("update user")
    println("==========================================================")
    val jsonMap: MutableMap<String, Any> = mutableMapOf()
    jsonMap.put("userName", name)

    val request: UpdateRequest = UpdateRequest(index,type, id).doc(jsonMap)
    println("1. request : $request")

    val response: UpdateResponse = createConnection().update(request,RequestOptions.DEFAULT)
    println("2. response : $response")

    return response
}

해당 코드에서 type도 입력을 받도록 되어있는데 default값은 _doc다.

4. Document 삭제

4-1. Controller

@DeleteMapping("/delete-user")
fun deleteUser(index: String, type: String,id: String) : DeleteResponse {
    return service.deleteUser(index,type,id)
}

4-2. Service

fun deleteUser(index:String, type:String,id: String): DeleteResponse {
    println("==========================================================")
    println("delete user")
    println("==========================================================")
    val request: DeleteRequest = DeleteRequest(index,type, id)
    println("1. request : $request")

    val deleteResponse: DeleteResponse = createConnection().delete(request, RequestOptions.DEFAULT)
    println("2. deleteResponse : $deleteResponse")

    return deleteResponse
}

5. HTTP

// 특정 document 조회
GET http://localhost:9200/[Index명]/_doc/[Id]?pretty

// 전체 document 조회
GET http://localhost:9200/[Index명]/_doc/_search?pretty

// document 생성
POST http://localhost:9200/[Index명]/_doc/[Id]?pretty
Content-Type: application/json

{
	"key": "value"
}

// document 수정
PUT http://localhost:9200/[Index명]/_doc/[Id]?pretty
Content-Type: application/json

{
	"key": "value"
}

// document 삭제
POST http://localhost:9200/[Index명]/_delete_by_query?conflicts=proceed
Content-Type: application/json

{
  "query": {
    "match_all": {}
  }
}

// bulk insert
POST http://localhost:9200/[Index명]/_doc/_bulk?pretty
Content_Type: application/x-ndjson

> 파일명.ndjson

bulk insert를 수행할때는 ndjson형태로 파일을 전송해야 api가 작동한다.

 

ndjson이란 Newline Delimited Json형태로 유효한 json파일을 줄로 구분지은것을 말한다.

{ "index" : { "_index" : "test", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_id" : "2" } }
{ "create" : { "_index" : "test", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
728x90