ElasticsearchTemplate替换为ElasticsearchRestTemplate(Transport Client替换为RestHighLevelClient)

 

 

 

Elasticsearch 8.0的版本中也将完全移除TransportClient,其次有些es有些账号不能通过 9300端口连接

所以项目中打算由RestHighLevelClient 替换掉 Transport Client

 

版本

这里给一张springboot官方的版本推荐

 

 

 

这里我的springboot版本为 2.1.6.RELEASE Elasticsearch 版本为 6.8.2

升级需要的maven依赖:

<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>

只需要这一个即可

 

配置

application.properties

# ip+端口
elasticSearch.host.port=localhost:9200
elasticSearch.user=elastic
elasticSearch.password=123456
# Socket连接超时时间
elasticSearch.socketTimeout = 60

ElasticConfig

@Configuration
public class ElasticConfig extends AbstractElasticsearchConfiguration {
 
    @Value("${elasticSearch.host.port}")
    private String hostAndPort;
    @Value("${elasticSearch.user}")
    private String user;
    @Value("${elasticSearch.password}")
    private String password;
    @Value("${elasticSearch.socketTimeout}")
    private long socketTimeout;
 
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
 
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(hostAndPort)
                .withBasicAuth(user, password)
                .withSocketTimeout(Duration.ofSeconds(socketTimeout))
                .build();
 
        return RestClients.create(clientConfiguration).rest();
    }
    
    /*@Bean
    public RestHighLevelClient esRestClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("192.168.77.130", 9200, "http")));
        return  client;
    }*/
    
    
 
    @Bean
    public ElasticsearchRestTemplate restTemplate() throws Exception {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
 
 
}

至此环境就搭建完成了,我们来看看具体的操作

 

删除索引

 
@Autowired
ElasticsearchRestTemplate restTemplate;
 
 public boolean deleteIndex(String indexName) throws Exception{
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = restTemplate.getClient().indices().exists(request, RequestOptions.DEFAULT);
        if (exists) {
            log.info("索引存在");
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
            AcknowledgedResponse deleteIndexResponse = restTemplate.getClient().indices()
                    .delete(deleteIndexRequest, RequestOptions.DEFAULT);
 
            if (deleteIndexResponse.isAcknowledged()) {
                log.info("删除成功");
            }
            return true;
 
        }
        return true;
    }

创建索引

    public boolean createIndex(String indexName, String mapping) throws Exception {
        //创建前先调用上面的删除索引方法
        deleteIndex(indexName);
        // 创建索引
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        createIndexRequest.settings(Settings.builder()
                .put("index.number_of_shards", 1)//指定shards
                .put("index.number_of_replicas", 0))//指定replicas
                .mapping(mapping, XContentType.JSON);//指定mapping
        CreateIndexResponse createIndexResponse = restTemplate.getClient().indices()
                .create(createIndexRequest, RequestOptions.DEFAULT);
        if (createIndexResponse.isAcknowledged()) {
            log.info("索引创建成功");
            return true;
        }
 
        return false;
 
 
    }

批量插入数据

public <T> int documents(List<DscStandardProduct> list){
         if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        DscStandardProduct t = list.get(0);
        Document document = t.getClass().getAnnotation(Document.class);
        BulkRequest request = new BulkRequest();
        List<IndexQuery> queries = list.stream().map(item->{
            item.getOtherSpec();
            IndexQuery query = new IndexQuery();
            query.setIndexName(document.indexName());
            query.setType(document.type());
            query.setSource(JSON.toJSONString(item));
            return query;
        }).collect(Collectors.toList());
 
        restTemplate.bulkIndex(queries);
        return list.size();
    }

这里给出类 DscStandardProduct的注解信息

 

 

 

简单的查询

基本还是和原来 ElasticsearchTemplate 类似

public void query(){
        Drug drug = new Drug(name, company, approval, spec);
        SearchQuery query = getQuery(drug, true);
        PageRequest request = PageRequest.of(0,1);
        query.setPageable(request);
        List<DscStandardProduct> list = restTemplate.queryForList(query, DscStandardProduct.class);
 
}
 
 
 
private SearchQuery getQuery(Drug drug, Boolean specFlag) {
 
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        BoolQueryBuilder nameMatch = QueryBuilders.boolQuery().minimumShouldMatch(1)
                .should(QueryBuilders.matchQuery("drugName",drug.getName()))
                .should(QueryBuilders.matchQuery("productName",drug.getName()));
 
 
 
        BoolQueryBuilder must = QueryBuilders.boolQuery().minimumShouldMatch(2)
                .should(nameMatch)
                .should(QueryBuilders.matchQuery("company", drug.getCompany()))
                .should(QueryBuilders.matchQuery("approvalIndex", drug.getApproval()));
 
 
        builder.must(must);
        if (specFlag) {
            BoolQueryBuilder specMatch = QueryBuilders.boolQuery().minimumShouldMatch(1)
                    .should(QueryBuilders.matchQuery("specIndex",drug.getSpec()))
                    .should(QueryBuilders.matchQuery("otherSpec",drug.getSpec()));
            builder.must(specMatch);
            builder.should(QueryBuilders.termQuery("specIndex.full", drug.getSpec()))
                    .should(QueryBuilders.termQuery("otherSpec.full", drug.getSpec()));
        }
 
 
        return new NativeSearchQuery(builder);
 
    }

更多

更多操作请参考
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.8/java-rest-high-search.html

posted @ 2021-12-16 12:01  图图小淘气_real  阅读(687)  评论(0编辑  收藏  举报