Springboot 整合ElasticSearch(Client篇)

目录

 

1.简介

2.依赖。pom.xml

3.配置类ESConfig

 

4.yml配置文件

5.实体类,省略不写了,根据自己的业务定义实体类

6.Client的使用

7.有问题留言,谢谢


1.简介

相信使用springboot 2.0以下的同学都遇到这个坑了。

spring-boot-starter-data-elasticsearch 不支持springboot 版本2.0以下

所以。。。只能自己写client来操作ElasticSearch了

 

2.依赖。pom.xml

关于ElasticSearch与Springboot的整合,我经历了2次因为reimport线上的包导致项目跑起来报错了。

所以,建议大家能在调试成功后把这部分jar包单独分开。

其中swagger也可以不加入到依赖

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <elasticsearch.version>6.5.1</elasticsearch.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Elasticsearch核心依赖包 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <!-- 日志依赖 -->
        <!-- ===================== @Getter @Setter @Slf4j @Data ======================== -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>

 

3.配置类ESConfig

package com.example.elatiscsearch;

import org.apache.commons.lang.StringUtils;
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 java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @program: elatiscsearch
 * @description: config
 * @author: Irving Wei
 * @create: 2018-12-06 11:00
 **/
@Configuration
public class ESConfig {
    @Value("${elasticsearch.host}")
    private String host;

    private int port;
    @Value("${elasticsearch.port}")
    private void setPort(String str){
        if(StringUtils.isNotBlank(str)){
            port = Integer.valueOf(str);
        }
    }
    @Value("${elasticsearch.cluster-name}")
    private String clusterName;

    @Bean
    public TransportClient client() throws UnknownHostException {

        //es集群连接
        TransportAddress node = new TransportAddress(
                InetAddress.getByName(host),
                port
        );

        //es集群配置(自定义配置) 连接自己安装的集群名称
        Settings settings = Settings.builder()
                .put("cluster.name", clusterName)
                .build();

        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);

        client.addTransportAddress(node);

        return client;
    }
}

 

4.yml配置文件

elasticsearch:
  host: #es的IP
  port: 9300
  cluster-name: my-application  #这里在es的配置文件查,要保证cluster-name与配置文件相同

 

5.实体类,省略不写了,根据自己的业务定义实体类

 

6.Client的使用

@Autowired
private TransportClient client;

public void function(){
    // 单一查询
    GetResponse result = this.client.prepareGet("index_name", "type_name", id).get();



    // 新增
    // entityMap 是一个map参数,将要保存的实体转换为map类型
    IndexResponse result = this.client.prepareIndex("index_name", "type_name")
                    .setSource(entityMap)
                    .get();

    // 删除
    DeleteResponse result = this.client.prepareDelete("index_name", "type_name",         id).get();



    // 修改
    // dataMap: 把需要修改的数据,以key value的形式封装到一个map中
    UpdateRequestBuilder urb = client.prepareUpdate("index_name", "type_name", id);
        urb.setDoc(dataMap);
        urb.execute().actionGet();


    // 复合查询
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

    boolQuery.must(QueryBuilders.matchQuery("filed", value));

    RangeQueryBuilder rangeQuery =     QueryBuilders.rangeQuery("word_count").from(gtWordCount);

        if (ltWordCount != null && ltWordCount > 0) {
            rangeQuery.to(ltWordCount);
        }

        boolQuery.filter(rangeQuery);

        SearchRequestBuilder builder = this.client.prepareSearch("index_name")
                .setTypes("type_name")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(0)
                .setSize(10);

        SearchResponse response = builder.get();
        List<Object> result = new ArrayList<>();

        for (SearchHit hit : response.getHits()) {
            try {
                result.add(hit.getSourceAsMap());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


}

 

7.有问题留言,谢谢

6点下班了,我今天一定要准时走,耶稣也拦不住我.gif,手动狗头!

发布了37 篇原创文章 · 获赞 16 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览