티스토리 뷰
01) create 메서드 만들기
이전 만들어둔 ElasticUtil.java에 create 메서드 생성.
public IndexResponse create(String index, String id, String jsonBody) {
IndexResponse response = null;
IndexRequest indexRequest = new IndexRequest(index).id(id).source(jsonBody, XContentType.JSON);
try {
response = client.index(indexRequest, RequestOptions.DEFAULT);
} catch(IOException e) {
e.printStackTrace();
}
return response;
}
ElasticsearchTestApplication.java에서 Map에 데이터를 넣고 XContentBuilder로 데이터를 넣고 response에 담은 후 요청.
String index = "gaia";
String id = "1";
ElasticUtil elastic = ElasticUtil.getInstance();
Map<String, Object> map = new HashMap<>();
map.put("새로운 항목", 155);
map.put("test", 153);
XContentBuilder xContent = XContentFactory.jsonBuilder().map(map);
String jsonBody = Strings.toString(xContent);
IndexResponse response = elastic.create(index, id, jsonBody);
System.out.println(response);
다음은 XContetnBuilder 부분이 번거로우니 create 메서드 쪽으로 넣어버림.
public IndexResponse create(String index, String id, Map<String, Object> data) throws IOException {
IndexResponse response = null;
XContentBuilder xContent = XContentFactory.jsonBuilder().map(data);
String jsonBody = Strings.toString(xContent);
IndexRequest indexRequest = new IndexRequest(index).id(id).source(jsonBody, XContentType.JSON);
response = client.index(indexRequest, RequestOptions.DEFAULT);
return response;
}
이제 사용할때 String jsonBody가 아닌 map 형태를 바로 create 메서드로 요청하면 됨.
String index = "gaia";
String id = "1";
ElasticUtil elastic = ElasticUtil.getInstance();
Map<String, Object> map = new HashMap<>();
map.put("새로운 항목", 155);
map.put("test", 153);
IndexResponse response = elastic.create(index, id, map);
System.out.println(response);
실행하면 동일하게 성공.
'DB > Elasticsearch' 카테고리의 다른 글
06. Elasticsearch - snapshot 생성 및 복원 (0) | 2022.07.13 |
---|---|
05. Elasticsearch - 외부 접속 허용 (0) | 2022.05.16 |
03. Elasticsearch - Java를 이용하여 Get Request (0) | 2021.07.16 |
02. Elasticsearch - 조회, 삽입, 수정, 삭제 (0) | 2021.07.13 |
01. Elasticsearch - 설치 및 실행 (0) | 2021.07.13 |
댓글