즐겁게/elasticsearch-8

IndexRequest를 이용한 Document 추가

파이브빈즈 2022. 10. 10. 17:54

Board와 Author 라는 게시판, 작성자 클래스가 있다고 할때 이를 이용하여 Index에 추가를 할수 있음

@Setter
@Getter
public class Board {
	private int idx;
    	private String category;
	private String subject;
	private String body;
	private Author author;
}

@Setter
@Getter
@AllArgsConstructor
public class Author {
	private String userid;
	private String name;
	private String email;
}

 

public void insertDocument() {
	ElasticsearchClient client = null;
	try {
		// Index name to indexing
		String indexName = "test-Index";

		// Author
		Author author = new Author("tester", "테스트작성자", "test@test-email.com");
		// Board
		Boad board = new Board();
		board.setIdx(1);
        	board.setCategory("자유게시판");
		board.setSubject("글작성 테스트 첫번째");
		board.setBody("첫번째 게시판 테스트입니다.");
		board.setAuthor(author);

		// ElasticSearchClient
		client = ElasticClient.getInstacne();


		1) Using JsonData ----------------------------------------------------------------

		// to json string
		ObjectMapper objMapper = new ObjectMapper();
		String jsonString = objMapper.writeValueAsString(board);

		// to JsonData
		JsonpMapper mapper = new JsonbJsonpMapper();
		JsonParser parser = mapper.jsonProvider().createParser(new StringReader(jsonString));
		JsonData jsonData = JsonData.from(parser, mapper);		

		IndexRequest<JsonData> indexRequest = IndexRequest.of(builder -> builder
								.index(indexName)
								.document(jsonData)
								);
		// or
        
		IndexRequest<JsonData> indexRequest = new IndexRequest.Builder<JsonData>()
								.index(indexName)
								.document(jsonData)
								.build();


		2) or, Using Object -------------------------------------------------------------------

		IndexRequest<Board> indexRequest = IndexRequest.of(builder -> builder
								.index(indexName)
								.document(board)
								);

		// or
                                
		IndexRequest<Board> indexRequest = new IndexRequest.Builder<Board>()
								.index(indexName)
								.document(board)
								.build();

		// ---------------------------------------------------------------------------------

		IndexResponse response = client.index(indexRequest);
		System.out.println("insertDocument result: " + response.result());

	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		ElasticClient.close();
	}
}