Springboot集成elasticsearch
Springboot集成elasticsearch有多种方式,如TransportClient、
RestHighLevelClient等等;但是官方已经停止更新TransportClient并且在elasticsearch8.0之后已经弃用,所以本人使用的是RestHighLevelClient。
引入pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
增加配置
配置文件
elasticsearch:
url: 127.0.0.1
port: 9200
配置类
@Configuration
public class ElasticSearchConfig {
@Value("#{elasticsearch.url}")
private String url;
@Value("#{elasticsearch.port}")
private String port;
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(url, 9200)));
return client;
}
}
工具类
创建索引
public Boolean createIndex(String indexNam) {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexNam.toLowerCase());
createIndexRequest.settings(Settings.builder().put("index.number_of_shards", 4)
.put("index.number_of_replicas", 2));
try {
XContentBuilder xContentBuilder= XContentFactory.jsonBuilder();
xContentBuilder.startObject().startObject("properties")
.startObject("type").field("type", "integer").endObject()
.startObject("content").field("type", "text").field("analyzer", "ik_max_word").endObject()
.endObject().endObject();
creat