1、初始化RestClient
在elasticsearch提供的API中,与elasticsearch一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。
1)引入es的RestHighLevelClient依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
注:导入的依赖的版本要和打开的es的版本对应
2)初始化RestHighLevelClient:
//初始化RestHighLevelClient:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(HttpHost.create("http://192.168.177.132:9200"))
);
}
2、创建索引库
//初始化RestHighLevelClient:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(HttpHost.create("http://192.168.177.132:9200"))
);
//创建请求
CreateIndexRequest request = new CreateIndexRequest("hotel");
//设置参数
//HotelConstants.HOTEL_MAPPING:是封装了的json建库语句
request.source(HotelConstants.HOTEL_MAPPING, XContentType.JSON);
//执行请求
client.indices().create(request, RequestOptions.DEFAULT);
System.out.println("索引库创建完毕");
把建库的json封装
package cn.itcast.hotel.utils;
/**
* @author ning
* @since 2022/12/4 22:08
*/
public class HotelConstants {
public static final String HOTEL_MAPPING ="{\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"id\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"name\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"address\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false\n" +
" },\n" +
" \"price\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"score\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"brand\":{\n" +
" \"type\": \"keyword\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"city\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"starName\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"business\":{\n" +
" \"type\": \"keyword\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"location\":{\n" +
" \"type\": \"geo_point\"\n" +
" },\n" +
" \"pic\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false\n" +
" },\n" +
" \"all\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
}
3、删除索引库
//初始化RestHighLevelClient:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(HttpHost.create("http://192.168.177.132:9200"))
);
//创建请求
DeleteIndexRequest request = new DeleteIndexRequest("hotel");
//执行请求
client.indices().delete(request,RequestOptions.DEFAULT);
System.out.println("索引库删除完毕");
}
4、判断索引库是否存在
//初始化RestHighLevelClient:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(HttpHost.create("http://192.168.177.132:9200"))
);
//创建请求
GetIndexRequest request = new GetIndexRequest("hotel");
//执行请求
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println("索引库是否存在?" + exists);
文章来源:https://www.toymoban.com/news/detail-507873.html
文章来源地址https://www.toymoban.com/news/detail-507873.html
到了这里,关于利用JavaRestClient实现创建、删除索引库,判断索引库是否存在的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!