ElasticSearch Java API 基本操作

铁佛  金牌会员 | 2023-11-7 13:49:26 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 906|帖子 906|积分 2718

前言

ElasticSearch Java API是ES官方在8.x版本推出的新java api,也可以适用于7.17.x版本的es。
本文主要参考了相关博文,自己手动编写了下相关操作代码,包括更新mappings等操作的java代码。
代码示例已上传github
版本


  • elasticsearch版本:7.17.9,修改/elasticsearch-7.17.9/config/elasticsearch.yml,新增一行配置:xpack.security.enabled: false,避免提示
  • cerebro版本:0.8.5(浏览器连接es工具)
  • jdk版本:11
  • elasticsearch-java版本:
  1. <dependency>  
  2.     <groupId>co.elastic.clients</groupId>  
  3.     <artifactId>elasticsearch-java</artifactId>  
  4.     <version>7.17.9</version>  
  5. </dependency>  
  6.   
  7. <dependency>  
  8.     <groupId>com.fasterxml.jackson.core</groupId>  
  9.     <artifactId>jackson-databind</artifactId>  
  10.     <version>2.12.3</version>  
  11. </dependency>
复制代码
连接
  1. public static ElasticsearchClient getEsClient(String serverUrl) throws IOException {  
  2.     RestClient restClient = RestClient.builder(HttpHost.create(serverUrl)).build();  
  3.     ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());  
  4.     ElasticsearchClient esClient = new ElasticsearchClient(transport);  
  5.     log.info("{}", esClient.info());  
  6.     return esClient;  
  7. }
复制代码
索引

创建索引
  1. public static void createIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
  2.     if (existsIndex(esClient, indexName)) {  
  3.         log.info("index name: {} exists!", indexName);  
  4.     } else {  
  5.         CreateIndexResponse response = esClient.indices().create(c -> c.index(indexName));  
  6.         log.info("create index name: {}, ack: {}", indexName, response.acknowledged());  
  7.     }  
  8. }
  9. // 判断索引是否存在
  10. public static boolean existsIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
  11.     BooleanResponse exists = esClient.indices().exists(c -> c.index(indexName));  
  12.     return exists.value();  
  13. }
复制代码
查询索引
  1. public static void getIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
  2.     GetIndexResponse getIndexResponse = esClient.indices().get(s -> s.index(indexName));  
  3.     Map<String, IndexState> result = getIndexResponse.result();  
  4.     result.forEach((k, v) -> log.info("get index key: {}, value= {}", k, v));  
  5.   
  6.     // 查看全部索引  
  7.     IndicesResponse indicesResponse = esClient.cat().indices();  
  8.     indicesResponse.valueBody().forEach(i ->  
  9.             log.info("get all index, health: {}, status: {}, uuid: {}", i.health(), i.status(), i.uuid()));  
  10. }
复制代码
删除索引
  1. public static void delIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
  2.     if (existsIndex(esClient, indexName)) {  
  3.         log.info("index: {} exists!", indexName);  
  4.         DeleteIndexResponse deleteIndexResponse = esClient.indices().delete(s -> s.index(indexName));  
  5.         log.info("删除索引操作结果:{}", deleteIndexResponse.acknowledged());  
  6.     } else {  
  7.         log.info("index: {} not found!", indexName);  
  8.     }  
  9. }
复制代码
更新Mappings
  1. public static void updateMappings(ElasticsearchClient esClient, String indexName, Map<String, Property> documentMap) throws IOException {  
  2.     PutMappingRequest putMappingRequest = PutMappingRequest.of(m -> m.index(indexName).properties(documentMap));  
  3.     PutMappingResponse putMappingResponse = esClient.indices().putMapping(putMappingRequest);  
  4.     boolean acknowledged = putMappingResponse.acknowledged();  
  5.     log.info("update mappings ack: {}", acknowledged);  
  6. }
复制代码
使用更新Mappings方法
  1. @Test  
  2. public void updateMappingsTest() throws IOException {  
  3.     Map<String, Property> documentMap = new HashMap<>();  
  4.     documentMap.put("name", Property.of(p -> p.text(TextProperty.of(t -> t.index(true)))));  
  5.     documentMap.put("location", Property.of(p -> p.geoPoint(GeoPointProperty.of(g -> g.ignoreZValue(true)))));  
  6.     // index 设置为 true,才可以使用 search range 功能  
  7.     documentMap.put("age", Property.of(p -> p.integer(IntegerNumberProperty.of(i -> i.index(true)))));  
  8.     EsUtils.updateMappings(esClient, indexName, documentMap);  
  9. }
复制代码
文档操作

实体类
  1. @Data  
  2. public class Product {  
  3.     private String id;  
  4.     private String name;  
  5.     private String location;  
  6.     private Integer age;  
  7.     private String polygon;
  8. }
复制代码
新增
  1. public static void addOneDocument(ElasticsearchClient esClient, String indexName, Product product) throws IOException {  
  2.     IndexResponse indexResponse = esClient.index(i -> i.index(indexName).id(product.getId()).document(product));  
  3.     log.info("add one document result: {}", indexResponse.result().jsonValue());  
  4. }
