SpringBoot2.x RestClient 작업 ElasticSearch 7.x
28914 단어 JavaDistributedspringboot
현지 환경
ES 신 판 과 사장 차이7.6.2 버 전
오래된 버 전
RestClient 사용 하기가 져 오기 의존yml 설정
새 색인 문서색인 존재 여 부 를 판단 하 다.
찾다
하 이 라이트
로 컬 환경
Spring Boot 2.2.6 Elasticsearch 7.6.2 이 글 을 쓴 이 유 는"The well known TransportClient is deprecated as of Elasticsearch 7 and will be removed in Elasticsearch 8.(see the Elasticsearch documentation).Spring Data Elasticsearch will support the TransportClient as long as it is available in the used Elasticsearch version.ecommend to use the High Level REST Client instead of the TransportClient.그러나 인터넷 상에 서 RestClient 에 관 한 자 료 는 매우 적다.
ES 새 버 전과 사장 님 차이
먼저 색인 을 만 들 겠 습 니 다.새 버 전 은 type 이름 을 가 질 수 없습니다.우 리 는 코드 를 통 해 코드 가 간결 합 니 다.
7.6.2 버 전
PUT http://localhost:9200/test/
{
"mappings":{
"properties":{
"id":{
"type": "long",
"index": true
},
"title":{
"type": "text"
}
}
}
}
옛날 판본
PUT http://localhost:9200/test/
{
"mappings":{
"lalala":{
"properties":{
"id":{
"type": "long",
"index": true
},
"title":{
"type": "text"
}
}
}
}
}
그리고 자주 사용 하 는 점:minimummatch 새 버 전 은 minimum 을 사용 해 야 합 니 다.should_match
RestClient 사용 하기
가 져 오기 의존
가 져 오기 의존 은 말 할 것 도 없고,예전 에는 Jest 가방 이 필요 했다.
<properties>
.......
properties>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
yml 설정
기 존 버 전과 비교 하기 위해 jest 를 제거 하지 않 았 습 니 다.사실 jest 의 uris 는 시대 에 뒤떨어 졌 음 을 명확 하 게 밝 혔 습 니 다.
spring:
elasticsearch:
jest:
uris: http://localhost:9200
rest:
uris: http://localhost:9200
rest 새 색인 문서
@Autowired
private RestHighLevelClient restClient;
@Test
public void testRestCreate(){
JestEntity entity = new JestEntity();
entity.setId(1);
entity.setTitle(" ");
ObjectMapper mapper=new ObjectMapper();
String source = mapper.writeValueAsString(entity);
// 1. IndexRequest
// type es7 ,type
// source json, fastjson jackson
// xml es , 2 ,index id
IndexRequest request = new IndexRequest("test", "_doc", "1")
.source(source, XContentType.JSON)
.setRefreshPolicy(IMMEDIATE);
//
try {
IndexResponse res = restClient.index(request, RequestOptions.DEFAULT);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
//
/*ActionListener listener = new ActionListener() {
@Override
public void onResponse(IndexResponse indexResponse) {
System.out.println(" ");
System.out.println(indexResponse);
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
}
};
restClient.indexAsync(request,RequestOptions.DEFAULT,listener);
*/
}
색인 존재 여부 판단
@Test
public void testRestExists(){
GetIndexRequest request = new GetIndexRequest("test");
// indices , ,
CreateIndexResponse res = restClient.indices().exists(request,RequestOptions.DEFAULT);
System.out.println(res);
}
찾다
@Test
public void testRestSearch(){
SearchRequest searchRequest = new SearchRequest("test");
//ES7 types
//
//searchRequest.types("_doc");
SearchSourceBuilder searchSource = new SearchSourceBuilder();
//
//searchSource.query(QueryBuilders.matchAllQuery());
// title
searchSource.query(QueryBuilders.matchQuery("title", " "));
searchRequest.source(searchSource);
try {
SearchResponse res = restClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
}
하 이 라이트
highlightBuilder.field 새 버 전 을 설정 해 야 합 니 다.그렇지 않 으 면 하 이 라이트 내용 을 가 져 올 수 없습니다.
@Test
public void testRestSearch() throws IOException {
//
SearchRequest searchRequest = new SearchRequest("Hoola");
//searchRequest.types("_doc"); ES7
//
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// field
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("tag").field("title");//
highlightBuilder.preTags("");
highlightBuilder.postTags("");
// , , restClient
searchSourceBuilder.query(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("tag", " "))
.should(QueryBuilders.matchQuery("title", " "))
.minimumShouldMatch(1)
).highlighter(highlightBuilder).from(0).size(10);
//
searchRequest.source(searchSourceBuilder);
SearchResponse res = restClient.search(searchRequest, RequestOptions.DEFAULT);
//
for (SearchHit hit:res.getHits().getHits()){
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
// , map
if (highlightFields.get("title")!=null){
sourceAsMap.put("title",highlightFields.get("title").fragments());
}
if (highlightFields.get("tag")!=null){
sourceAsMap.put("tag",highlightFields.get("tag").fragments());
}
JestEntity jestEntity = new JestEntity();
try {
//map 。
BeanUtils.populate(jestEntity, sourceAsMap);
System.out.println(jestEntity);
} catch (IllegalAccessException|InvocationTargetException e) {
e.printStackTrace();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.