日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

ElasticSearch Java API只需十招,輕松掌握變專家!

來源: 責編: 時間:2023-10-10 18:31:07 227觀看
導讀環境:springboot2.4.12 + elasticsearch7.8.0 Elasticsearch是一種開源的、分布式的、實時的搜索和分析引擎。它允許你存儲,搜索和分析大量數據,通常用于為網站或應用程序提供強大的搜索功能。 Java API是Elas

環境:springboot2.4.12 + elasticsearch7.8.0OV528資訊網——每日最新資訊28at.com

      Elasticsearch是一種開源的、分布式的、實時的搜索和分析引擎。它允許你存儲,搜索和分析大量數據,通常用于為網站或應用程序提供強大的搜索功能。OV528資訊網——每日最新資訊28at.com

      Java API是Elasticsearch提供的官方客戶端,它允許Java開發者輕松地與Elasticsearch服務器進行交互。下面是一些關于如何使用Java API來調用Elasticsearch的常用方法。OV528資訊網——每日最新資訊28at.com

注意:這里為了方便使用springboot項目(避免還要單獨引用其它包)OV528資訊網——每日最新資訊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客戶端對象OV528資訊網——每日最新資訊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) ;}

完畢!!!OV528資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-12707-0.htmlElasticSearch Java API只需十招,輕松掌握變專家!

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 十個優秀的編程范式,你已經用過了幾個?

下一篇: Java String類為什么用final修飾

標簽:
  • 熱門焦點
  • vivo TWS Air開箱體驗:真輕 臻好聽

    在vivo S15系列新機的發布會上,vivo的最新款真無線藍牙耳機vivo TWS Air也一同發布,本次就這款耳機新品給大家帶來一個簡單的分享。外包裝盒上,vivo TWS Air保持了vivo自家產
  • 十個可以手動編寫的 JavaScript 數組 API

    JavaScript 中有很多API,使用得當,會很方便,省力不少。 你知道它的原理嗎? 今天這篇文章,我們將對它們進行一次小總結。現在開始吧。1.forEach()forEach()用于遍歷數組接收一參
  • 微信語音大揭秘:為什么禁止轉發?

    大家好,我是你們的小米。今天,我要和大家聊一個有趣的話題:為什么微信語音不可以轉發?這是一個我們經常在日常使用中遇到的問題,也是一個讓很多人好奇的問題。讓我們一起來揭開這
  • JVM優化:實戰OutOfMemoryError異常

    一、Java堆溢出堆內存中主要存放對象、數組等,只要不斷地創建這些對象,并且保證 GC Roots 到對象之間有可達路徑來避免垃 圾收集回收機制清除這些對象,當這些對象所占空間超過
  • 破圈是B站頭上的緊箍咒

    來源 | 光子星球撰文 | 吳坤諺編輯 | 吳先之每年的暑期檔都少不了瞄準追劇女孩們的古偶劇集,2021年有優酷的《山河令》,2022年有愛奇藝的《蒼蘭訣》,今年卻輪到小破站抓住了追
  • 10天營收超1億美元,《星鐵》比《原神》差在哪?

    來源:伯虎財經作者:陳平安即便你沒玩過《原神》,你一定聽說過的它的大名。恨它的人把《原神》開服那天稱作是中國游戲史上最黑暗的一天,有粉絲因為索尼在PS平臺上線《原神》,怒而
  • 大廠卷向扁平化

    來源:新熵作者丨南枝 編輯丨月見大廠職級不香了。俗話說,兵無常勢,水無常形,互聯網企業調整職級體系并不稀奇。7月13日,淘寶天貓集團啟動了近年來最大的人力制度改革,目前已形成一
  • 三星Galaxy Z Fold5官方渲染圖曝光:13.4mm折疊厚度依舊感人

    據官方此前宣布,三星將于7月26日在韓國首爾舉辦Unpacked活動,屆時將帶來帶來包括Galaxy Buds 3、Galaxy Watch 6、Galaxy Tab S9、Galaxy Z Flip 5、
  • 2022爆款:ROG魔霸6 冰川散熱系統持續護航

    喜逢開學季,各大商家開始推出自己的新產品,進行打折促銷活動。對于忠實的端游愛好者來說,能夠擁有一款夢寐以求的筆記本電腦是一件十分開心的事。但是現在的
Top 主站蜘蛛池模板: 通榆县| 福清市| 咸阳市| 浮梁县| 兴化市| 高邑县| 蓬安县| 英超| 应用必备| 行唐县| 遵化市| 吉木乃县| 岳阳市| 长白| 新丰县| 乌兰县| 牡丹江市| 井陉县| 渝中区| 罗甸县| 兴和县| 商丘市| 互助| 汉寿县| 高清| 灵石县| 扎囊县| 临猗县| 田东县| 普兰店市| 清镇市| 保靖县| 云和县| 平定县| 吴江市| 双桥区| 靖远县| 双柏县| 东乌珠穆沁旗| 淅川县| 华蓥市|