当前位置:首页 > 科技  > 软件

ElasticSearch Java API只需十招,轻松掌握变专家!

来源: 责编: 时间:2023-10-10 18:31:07 345观看
导读环境:springboot2.4.12 + elasticsearch7.8.0 Elasticsearch是一种开源的、分布式的、实时的搜索和分析引擎。它允许你存储,搜索和分析大量数据,通常用于为网站或应用程序提供强大的搜索功能。 Java API是Elas

环境:springboot2.4.12 + elasticsearch7.8.0Y9D28资讯网——每日最新资讯28at.com

      Elasticsearch是一种开源的、分布式的、实时的搜索和分析引擎。它允许你存储,搜索和分析大量数据,通常用于为网站或应用程序提供强大的搜索功能。Y9D28资讯网——每日最新资讯28at.com

      Java API是Elasticsearch提供的官方客户端,它允许Java开发者轻松地与Elasticsearch服务器进行交互。下面是一些关于如何使用Java API来调用Elasticsearch的常用方法。Y9D28资讯网——每日最新资讯28at.com

注意:这里为了方便使用springboot项目(避免还要单独引用其它包)Y9D28资讯网——每日最新资讯28at.com

相关依赖

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId></dependency><dependency>  <groupId>org.elasticsearch</groupId>  <artifactId>elasticsearch</artifactId>  <version>7.8.0</version><!--$NO-MVN-MAN-VER$--></dependency><dependency>  <groupId>org.elasticsearch.client</groupId>  <artifactId>elasticsearch-rest-high-level-client</artifactId>  <version>7.8.0</version><!--$NO-MVN-MAN-VER$--></dependency>

索引操作

高级别的Rest客户端对象Y9D28资讯网——每日最新资讯28at.com

private static RestHighLevelClient client =   new RestHighLevelClient(RestClient.builder(    new HttpHost("localhost", 9200, "http"))) ;

1. 创建索引

public static void createIndex(String index) throws Exception {  CreateIndexRequest request = new CreateIndexRequest(index) ;  CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT) ;  boolean ack = response.isAcknowledged() ;  System.out.println("ack = " + ack) ;}

2. 查看索引

public static void viewIndex(String index) throws Exception {  GetIndexRequest request = new GetIndexRequest(index) ;  GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT) ;  System.out.println("aliases: " + response.getAliases() + "/n"    + "mappings: " + response.getMappings() + "/n"    + "settings: " + response.getSettings()) ;}

3. 删除索引

public static void deleteIndex(String index) throws Exception {  DeleteIndexRequest request = new DeleteIndexRequest(index) ;  AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT) ;  System.out.println("ack: " + response.isAcknowledged()) ;}

文档操作

private static RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))) ;

1. 创建文档

public static void createDoc(String index, Users users) throws Exception {  IndexRequest request = new IndexRequest() ;  // 设置索引及唯一标识  request.index(index).id("1001") ;  ObjectMapper objectMapper = new ObjectMapper() ;  String jsonString = objectMapper.writeValueAsString(users) ;  // 添加文档数据及数据格式  request.source(jsonString, XContentType.JSON) ;  IndexResponse response = client.index(request, RequestOptions.DEFAULT) ;  System.out.println("_index: " + response.getIndex() + "/n"      + "_id: " + response.getId() + "/n"      + "_result: " + response.getResult()) ;}

2. 更新文档

public static void updateDoc(String index, String id) throws Exception {  UpdateRequest request = new UpdateRequest() ;  // 配置修改参数  request.index(index).id(id) ;  Map<String, Object> source = new HashMap<>() ;  source.put("sex", "女") ;  request.doc(source, XContentType.JSON) ;  UpdateResponse response = client.update(request, RequestOptions.DEFAULT) ;  System.out.println("_index: " + response.getIndex() + "/n"      + "_id: " + response.getId() + "/n"      + "_result: " + response.getResult()) ;}

3. 查询文档

public static void viewDoc(String index, String id) throws Exception {  GetRequest request = new GetRequest().index(index).id(id) ;  GetResponse response = client.get(request, RequestOptions.DEFAULT) ;  System.out.println("_index: " + response.getIndex() + "/n"      + "_type: " + response.getType() + "/n"      + "_id: " + response.getId() + "/n"      + "source: " + response.getSourceAsString()) ;}

4. 删除文档

public static void deleteIndex(String index, String id) throws Exception {  DeleteRequest request = new DeleteRequest().index(index).id(id) ;  DeleteResponse response = client.delete(request, RequestOptions.DEFAULT) ;  System.out.println(response.toString()) ;}

5. 批量操作

public static void batchOperator(String index) throws Exception {  BulkRequest request = new BulkRequest() ;  request.add(new IndexRequest().index(index).id("1002").source(XContentType.JSON, "name","老六", "sex", "男", "age", 20)) ;  request.add(new IndexRequest().index(index).id("1003").source(XContentType.JSON, "name","外网", "sex", "女", "age", 10)) ;  request.add(new IndexRequest().index(index).id("1004").source(XContentType.JSON, "name","莉莉", "sex", "女", "age", 35)) ;  BulkResponse response = client.bulk(request, RequestOptions.DEFAULT) ;  System.out.println("took: " + response.getTook() + "/n"      + "items: " + new ObjectMapper().writeValueAsString(response.getItems())) ;}

6. 高级查询

public static void highSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.matchAllQuery()) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }}

7. term精确查询

public static void highTermSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.termQuery("age", "20")) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }}

