日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

集成Springboot----ElasticSearch

發布時間:2023/12/3 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 集成Springboot----ElasticSearch 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

集成Springboot

官方文檔:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-7WO11AQr-1610955801732)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210117234918617.png)]

創建一個模塊的辦法(新)

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-hAbuuaTh-1610955801735)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210117235819775.png)]

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-mAtpbds5-1610955801739)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210118000624531.png)]

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-RbhSjz3x-1610955801742)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210118001126961.png)]

1、找到原生的依賴

<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.6.1</version> </dependency><properties><java.version>1.8</java.version><elasticsearch.version>7.6.1</elasticsearch.version></properties>

2、找對象

Initialization

A RestHighLevelClient instance needs a REST low-level client builder to be built as follows:

package com.kuang.config;import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class ElasticSearchClientConfig {@Beanpublic RestHighLevelClient restHighLevelClient(){RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"),new HttpHost("localhost", 9201, "http")));return client;} }

The high-level client will internally create the low-level client used to perform requests based on the provided builder. That low-level client maintains a pool of connections and starts some threads so you should close the high-level client when you are well and truly done with it and it will in turn close the internal low-level client to free those resources. This can be done through the close:

client.close();

In the rest of this documentation about the Java High Level Client, the RestHighLevelClient instance will be referenced as client.

3、分析類中的方法

一定要版本一致!默認es是6.8.1,要改成與本地一致的。

<properties><java.version>1.8</java.version><elasticsearch.version>7.6.1</elasticsearch.version></properties>

Java配置類

@Configuration //xml public class EsConfig {@Beanpublic RestHighLevelClient restHighLevelClient(){RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))); //媽的被這個端口搞了return client;} }

索引API操作

1、創建索引

@SpringBootTest class EsApplicationTests {@Autowired@Qualifier("restHighLevelClient")private RestHighLevelClient restHighLevelClient;//創建索引的創建 Request@Testvoid testCreateIndex() throws IOException {//1.創建索引請求CreateIndexRequest request = new CreateIndexRequest("索引名");//2.執行創建請求 indices 請求后獲得響應CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);System.out.println(createIndexResponse);}}

2、獲取索引

@Testvoid testExistIndex() throws IOException {GetIndexRequest request = new GetIndexRequest("索引名");boolean exist =restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);System.out.println(exist);}

3、刪除索引

@Testvoid deleteIndex() throws IOException{DeleteIndexRequest request = new DeleteIndexRequest("索引名");AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);System.out.println(delete.isAcknowledged());}

文檔API操作

package com.kuang.pojo;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Data @AllArgsConstructor @NoArgsConstructor @Component public class User {private String name;private int age;}

1、測試添加文檔

導入

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.16</version> </dependency> //測試添加文檔@Testvoid testAddDocument() throws IOException {//創建對象User user = new User("psz", 22);IndexRequest request = new IndexRequest("ppp");//規則 PUT /ppp/_doc/1request.id("1");request.timeout(timeValueSeconds(1));//數據放入請求IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);//客戶端發送請求,獲取響應結果IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);System.out.println(indexResponse.toString());System.out.println(indexResponse.status());}

2、獲取文檔

//獲取文檔,判斷是否存在 GET /index/doc/1@Testvoid testIsExists() throws IOException {GetRequest getRequest = new GetRequest("ppp", "1");//過濾,不放回_source上下文getRequest.fetchSourceContext(new FetchSourceContext(false));getRequest.storedFields("_none_");boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);System.out.println(exists);}

3、獲取文檔信息

//獲取文檔信息@Testvoid getDocument() throws IOException {GetRequest getRequest = new GetRequest("ppp", "1");GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);System.out.println(getResponse.getSourceAsString());System.out.println(getResponse);} ==============輸出========================== {"age":22,"name":"psz"} {"_index":"ppp","_type":"_doc","_id":"1","_version":2,"_seq_no":1,"_primary_term":1,"found":true,"_source":{"age":22,"name":"psz"}}

4、更新文檔信息

//更新文檔信息@Testvoid updateDocument() throws IOException {UpdateRequest updateRequest = new UpdateRequest("ppp","1");updateRequest.timeout("1s");//json格式傳入對象User user=new User("新名字",21);updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);//請求,得到響應UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);System.out.println(updateResponse);}

5、刪除文檔信息

//刪除文檔信息 @Test void deleteDocument() throws IOException {DeleteRequest deleteRequest = new DeleteRequest("ppp","1");deleteRequest.timeout("1s");DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);System.out.println(deleteResponse); }

批量操作Bulk

  • 真實項目中,肯定用到大批量查詢
  • 不寫id會隨機生成id

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-CS8wKFqS-1610955801744)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20210118104900129.png)]

@Testvoid testBulkRequest() throws IOException{BulkRequest bulkRequest = new BulkRequest();bulkRequest.timeout("10s");//數據量大的時候,秒數可以增加ArrayList<User> userList = new ArrayList<>();userList.add(new User("psz",11));userList.add(new User("psz2",12));userList.add(new User("psz3",13));userList.add(new User("psz4",14));userList.add(new User("psz5",15));for (int i = 0; i < userList.size(); i++) {bulkRequest.add(new IndexRequest("ppp").id(""+(i+1)).source(JSON.toJSONString(userList.get(i)),XContentType.JSON));}//請求+獲得響應BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);System.out.println(bulkResponse.hasFailures());//返回false:成功}

搜索

/*查詢:搜索請求:SearchRequest條件構造:SearchSourceBuilder*/@Testvoid testSearch() throws IOException {SearchRequest searchRequest = new SearchRequest("ppp");//構建搜索條件SearchSourceBuilder searchSourceBuilderBuilder = new SearchSourceBuilder();// 查詢條件QueryBuilders工具// :比如:精確查詢TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "psz");searchSourceBuilderBuilder.query(termQueryBuilder);//設置查詢時間searchSourceBuilderBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));//設置高亮//searchSourceBuilderBuilder.highlighter()searchRequest.source(searchSourceBuilderBuilder);SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);System.out.println(JSON.toJSONString(searchResponse.getHits()));}

總結

以上是生活随笔為你收集整理的集成Springboot----ElasticSearch的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。