티스토리 뷰

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);

 

실행하면 동일하게 성공.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
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
글 보관함