maven
<dependency> <groupId>org.elasticsearch.clientgroupId> <artifactId>elasticsearch-rest-high-level-clientartifactId> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>fastjsonartifactId> <version>1.2.76version> dependency>
配置
package com.example.demo.elasticsearch;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LipsuperElasticsearchConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS = builder.build();
}
@Bean
public RestHighLevelClient esClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
// 单个节点配置
new HttpHost("192.168.233.128", 9200, "http")));
return client;
}
}
使用
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* getStudentES
*
* @return
* @throws IOException
*/
@RequestMapping("/getStudentES")
public List getStudentES() throws IOException {
String index = "studentinfo";
//先查询是否存在
GetRequest getRequest = new GetRequest(index, "2");
GetResponse getResponse = restHighLevelClient.get(getRequest, LipsuperElasticsearchConfig.COMMON_OPTIONS);
StudentPO studentPO = JSON.parseObject(getResponse.getSourceAsString(), StudentPO.class);
if (studentPO != null) {
return Arrays.asList(studentPO);
}
//不存在则添加
List studentList = Arrays.asList(
new StudentPO() {{
setId(1L);
setName("张三");
}},
new StudentPO() {{
setId(2L);
setName("李四");
}});
// 往es中批量保存数据
BulkRequest bulkRequest = new BulkRequest();
for (StudentPO student : studentList) {
IndexRequest indexRequest = new IndexRequest(index);
indexRequest.id(student.getId().toString());
String u = JSON.toJSONString(student);
indexRequest.source(u, XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, LipsuperElasticsearchConfig.COMMON_OPTIONS);
// 可选操作
boolean b = bulk.hasFailures();
System.out.println(b);
return studentList;
}
Original: https://www.cnblogs.com/xiaoxiaoyu0707/p/15720769.html
Author: 小小渔
Title: Spring Boot 入门(十三)使用Elasticsearch
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/572280/
转载文章受原作者版权保护。转载请注明原作者出处!