做网站维护有前途吗,淄博建网站,建设银行网站招聘官网,营销型网站建设网站建设资讯ES官方提供了各种不同语言的客户端#xff0c;用来操作ES。这些客户端的本质就是组装DSL语句#xff0c;通过http请求发送给ES。官方文档地址#xff1a;Elasticsearch Clients | Elastic
初始化RestClient
引入es的RestHighLevelClient依赖#xff1a;
dependency用来操作ES。这些客户端的本质就是组装DSL语句通过http请求发送给ES。官方文档地址Elasticsearch Clients | Elastic
初始化RestClient
引入es的RestHighLevelClient依赖
dependencygroupIdorg.elasticsearch.client/groupIdartifactIdelasticsearch-rest-high-level-client/artifactId
/dependency
因为SpringBoot默认的ES版本是7.6.2所以我们需要覆盖默认的ES版本
propertiesjava.version1.8/java.versionelasticsearch.version7.12.1/elasticsearch.version
/properties
初始化RestHighLevelClient
RestHighLevelClient client new RestHighLevelClient(RestClient.builder(HttpHost.create(http://192.168.150.101:9200)
));
创建索引库 1创建Request对象。因为是创建索引库的操作因此Request是CreateIndexRequest。 2添加请求参数其实就是DSL的JSON参数部分。因为json字符串很长这里是定义了静态字符串常量MAPPING_TEMPLATE让代码看起来更加优雅。 3发送请求client.indices()方法的返回值是IndicesClient类型封装了所有与索引库操作有关的方法。
Test
void createHotelIndex() throws IOException {// 1.创建Request对象CreateIndexRequest request new CreateIndexRequest(hotel);// 2.准备请求的参数DSL语句request.source(MAPPING_TEMPLATE, XContentType.JSON);// 3.发送请求client.indices().create(request, RequestOptions.DEFAULT);
} 删除索引库 1创建Request对象。这次是DeleteIndexRequest对象 2准备参数。这里是无参 3发送请求。改用delete方法
Test
void testDeleteHotelIndex() throws IOException {// 1.创建Request对象DeleteIndexRequest request new DeleteIndexRequest(hotel);// 2.发送请求client.indices().delete(request, RequestOptions.DEFAULT);
}
判断索引库是否存在 1创建Request对象。这次是GetIndexRequest对象 2准备参数。这里是无参 3发送请求。改用exists方法
Test
void testExistsHotelIndex() throws IOException {// 1.创建Request对象GetIndexRequest request new GetIndexRequest(hotel);// 2.发送请求boolean exists client.indices().exists(request, RequestOptions.DEFAULT);// 3.输出System.err.println(exists ? 索引库已经存在 : 索引库不存在);
} 总结
JavaRestClient操作elasticsearch的流程基本类似。核心是client.indices()方法来获取索引库的操作对象。
索引库操作的基本步骤 初始化RestHighLevelClient 创建XxxIndexRequest。XXX是Create、Get、Delete 准备DSL Create时需要其它是无参 发送请求。调用RestHighLevelClient#indices().xxx()方法xxx是create、exists、delete