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

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

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

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

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

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

注意:这里为了方便使用springboot项目(避免还要单独引用其它包)6xn28资讯网——每日最新资讯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客户端对象6xn28资讯网——每日最新资讯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) ;}

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

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

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

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

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

标签:
  • 热门焦点
  • 卢伟冰长文解析K60至尊版 对Redmi有着里程碑式的意义

    在今天的Redmi后性能时代战略发布会结束之后,Redmi总经理卢伟冰又带来了一篇长文,详解了为什么 Redmi 要开启后性能时代?为什么选择和 MediaTek、Pixelworks 深度合作?以及后性
  • 官方承诺:K60至尊版将会首批升级MIUI 15

    全新的MIUI 15今天也有了消息,在官宣了K60至尊版将会搭载天玑9200+处理器和独显芯片X7的同时,Redmi给出了官方承诺,K60至尊重大更新首批升级,会首批推送MIUI 15。也就是说虽然
  • 6月安卓手机性价比榜:Note 12 Turbo断层式碾压

    6月份有一个618,虽然这是京东周年庆的日子,但别的电商也都不约而同的跟进了,反正促销没坏处,厂商和用户都能满意。618期间一些产品也出现了历史低价,那么各个价位段的产品性价比
  • 量化指标是与非:挽救被量化指标扼杀的技术团队

    作者 | 刘新翠整理 | 徐杰承本文整理自快狗打车技术总监刘新翠在WOT2023大会上的主题分享,更多精彩内容及现场PPT,请关注51CTO技术栈公众号,发消息【WOT2023PPT】即可直接领取
  • 微信语音大揭秘:为什么禁止转发?

    大家好,我是你们的小米。今天,我要和大家聊一个有趣的话题:为什么微信语音不可以转发?这是一个我们经常在日常使用中遇到的问题,也是一个让很多人好奇的问题。让我们一起来揭开这
  • 深度探索 Elasticsearch 8.X:function_score 参数解读与实战案例分析

    在 Elasticsearch 中,function_score 可以让我们在查询的同时对搜索结果进行自定义评分。function_score 提供了一系列的参数和函数让我们可以根据需求灵活地进行设置。近期
  • 一条抖音4亿人围观 ! 这家MCN比无忧传媒还野

    作者:Hiu 来源:互联网品牌官01 擦边少女空降热搜,幕后推手曝光被网友誉为&ldquo;纯欲天花板&rdquo;的女网红井川里予,近期因为一组哥特风照片登上热搜,引发了一场互联网世界关于
  • 当家的盒马,加速谋生

    来源 | 价值星球Planet作者 | 归去来自己&ldquo;当家&rdquo;的盒马,开始加速谋生了。据盒马官微消息,盒马计划今年开放生鲜供应链,将其生鲜商品送往食堂。目前,盒马在上海已经与
  • 造车两年股价跌六成,小米的估值逻辑变了吗?

    如果从小米官宣造车后的首个交易日起持有小米集团的股票,那么截至2023年上半年最后一个交易日,投资者将浮亏59.16%,同区间的恒生科技指数跌幅为52.78%
Top