maven
<!--elasticsearch--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </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<StudentPO> 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<StudentPO> 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; }