本文已参与「新人创作礼」活动,一起开启掘金创作之路。
Java操作elasticSearch索引保存数据
计划与实现:
存储一个新索引students,然后保存文档
借助Kibana:å
GET /students/_search
结果:
{
"error" : {
"root_cause" : [
{
"type" : "index_not_found_exception",
"reason" : "no such index [students]",
"resource.type" : "index_or_alias",
"resource.id" : "students",
"index_uuid" : "_na_",
"index" : "students"
}
],
"type" : "index_not_found_exception",
"reason" : "no such index [students]",
"resource.type" : "index_or_alias",
"resource.id" : "students",
"index_uuid" : "_na_",
"index" : "students"
},
"status" : 404
}
索引不存在
单元测试
索引数据的请求是个网络操作,所以会有异常处理。
//做一个学生对象
//注解后setter getter
@Data
class Student{
private String name;
private Integer age;
private String gender;
}
@Test
public void indexData() throws IOException {
//索引
IndexRequest indexRequest = new IndexRequest("students");
//数据id 不设置会自动生成
indexRequest.id("1");
Student student = new Student();
student.setAge(18);
student.setGender("男");
student.setName("张铁蛋");
//对象转换json
String jsonString = JSON.toJSONString(student);
//索引对象加入对象json 声明保存形式
indexRequest.source(jsonString, XContentType.JSON);
//用容器中导入的client 调用请求 索引对象 和 配置参数 这个配置参数是整合配置时搞定的
IndexResponse index = client.index(indexRequest, GuilimallElasticSearchConfig.COMMON_OPTIONS);
//index为相应数据
System.out.println(index);
}
执行:
2021-11-05 16:01:28.219 INFO 1548 --- [ main] c.a.g.s.GulimallSearchApplicationTests : Started GulimallSearchApplicationTests in 18.417 seconds (JVM running for 19.985)
IndexResponse[index=students,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
2021-11-05 16:01:32.019 INFO 1548 --- [ Thread-9] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Process finished with exit code 0
在看一下Kibana:
GET /students/_search
结果集:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "students",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"age" : 18,
"gender" : "男",
"name" : "张铁蛋"
}
}
]
}
}
保存成功
Java操作elasticSearch整合SpringBoot
针对elasticSearch不同端口操作客户端API:
1)、9300:TCP (es集群通讯9300)
· spring-data-elasticsearch:transport-api.jar;
· springboot 版本不同, transport-api.jar 不同,不能适配 es 版本
· 官网 es的版本:7.x 已经不建议使用,8 以后就要废弃
2)、9200:HTTP
· JestClient:非官方,更新慢
· RestTemplate:模拟发 HTTP 请求,ES 很多操作需要自己封装,麻烦
· HttpClient:同上 ▷ Elasticsearch-Rest-Client:官方 RestClient,封装了 ES 操作,API 层次分明,上手简单 最终选择 Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client) https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
▷Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)
整合SpringBoot
版本说明:elasticSearch版本 kibana版本 Elasticsearch-Rest-Client版本 请保持一致
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
配置: 容器中导入RestHighLevelClient 操作以及加密鉴权
**
* 1.导入依赖
* 2.容器中导入RestHighLevelClient 操作9200
*/
//注解配置启动容器自动执行
@Configuration
public class ElasticSearchConfig {
//常亮配置项 在调用es操作的时候直接引用这个常量
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();
}
//容器中引入client 调用es服务时,用这个client请求
@Bean
public RestHighLevelClient esRestClient(){
//多个es的写法
// RestHighLevelClient client = new RestHighLevelClient(
// RestClient.builder(
// //多个es new HttpHost("192.168.31.120",9200,"http"),
// new HttpHost("192.168.31.125",9200,"http")));
// return client;
RestClientBuilder builder = null;
builder = RestClient.builder(new HttpHost("192.168.31.125",9200,"http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
public void contextLoads() {
System.out.println(client);
}
}
2021-11-05 15:44:39.332 INFO 2108 --- [ main] c.a.g.s.GulimallSearchApplicationTests : Started GulimallSearchApplicationTests in 19.746 seconds (JVM running for 21.598)
org.elasticsearch.client.RestHighLevelClient@342e690b
2021-11-05 15:44:39.690 INFO 2108 --- [ Thread-9] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Process finished with exit code 0
看到client的打印信息:org.elasticsearch.client.RestHighLevelClient@342e690b
整合成功