本文已参与「新人创作礼」活动,一起开启掘金创作之路。 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" : "张铁蛋"
}
}
]
}
}
保存成功