复制代码
批量新增
  1. public static void batchAddDocument(ElasticsearchClient esClient, String indexName, List<Product> products) throws IOException {  
  2.     List<BulkOperation> bulkOperations = new ArrayList<>();  
  3.     products.forEach(p -> bulkOperations.add(BulkOperation.of(b -> b.index(c -> c.id(p.getId()).document(p)))));  
  4.     BulkResponse bulkResponse = esClient.bulk(s -> s.index(indexName).operations(bulkOperations));  
  5.     bulkResponse.items().forEach(b -> log.info("bulk response result = {}", b.result()));  
  6.     log.error("bulk response.error() = {}", bulkResponse.errors());  
  7. }
复制代码
查询
  1. public static void getDocument(ElasticsearchClient esClient, String indexName, String id) throws IOException {  
  2.     GetResponse<Product> getResponse = esClient.get(s -> s.index(indexName).id(id), Product.class);  
  3.     if (getResponse.found()) {  
  4.         Product source = getResponse.source();  
  5.         log.info("get response: {}", source);  
  6.     }  
  7.     // 判断文档是否存在  
  8.     BooleanResponse booleanResponse = esClient.exists(s -> s.index(indexName).id(id));  
  9.     log.info("文档id:{},是否存在:{}", id, booleanResponse.value());  
  10. }
复制代码
更新
  1. public static void updateDocument(ElasticsearchClient esClient, String indexName, Product product) throws IOException {  
  2.     UpdateResponse<Product> updateResponse = esClient.update(s -> s.index(indexName).id(product.getId()).doc(product), Product.class);  
  3.     log.info("update doc result: {}", updateResponse.result());  
  4. }
复制代码
删除
  1. public static void deleteDocument(ElasticsearchClient esClient, String indexName, String id) {  
  2.     try {  
  3.         DeleteResponse deleteResponse = esClient.delete(s -> s.index(indexName).id(id));  
  4.         log.info("del doc result: {}", deleteResponse.result());  
  5.     } catch (IOException e) {  
  6.         log.error("del doc failed, error: ", e);  
  7.     }  
  8. }
复制代码
批量删除
  1. public static void batchDeleteDocument(ElasticsearchClient esClient, String indexName, List<String> ids) {  
  2.     List<BulkOperation> bulkOperations = new ArrayList<>();  
  3.     ids.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.delete(c -> c.id(a)))));  
  4.     try {  
  5.         BulkResponse bulkResponse = esClient.bulk(a -> a.index(indexName).operations(bulkOperations));  
  6.         bulkResponse.items().forEach(a -> log.info("batch del result: {}", a.result()));  
  7.         log.error("batch del bulk resp errors: {}", bulkResponse.errors());  
  8.     } catch (IOException e) {  
  9.         log.error("batch del doc failed, error: ", e);  
  10.     }  
  11. }
复制代码
搜索

单个搜索
  1. public static void searchOne(ElasticsearchClient esClient, String indexName, String searchText) throws IOException {  
  2.     SearchResponse<Product> searchResponse = esClient.search(s -> s  
  3.             .index(indexName)  
  4.             // 搜索请求的查询部分(搜索请求也可以有其他组件,如聚合)  
  5.             .query(q -> q  
  6.                     // 在众多可用的查询变体中选择一个。我们在这里选择匹配查询(全文搜索)  
  7.                     .match(t -> t  
  8.                             .field("name")  
  9.                             .query(searchText))), Product.class);  
  10.     TotalHits total = searchResponse.hits().total();  
  11.     boolean isExactResult = total != null && total.relation() == TotalHitsRelation.Eq;  
  12.     if (isExactResult) {  
  13.         log.info("search has: {} results", total.value());  
  14.     } else {  
  15.         log.info("search more than : {} results", total.value());  
  16.     }  
  17.     List<Hit<Product>> hits = searchResponse.hits().hits();  
  18.     for (Hit<Product> hit : hits) {  
  19.         Product source = hit.source();  
  20.         log.info("Found result: {}", source);  
  21.     }  
  22. }
复制代码
分页搜索
  1. public static void searchPage(ElasticsearchClient esClient, String indexName, String searchText) throws IOException {  
  2.     Query query = RangeQuery.of(r -> r  
  3.                     .field("age")  
  4.                     .gte(JsonData.of(8)))  
  5.             ._toQuery();  
  6.   
  7.     SearchResponse<Product> searchResponse = esClient.search(s -> s  
  8.                     .index(indexName)  
  9.                     .query(q -> q  
  10.                             .bool(b -> b.must(query)))  
  11.                     // 分页查询,从第0页开始查询四个doc  
  12.                     .from(0)  
  13.                     .size(4)  
  14.                     // 按id降序排列  
  15.                     .sort(f -> f  
  16.                             .field(o -> o  
  17.                                     .field("age").order(SortOrder.Desc))),  
  18.             Product.class);  
  19.     List<Hit<Product>> hits = searchResponse.hits().hits();  
  20.     for (Hit<Product> hit : hits) {  
  21.         Product product = hit.source();  
  22.         log.info("search page result: {}", product);  
  23.     }  
  24. }
复制代码
参考


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

铁佛

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表