springboot2.5.6+elasticsearch7.16
1 pom 引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2 总配置
package com.realize.framework.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author : ywb
* @createdDate : 2020/5/31
* @updatedDate
*/
@Configuration
public class ElasticSearchConfig {
@Value("${spring.elasticsearch.ip}")
private String ip;
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(new HttpHost(ip, 9200, "http"))
);
return restHighLevelClient;
}
}
3 controller
//创建索引,存入数据
@ApiOperation("创建新索引")
@GetMapping("/createIndex")
public Boolean createIndex() throws IOException {
return iLawsAndRegulationsService.createIndex();
}
4 service
/**
* @Author HZJ
* @Description 创建新索引
* @date 2022/4/6 0:34
* @return java.lang.Boolean
**/
@Override
public Boolean createIndex() throws IOException {
/*DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("ywb");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
GetIndexRequest request = new GetIndexRequest("ywb");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);*/
CreateIndexRequest createIndexRequest = new CreateIndexRequest(clusterName);
CreateIndexResponse response = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println(response);
//查询出所有数据
List<BusiSpecialSubjectInfo> searchList = busiProjectInformationMapper.selectOfEs();
try{
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("2m");
for (int i = 0; i < searchList.size(); i++) {
bulkRequest.add(new IndexRequest(clusterName).source(JSON.toJSONString(searchList.get(i)),XContentType.JSON));
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
5 yml 配置
# ES 地址
spring
elasticsearch:
ip: 127.0.0.1
springboot2.5+elasticsearch7.16
于 2022-04-08 21:46:21 首次发布