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();
}
}
'즐겁게 > elasticsearch-8' 카테고리의 다른 글
elasticsearch snapshot 설정 (0) | 2022.10.23 |
---|---|
Query, SearchRequest를 이용한 검색 (0) | 2022.10.17 |
PutIndicesSettingsRequest를 이용한 인덱스 Settings 값 변경 (0) | 2022.10.10 |
DeleteIndexRequest를 이용한 인덱스삭제 (0) | 2022.10.10 |
CreateIndexRequest를 이용한 Index 생성 (0) | 2022.10.06 |