SpringBoot2.x RestClient 작업 ElasticSearch 7.x

SpringBoot2.x RestClient 작업 ElasticSearch 7.x
현지 환경
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 새 색인 문서
  • 주의:코드 에 있 는 JestEntity 는 일반적인 실체 류 일 뿐 입 니 다.당신들 은 스스로 작성 할 수 있 습 니 다.Jest 가방 에 있 는 물건 아래 의 코드 가 아 닙 니 다.저 는 Create IndexRequest 를 사용 하지 않 고 문 서 를 직접 만 들 었 습 니 다
  • 	@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();
                } 
            }
        }
    

    좋은 웹페이지 즐겨찾기