三.SpringBoot整合Elasticsearch
前言
我们整合es直接给es发请求就可以了,但是现在有很多方式去调用es的接口,那都有那些呢?
一.java调用es的方式和工具
二.java集成Elasticsearch-Rest-Client
1.引入pom
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.3.1</version> </dependency>
2.导入版本不一致问题
比如你想导入 7.3.1版本的,但是你导入之后发现不是7.3.1版本的。 原因: 因为springboot默认对Elasticsearch版本进行了引入。
3.编写配置类
@Configuration public class EsConfig { //发送请求时的请求设置项(全局通用) public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); //通用设置 // builder.addHeader("Authorization", "Bearer " + TOKEN); // builder.setHttpAsyncResponseConsumerFactory( // new HttpAsyncResponseConsumerFactory // .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); COMMON_OPTIONS = builder.build(); } //注入 @Bean public RestHighLevelClient config(){ RestClientBuilder builder = null; //es的ip、访问的端口号、网络协议 builder = RestClient.builder(new HttpHost("127.0.0.1",9200,"http")); RestHighLevelClient client = new RestHighLevelClient(builder); return client; } }
4.测试类
@SpringBootTest @RunWith(SpringRunner.class) public class test { @Autowired RestHighLevelClient restClient; //测试从java保存数据到es @Test public void testEs() throws IOException { IndexRequest indexRequest = new IndexRequest("ikun"); indexRequest.id("1"); Kunkun kunkun = new Kunkun(); kunkun.setJineng("唱跳rap篮球"); kunkun.setName("小black子"); //把对象转为json字符串 String s = JSON.toJSONString(kunkun); //保存的数据 indexRequest.source(s, XContentType.JSON); //执行保存的操作(同步操作,文档里面有写异步请求) IndexResponse index = restClient.index(indexRequest, EsConfig.COMMON_OPTIONS); } @Data class Kunkun { private String jineng; private String name; } }