java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot2集成Elasticsearch6.x

SpringBoot2如何集成Elasticsearch6.x(TransportClient方式)

作者:终遇你..

这篇文章主要介绍了SpringBoot2如何集成Elasticsearch6.x(TransportClient方式)问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

技术架构

依赖POM

   <properties>
        <java.version>1.8</java.version>
        <elasticSearch.version>6.4.3</elasticSearch.version>
    </properties>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.59</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticSearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticSearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticSearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>transport-netty4-client</artifactId>
            <version>${elasticSearch.version}</version>
        </dependency>

application.yml配置

elasticsearch:
  cluster-name: test-es
  # 多台机器用,分割
  cluster-nodes: 192.168.116.200:9300

ESConfig 配置类

package com.example.link.config;
 
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
 
import java.net.InetAddress;
 
/**
 * @author lanx
 * @date 2022/3/13
 */
@Configuration
@Slf4j
public class ESConfig {
    private static final String CLUSTER_NODES_SPLIT_SYMBOL = ",";
    private static final String HOST_PORT_SPLIT_SYMBOL = ":";
 
 
    @Value("${elasticsearch.cluster-name}")
    String clusterName;
    @Value("${elasticsearch.cluster-nodes}")
    String clusterNodes;
 
    @Bean
    public TransportClient getTransportClient() {
        log.info("elasticsearch init.");
        if (StringUtils.isEmpty(clusterName)) {
            throw new RuntimeException("elasticsearch.cluster-name is empty.");
        }
        if (StringUtils.isEmpty(clusterNodes)) {
            throw new RuntimeException("elasticsearch.cluster-nodes is empty.");
        }
        try {
            Settings settings = Settings.builder().put("cluster.name", clusterName.trim())
                    .put("client.transport.sniff", true).build();
            TransportClient transportClient = new PreBuiltTransportClient(settings);
            String[] clusterNodeArray = clusterNodes.trim().split(CLUSTER_NODES_SPLIT_SYMBOL);
            for (String clusterNode : clusterNodeArray) {
                String[] clusterNodeInfoArray = clusterNode.trim().split(HOST_PORT_SPLIT_SYMBOL);
                TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(clusterNodeInfoArray[0]),
                        Integer.parseInt(clusterNodeInfoArray[1]));
                transportClient.addTransportAddress(transportAddress);
            }
            log.info("elasticsearch init success.");
            return transportClient;
        } catch (Exception e) {
            throw new RuntimeException("elasticsearch init fail.");
        }
    }
}

LinkWebAApplicationTests 测试类

package com.example.link;
 
import com.alibaba.fastjson.JSON;
import com.example.link.domain.Student;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
 
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
class LinkWebAApplicationTests {
 
    private Student student;
 
    @Autowired
    private TransportClient transportClient;
 
 
    /**
     * ES 插入数据,指定id
     */
    @Test
    void test() {
        student = new Student();
        student.setName("test2");
        student.setAge(20);
       IndexResponse response =  transportClient.prepareIndex("school","student","1").setSource(JSON.toJSONString(student), XContentType.JSON)
                .get();
        log.info("status:{}",response.status().getStatus());
    }
    /**
     * ES 插入数据,不指定id
     */
    @Test
    void test2() {
        student = new Student();
        student.setName("test2");
        student.setAge(20);
        IndexResponse response =  transportClient.prepareIndex("school","student").setSource(JSON.toJSONString(student), XContentType.JSON)
                .get();
        log.info("status:{}",response.status().getStatus());
    }
 
    /**
     * ES p批量插入数据,不指定id
     */
    @Test
    void test3() {
 
        //建立批量提交类
        BulkRequestBuilder bulkRequest =transportClient.prepareBulk();
        for (int i = 0; i<= 10 ;i++){
            student = new Student();
            student.setName("lx"+i);
            student.setAge(i);
            bulkRequest.add(transportClient.prepareIndex("school","student").setSource(JSON.toJSONString(student), XContentType.JSON));
        }
        BulkResponse bulkResponse=bulkRequest.execute().actionGet();
        //提交过程是否产生错误
        if(bulkResponse.hasFailures()){
            log.info("buildFailureMessage:{}",bulkResponse.buildFailureMessage());
        }else {
            log.info("bulkRequest success !");
        }
 
    }
 
    /*
     * 查询分页数据
     */
    @Test
    void test4(){
        SearchRequestBuilder builder = transportClient.prepareSearch("school");
        builder.setTypes("student");
        builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
        builder.setFrom(0);
        builder.setSize(20);
        //explain为true表示根据数据相关度排序,和关键字匹配最高的排在前面
        builder.setExplain(true);
 
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 搜索 name 字段包含test2的数据
         queryBuilder.must(QueryBuilders.matchQuery("name", "lx0"));
        queryBuilder.must(QueryBuilders.matchQuery("age", "0"));
        //多个字段查询一个文本
        queryBuilder.must(QueryBuilders.multiMatchQuery("0", "name","age"));
 
        // 多条件查询 FunctionScore
        FunctionScoreQueryBuilder query = QueryBuilders.functionScoreQuery(queryBuilder);
        builder.setQuery(query);
 
 
        SearchResponse response = builder.execute().actionGet();
        SearchHits hits = response.getHits();
        List<Map<String,Object>> result = new ArrayList<Map<String, Object>>();
        for (SearchHit hit:hits){
            result.add(hit.getSourceAsMap());
        }
 
        log.info("result List : {}",JSON.toJSONString(result));
 
    }
 
    /**
     * 更新数据
     * @throws Exception
     */
    @Test
    public void test5() throws Exception{
        student = new Student();
        student.setName("lx");
        student.setAge(30);
        UpdateRequest updateRequest = new UpdateRequest();
        UpdateRequest doc = updateRequest
                .index("school")
                .type("student")
                .id("1")
                .doc(JSON.toJSONString(student), XContentType.JSON);
        UpdateResponse response = transportClient.update(doc).get();
      log.info("status : {}",response.status().toString());
    }
 
    /**
     * 根据id删除数据
     */
    @Test
    public void test6(){
        DeleteResponse response = transportClient.prepareDelete("school", "student", "1").get();
        log.info("status : {}",response.status());
    }
 
    /**
     * 根据条件删除数据
     */
    @Test
    public void test8() {
        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE
                .newRequestBuilder(transportClient)
                .filter(QueryBuilders.matchQuery("name", "test2"))
                .source("school") //index
                .get();
        log.info("status : {}",response.getDeleted());
 
    }
 
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文