RestClient 创建索引库
再看一眼 上一篇 中 我们手写的 索引库 创建语句:
PUT /hotel
{
"mappings":{
"properties":{
"id":{
"type":"keyword"
},
"name":{
"type":"text",
"analyzer":"ik_max_word",
"copy_to": "all"
},
"address":{
"type":"keyword",
"index":false
},
"price":{
"type":"integer"
},
"score":{
"type":"integer"
},
"brand":{
"type":"keyword",
"copy_to": "all"
},
"city":{
"type":"keyword"
},
"starName":{
"type":"keyword"
},
"business":{
"type":"keyword",
"copy_to": "all"
},
"location":{
"type":"geo_point"
},
"pic":{
"type":"keyword",
"index":false
},
"all":{
"type":"text",
"analyzer":"ik_max_word"
}
}
}
}
这是手动在 kibana里面输入, 这次我用java代码的形式来创建索引库:
@Test
void createHotelIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("hotel");
request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
client.indices().create(request, RequestOptions.DEFAULT);
}
执行一下 执行成功。
到网页客户端确认一下:
{
"hotel" : {
"aliases" : { },
"mappings" : {
"properties" : {
"address" : {
"type" : "keyword",
"index" : false
},
"all" : {
"type" : "text",
"analyzer" : "ik_max_word"
},
"brand" : {
"type" : "keyword",
"copy_to" : [
"all"
]
},
"business" : {
"type" : "keyword",
"copy_to" : [
"all"
]
},
"city" : {
"type" : "keyword"
},
"id" : {
"type" : "keyword"
},
"location" : {
"type" : "geo_point"
},
"name" : {
"type" : "text",
"copy_to" : [
"all"
],
"analyzer" : "ik_max_word"
},
"pic" : {
"type" : "keyword",
"index" : false
},
"price" : {
"type" : "integer"
},
"score" : {
"type" : "integer"
},
"starName" : {
"type" : "keyword"
}
}
},
"settings" : {
"index" : {
"routing" : {
"allocation" : {
"include" : {
"_tier_preference" : "data_content"
}
}
},
"number_of_shards" : "1",
"provided_name" : "hotel",
"creation_date" : "1684447622521",
"number_of_replicas" : "1",
"uuid" : "j5jFxlRGRiCz4mhe2tpCag",
"version" : {
"created" : "7120199"
}
}
}
}
}
判断索引库是否存在
这个其实在代码里面 有时候单元测试里面 经常会遇到 所以把这个也讲一下:
代码也很简单
@Test
void HotelExist() throws IOException {
GetIndexRequest request = new GetIndexRequest("hotel");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
if (exists){
System.out.println("索引库存在");
}else {
System.out.println("索引库不存在");
}
}
在 client.indices() 里面有很多方法 创建 删除 判断存在之类的 新手可以去自己看一下 自己敲一遍。