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

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

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

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

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

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

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

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

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

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

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

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

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

標簽:
  • 熱門焦點
  • 8月總票房已突破10億!《封神》第一:口碑已經成了

    8月5日消息,據燈塔專業版數據,截至8月5日9時35分,8月總票房(含預售)已突破10億。其中,《封神》以大比分的優勢領先。根據官方消息,目前該片總票房已經超過14.
  • 十個可以手動編寫的 JavaScript 數組 API

    JavaScript 中有很多API,使用得當,會很方便,省力不少。 你知道它的原理嗎? 今天這篇文章,我們將對它們進行一次小總結。現在開始吧。1.forEach()forEach()用于遍歷數組接收一參
  • 不容錯過的MSBuild技巧,必備用法詳解和實踐指南

    一、MSBuild簡介MSBuild是一種基于XML的構建引擎,用于在.NET Framework和.NET Core應用程序中自動化構建過程。它是Visual Studio的構建引擎,可在命令行或其他構建工具中使用
  • 得物效率前端微應用推進過程與思考

    一、背景效率工程隨著業務的發展,組織規模的擴大,越來越多的企業開始意識到協作效率對于企業團隊的重要性,甚至是決定其在某個行業競爭中突圍的關鍵,是企業長久生存的根本。得物
  • 在線圖片編輯器,支持PSD解析、AI摳圖等

    自從我上次分享一個人開發仿造稿定設計的圖片編輯器到現在,不知不覺已過去一年時間了,期間我經歷了裁員失業、面試找工作碰壁,寒冬下一直沒有很好地履行計劃.....這些就放在日
  • 虛擬鍵盤 API 的妙用

    你是否在遇到過這樣的問題:移動設備上有一個固定元素,當激活虛擬鍵盤時,該元素被隱藏在了鍵盤下方?多年來,這一直是 Web 上的默認行為,在本文中,我們將探討這個問題、為什么會發生
  • 年輕人的“職場羞恥感”,無處不在

    作者:馮曉亭 陶 淘 李 欣 張 琳 馬舒葉來源:燃次元&ldquo;人在職場,應該選擇什么樣的著裝?&rdquo;近日,在網絡上,一個與著裝相關的帖子引發關注,在該帖子里,一位在高級寫字樓亞洲金
  • 余承東:AI大模型技術的發展將會帶來下一代智能終端操作系統的智慧體驗

    8月4日消息,2023年華為開發者大會(HDC.Together)今天正式開幕,華為發布HarmonyOS 4、全新升級的鴻蒙開發套件、HarmonyOS Next開發者預覽版本等一系列
  • 到手價3099元起!iQOO Neo8 Pro今日首銷:安卓性能最強旗艦

    5月23日,iQOO如期舉行了新品發布會,全新的iQOO Neo8系列也正式與大家見面,包含iQOO Neo8和iQOO Neo8 Pro兩個版本,其中標準版搭載高通驍龍8+,而Pro版更
Top 主站蜘蛛池模板: 三河市| 蓬安县| 京山县| 平塘县| 平罗县| 屯留县| 精河县| 密山市| 肇庆市| SHOW| 房产| 瓮安县| 盘山县| 来宾市| 科技| 南漳县| 六枝特区| 庄浪县| 永济市| 重庆市| 遂昌县| 逊克县| 香格里拉县| 绥阳县| 宜宾市| 竹溪县| 股票| 邵阳县| 达拉特旗| 汾西县| 澎湖县| 额济纳旗| 桐城市| 叶城县| 呼伦贝尔市| 嘉兴市| 台山市| 新巴尔虎左旗| 巴林右旗| 邳州市| 陆川县|