一、创建springboot项目
1.此处创建简单的springboot项目,不做过多赘述
我的springboot版本是2.4.5,装的ES是7.6.1的
二、导入elasticsearch依赖
1.pom.xml中添加elasticsearch相关依赖,如下:注意这里依赖的版本与es库版本需要一致
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.6.1</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.6.1</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.6.1</version> </dependency>
三、定义elasticsearch的配置类,设置elasticsearch库信息
创建ElasticSearchClientConfig类,目录结构如下:
配置基本信息代码如下:
package com.elasticsearch.esapi.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")
//可配置多个作为集群
//new HttpHost("127.0.0.1",9300,"http")
));
return restHighLevelClient;
}
}
四、对索引进进行增删查操作
在springboot的测试类中进行测试,代码如下:
package com.elasticsearch.esapi;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
imp