Spring Boot集成ES7.10

本文介绍了在Spring Boot中如何集成Elasticsearch 7.10,包括导入依赖、创建ES映射、初始化客户端、Spring Boot API封装及测试。同时,还详细讲解了如何更改ES字段类型,例如将text转换为keyword。

    在Spring boot中主要有Java REST Client、spring-data-elasticsearch两种方式,这里建议使用Elasticsearch官方提供的Java High Level REST Client来集成。

一:导入依赖:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.2</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.10.2</version>
</dependency>

创建es映射

PUT user_index
{
	"settings":{
	"number_of_shards": "3",
	"number_of_replicas": "0"
	},
  	"mappings": {
  		"properties":{
			"age" : {
			  "type" : "short"
			},
			"createTime" : {
			  "type" : "long"
			},
			"id" : {
			  "type" : "integer"
			},
			"updateTime" : {
			  "type" : "long"
			},
			"userName" : {
			  "type" : "text",
			  "fields" : {
				"keyword" : {
				  "type" : "keyword"
				}
			  }
			}
		}
  	}
}

二:初始化客户端

1,添加配置文件添加连接信息

elasticsearch:
  host: 127.0.0.1:9200
  port: 9200
  connTimeout: 3000
  socketTimeout: 5000
  connectionRequestTimeout: 1000
  username: elastic
  password: 123456

2,添加ES配置类

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @date 2022/7/15
 **/
@Configuration
public class ElasticsearchConfiguration {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private Integer port;

    @Value("${elasticsearch.connTimeout}")
    private Integer connTimeout;

    @Value("${elasticsearch.socketTimeout}")
    private Integer socketTimeout;

    @Value("${elasticsearch.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    @Bean(destroyMethod = "close", name = "client")
    public RestHighLevelClient initRestClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        RestClientBuilder builder = RestClient.builder(toHttpHost())
                .setRequestConfigCallback(requestConfigBuilder ->
                        requestConfigBuilder.setConnectTimeout(connTimeout)
                                .setSocketTimeout(socketTimeout)
                                .setConnectionRequestTimeout(connectionRequestTimeout))
                                .setHttpClientConfigCallback(h -> h.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);
    }


    /**
     * 解析配置的字符串,转为HttpHost对象数组
     */
    private HttpHost[] toHttpHost() {
        if (!StringUtils.hasLength(host)) {
            throw new RuntimeException("invalid elasticsearch configuration");
        }

        String[] hostArray = host.split(",");
        HttpHost[] httpHosts = new HttpHost[hostArray.length];
        HttpHost httpHost;
        for (int i = 0; i < hostArray.length; i++) {
            String[] strings = hostArray[i].split(":");
            httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
            httpHosts[i] = httpHost;
        }
        return httpHosts;
    }
}

三,springboot api封装

@Component
public class EsUtil {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     */
    @SneakyThrows
    public Boolean createIndex(String indexName) {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        // request.settings()  可以设置分片规则
        // request.mapping() 可以设置映射字段
        CreateIndexResponse indexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return indexResponse.isAcknowledged();
    }

    /**
     * 查询索引  * 查询全部
     */
    @SneakyThrows
    public List<String> searchIndex(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        if (!exists) {
            return Lists.newArrayList();
        }
        GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
        return Lists.newArrayList(getIndexResponse.getIndices());
    }

    /**
     * 删除索引
     */
    @SneakyThrows
    public Boolean deleteIndex(String indexName) {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (!exists) {
            return false;
        }
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse response = r
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值