8. 分页查询

public static void highPagingSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.matchAllQuery()) ;  builder.from(1) ;  builder.size(2) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }}

9. 分页&排序查询

public static void highPagingAndSortSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.matchAllQuery()) ;  builder.from(0) ;  builder.size(20) ;  builder.sort("age", SortOrder.ASC) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }}

10. 分页&排序&过滤字段查询

public static void highPagingAndSortAndFilterFieldSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.matchAllQuery()) ;  builder.from(0) ;  builder.size(20) ;  builder.sort("age", SortOrder.ASC) ;  String[] includes = {"name"} ;  String[] excludes = {} ;  builder.fetchSource(includes, excludes) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }}

11. 范围查询

public static void highBoolSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.matchAllQuery()) ;  builder.from(0) ;  builder.size(20) ;  builder.sort("age", SortOrder.ASC) ;  RangeQueryBuilder rangeBuilder = QueryBuilders.rangeQuery("age");  rangeBuilder.gte(15) ;  rangeBuilder.lte(30) ;  builder.query(rangeBuilder) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }}

12. 高亮查询

public static void highHighLightSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.query(QueryBuilders.matchQuery("name", "莉莉")) ;  HighlightBuilder highLightBuilder = new HighlightBuilder() ;  highLightBuilder.preTags("<font color='red'>") ;  highLightBuilder.postTags("</font>") ;  highLightBuilder.field("name") ;  builder.highlighter(highLightBuilder) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString() + "/n"        + "highlight: " + hit.getHighlightFields()) ;  }}

13. 聚合查询

public static void highAggsSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.aggregation(AggregationBuilders.avg("avg_age").field("age")) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString())  ;  }  System.out.println(((ParsedAvg)response.getAggregations().iterator().next()).getValue()) ;}

14. 分组统计

public static void highGroupSearch(String index) throws Exception {  SearchRequest request = new SearchRequest().indices(index) ;  SearchSourceBuilder builder = new SearchSourceBuilder() ;  builder.aggregation(AggregationBuilders.terms("age_groupby").field("age")) ;  request.source(builder) ;  SearchResponse response = client.search(request, RequestOptions.DEFAULT) ;  SearchHits hits = response.getHits() ;  System.out.println("took: " + response.getTook() + "/n"      + "timeout: " + response.isTimedOut() + "/n"      + "total: " + hits.getTotalHits() + "/n"      + "MaxScore: " + hits.getMaxScore()) ;  for (SearchHit hit : hits) {    System.out.println(hit.getSourceAsString()) ;  }  System.out.println(response) ;}

完毕!!!Y9D28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-12707-0.htmlElasticSearch Java API只需十招,轻松掌握变专家!

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 十个优秀的编程范式,你已经用过了几个?

下一篇: Java String类为什么用final修饰

标签:
  • 热门焦点
  • 轿车从天而降电动车主被撞身亡 超速抢道所致:现场视频让网友吵翻

    近日,上海青浦区法院判决轿车从天而降电动车主被撞身亡案,轿车车主被判有期徒刑一年。案件显示当时男子驾驶轿车在上海某路段行驶,前车忽然转弯提速超车,
  • K6:面向开发人员的现代负载测试工具

    K6 是一个开源负载测试工具,可以轻松编写、运行和分析性能测试。它建立在 Go 和 JavaScript 之上,它被设计为功能强大、可扩展且易于使用。k6 可用于测试各种应用程序,包括 Web
  • 如何通过Python线程池实现异步编程?

    线程池的概念和基本原理线程池是一种并发处理机制,它可以在程序启动时创建一组线程,并将它们置于等待任务的状态。当任务到达时,线程池中的某个线程会被唤醒并执行任务,执行完任
  • 三言两语说透柯里化和反柯里化

    JavaScript中的柯里化(Currying)和反柯里化(Uncurrying)是两种很有用的技术,可以帮助我们写出更加优雅、泛用的函数。本文将首先介绍柯里化和反柯里化的概念、实现原理和应用
  • JavaScript学习 -AES加密算法

    引言在当今数字化时代,前端应用程序扮演着重要角色,用户的敏感数据经常在前端进行加密和解密操作。然而,这样的操作在网络传输和存储中可能会受到恶意攻击的威胁。为了确保数据
  • 三分钟白话RocketMQ系列—— 如何发送消息

    我们知道RocketMQ主要分为消息 生产、存储(消息堆积)、消费 三大块领域。那接下来,我们白话一下,RocketMQ是如何发送消息的,揭秘消息生产全过程。注意,如果白话中不小心提到相关代
  • 为什么你不应该使用Div作为可点击元素

    按钮是为任何网络应用程序提供交互性的最常见方式。但我们经常倾向于使用其他HTML元素,如 div span 等作为 clickable 元素。但通过这样做,我们错过了许多内置浏览器的功能。
  • “又被陈思诚骗了”

    作者|张思齐 出品|众面(ID:ZhongMian_ZM)如今的国产悬疑电影,成了陈思诚的天下。最近大爆电影《消失的她》票房突破30亿断层夺魁暑期档,陈思诚再度风头无两。你可以说陈思诚的
  • 华为HarmonyOS 4升级计划公布:首批34款机型今日开启公测

    8月4日消息,今天下午华为正式发布了HarmonyOS 4系统,在更流畅的前提下,还带来了不少新功能,UI设计也有变化,会让手机焕然一新。华为宣布,首批机型将会在
Top