国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Boot 集成 ElasticSearch:實(shí)現(xiàn)模糊查詢、批量 CRUD、排序、分頁(yè)和高亮功能

這篇具有很好參考價(jià)值的文章主要介紹了Spring Boot 集成 ElasticSearch:實(shí)現(xiàn)模糊查詢、批量 CRUD、排序、分頁(yè)和高亮功能。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

文章來(lái)源:https://blog.csdn.net/qq_52355487/article/details/123805713
Spring Boot 集成 ElasticSearch:實(shí)現(xiàn)模糊查詢、批量 CRUD、排序、分頁(yè)和高亮功能,Springboot,spring boot,elasticsearch,jenkins

一、導(dǎo)入elasticsearch依賴

在pom.xml里加入如下依賴

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

非常重要:檢查依賴版本是否與你當(dāng)前所用的版本是否一致,如果不一致,會(huì)連接失??!

Spring Boot 集成 ElasticSearch:實(shí)現(xiàn)模糊查詢、批量 CRUD、排序、分頁(yè)和高亮功能,Springboot,spring boot,elasticsearch,jenkins

二、創(chuàng)建高級(jí)客戶端

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("服務(wù)器IP", 9200, "http")));
        return client;
    }
}

三、基本用法

1.創(chuàng)建、判斷存在、刪除索引

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class ElasticsearchApplicationTests {

 @Autowired
 private RestHighLevelClient restHighLevelClient;

 @Test
 void testCreateIndex() throws IOException {
  //1.創(chuàng)建索引請(qǐng)求
  CreateIndexRequest request = new CreateIndexRequest("ljx666");
  //2.客戶端執(zhí)行請(qǐng)求IndicesClient,執(zhí)行create方法創(chuàng)建索引,請(qǐng)求后獲得響應(yīng)
  CreateIndexResponse response=
    restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
  System.out.println(response);
 }

 @Test
 void testExistIndex() throws IOException {
        //1.查詢索引請(qǐng)求
  GetIndexRequest request=new GetIndexRequest("ljx666");
        //2.執(zhí)行exists方法判斷是否存在
  boolean exists=restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);
  System.out.println(exists);
 }

 @Test
 void testDeleteIndex() throws IOException {
        //1.刪除索引請(qǐng)求
  DeleteIndexRequest request=new DeleteIndexRequest("ljx666");
        //執(zhí)行delete方法刪除指定索引
  AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
  System.out.println(delete.isAcknowledged());
 }

}

2.對(duì)文檔的CRUD

創(chuàng)建文檔:

注意:如果添加時(shí)不指定文檔ID,他就會(huì)隨機(jī)生成一個(gè)ID,ID唯一。

創(chuàng)建文檔時(shí)若該ID已存在,發(fā)送創(chuàng)建文檔請(qǐng)求后會(huì)更新文檔中的數(shù)據(jù)。

@Test
void testAddUser() throws IOException {
 //1.創(chuàng)建對(duì)象
 User user=new User("Go",21,new String[]{"內(nèi)卷","吃飯"});
 //2.創(chuàng)建請(qǐng)求
 IndexRequest request=new IndexRequest("ljx666");
 //3.設(shè)置規(guī)則 PUT /ljx666/_doc/1
 //設(shè)置文檔id=6,設(shè)置超時(shí)=1s等,不設(shè)置會(huì)使用默認(rèn)的
 //同時(shí)支持鏈?zhǔn)骄幊倘?request.id("6").timeout("1s");
 request.id("6");
 request.timeout("1s");

 //4.將數(shù)據(jù)放入請(qǐng)求,要將對(duì)象轉(zhuǎn)化為json格式
    //XContentType.JSON,告訴它傳的數(shù)據(jù)是JSON類型
 request.source(JSONValue.toJSONString(user), XContentType.JSON);
    
 //5.客戶端發(fā)送請(qǐng)求,獲取響應(yīng)結(jié)果
 IndexResponse indexResponse=restHighLevelClient.index(request,RequestOptions.DEFAULT);
 System.out.println(indexResponse.toString());
 System.out.println(indexResponse.status());
}

獲取文檔中的數(shù)據(jù):

@Test
void testGetUser() throws IOException {
 //1.創(chuàng)建請(qǐng)求,指定索引、文檔id
 GetRequest request=new GetRequest("ljx666","1");
 GetResponse getResponse=restHighLevelClient.get(request,RequestOptions.DEFAULT);
  
 System.out.println(getResponse);//獲取響應(yīng)結(jié)果
 //getResponse.getSource() 返回的是Map集合
 System.out.println(getResponse.getSourceAsString());//獲取響應(yīng)結(jié)果source中內(nèi)容,轉(zhuǎn)化為字符串
  
}

更新文檔數(shù)據(jù):

注意:需要將User對(duì)象中的屬性全部指定值,不然會(huì)被設(shè)置為空,如User只設(shè)置了名稱,那么只有名稱會(huì)被修改成功,其他會(huì)被修改為null。

@Test
void testUpdateUser() throws IOException {
 //1.創(chuàng)建請(qǐng)求,指定索引、文檔id
 UpdateRequest request=new UpdateRequest("ljx666","6");

 User user =new User("GoGo",21,new String[]{"內(nèi)卷","吃飯"});
 //將創(chuàng)建的對(duì)象放入文檔中
 request.doc(JSONValue.toJSONString(user),XContentType.JSON);

 UpdateResponse updateResponse=restHighLevelClient.update(request,RequestOptions.DEFAULT);
 System.out.println(updateResponse.status());//更新成功返回OK
}

刪除文檔:

@Test
void testDeleteUser() throws IOException {
 //創(chuàng)建刪除請(qǐng)求,指定要?jiǎng)h除的索引與文檔ID
 DeleteRequest request=new DeleteRequest("ljx666","6");

 DeleteResponse updateResponse=restHighLevelClient.delete(request,RequestOptions.DEFAULT);
 System.out.println(updateResponse.status());//刪除成功返回OK,沒有找到返回NOT_FOUND
}

3.批量CRUD數(shù)據(jù)

這里只列出了批量插入數(shù)據(jù),其他與此類似

注意:hasFailures()方法是返回是否失敗,即它的值為false時(shí)說(shuō)明上傳成功

@Test
void testBulkAddUser() throws IOException {
 BulkRequest bulkRequest=new BulkRequest();
 //設(shè)置超時(shí)
 bulkRequest.timeout("10s");

 ArrayList<User> list=new ArrayList<>();
 list.add(new User("Java",25,new String[]{"內(nèi)卷"}));
 list.add(new User("Go",18,new String[]{"內(nèi)卷"}));
 list.add(new User("C",30,new String[]{"內(nèi)卷"}));
 list.add(new User("C++",26,new String[]{"內(nèi)卷"}));
 list.add(new User("Python",20,new String[]{"內(nèi)卷"}));

 int id=1;
 //批量處理請(qǐng)求
 for (User u :list){
  //不設(shè)置id會(huì)生成隨機(jī)id
  bulkRequest.add(new IndexRequest("ljx666")
    .id(""+(id++))
    .source(JSONValue.toJSONString(u),XContentType.JSON));
 }

 BulkResponse bulkResponse=restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
 System.out.println(bulkResponse.hasFailures());//是否執(zhí)行失敗,false為執(zhí)行成功
}

4.查詢所有、模糊查詢、分頁(yè)查詢、排序、高亮顯示

@Test
void testSearch() throws IOException {
 SearchRequest searchRequest=new SearchRequest("ljx666");//里面可以放多個(gè)索引
 SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();//構(gòu)造搜索條件

 //此處可以使用QueryBuilders工具類中的方法
 //1.查詢所有
 sourceBuilder.query(QueryBuilders.matchAllQuery());
 //2.查詢name中含有Java的
 sourceBuilder.query(QueryBuilders.multiMatchQuery("java","name"));
 //3.分頁(yè)查詢
 sourceBuilder.from(0).size(5);
    
 //4.按照score正序排列
 //sourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.ASC));
 //5.按照id倒序排列(score會(huì)失效返回NaN)
 //sourceBuilder.sort(SortBuilders.fieldSort("_id").order(SortOrder.DESC));

 //6.給指定字段加上指定高亮樣式
 HighlightBuilder highlightBuilder=new HighlightBuilder();
 highlightBuilder.field("name").preTags("<span style='color:red;'>").postTags("</span>");
 sourceBuilder.highlighter(highlightBuilder);
  
 searchRequest.source(sourceBuilder);
 SearchResponse searchResponse=restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

 //獲取總條數(shù)
 System.out.println(searchResponse.getHits().getTotalHits().value);
 //輸出結(jié)果數(shù)據(jù)(如果不設(shè)置返回條數(shù),大于10條默認(rèn)只返回10條)
 SearchHit[] hits=searchResponse.getHits().getHits();
 for(SearchHit hit :hits){
  System.out.println("分?jǐn)?shù):"+hit.getScore());
  Map<String,Object> source=hit.getSourceAsMap();
  System.out.println("index->"+hit.getIndex());
  System.out.println("id->"+hit.getId());
  for(Map.Entry<String,Object> s:source.entrySet()){
   System.out.println(s.getKey()+"--"+s.getValue());
  }
 }
}

四、總結(jié)

1.大致流程
創(chuàng)建對(duì)應(yīng)的請(qǐng)求 --> 設(shè)置請(qǐng)求(添加規(guī)則,添加數(shù)據(jù)等) --> 執(zhí)行對(duì)應(yīng)的方法(傳入請(qǐng)求,默認(rèn)請(qǐng)求選項(xiàng))–> 接收響應(yīng)結(jié)果(執(zhí)行方法返回值)–> 輸出響應(yīng)結(jié)果中需要的數(shù)據(jù)(source,status等)
2.注意事項(xiàng)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-765242.html

  • 如果不指定id,會(huì)自動(dòng)生成一個(gè)隨機(jī)id
  • 正常情況下,不應(yīng)該這樣使用new IndexRequest(“l(fā)jx777”),如果索引發(fā)生改變了,那么代碼都需要修改,可以定義一個(gè)枚舉類或者一個(gè)專門存放常量的類,將變量用final static等進(jìn)行修飾,并指定索引值。其他地方引用該常量即可,需要修改也只需修改該類即可。
  • elasticsearch相關(guān)的東西,版本都必須一致,不然會(huì)報(bào)錯(cuò)
  • elasticsearch很消耗內(nèi)存,建議在內(nèi)存較大的服務(wù)器上運(yùn)行elasticsearch,否則會(huì)因?yàn)閮?nèi)存不足導(dǎo)致elasticsearch自動(dòng)killed

到了這里,關(guān)于Spring Boot 集成 ElasticSearch:實(shí)現(xiàn)模糊查詢、批量 CRUD、排序、分頁(yè)和高亮功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring Boot Elasticsearch7.6.2實(shí)現(xiàn)創(chuàng)建索引、刪除索引、判斷索引是否存在、獲取/添加/刪除/更新索引別名、單條/批量插入、單條/批量更新、刪除數(shù)據(jù)、遞歸統(tǒng)計(jì)ES聚合的數(shù)據(jù)

    注意:我的版本是elasticsearch7.6.2、spring-boot-starter-data-elasticsearch-2.5.6 引入依賴 有時(shí)候你可能需要查詢大批量的數(shù)據(jù),建議加上下面配置文件

    2024年02月13日
    瀏覽(101)
  • Spring Boot 集成 ElasticSearch

    Spring Boot 集成 ElasticSearch

    首先創(chuàng)建一個(gè)項(xiàng)目,在項(xiàng)目中加入 ES 相關(guān)依賴,具體依賴如下所示: 在配置文件 application.properties 中配置 ES 的相關(guān)參數(shù),具體內(nèi)容如下: 其中指定了 ES 的 host 和端口以及超時(shí)時(shí)間的設(shè)置,另外我們的 ES 沒有添加任何的安全認(rèn)證,因此 username 和 password 就沒有設(shè)置。 然后在

    2024年02月03日
    瀏覽(24)
  • Spring boot簡(jiǎn)單集成Elasticsearch

    本文主要介紹Spring boot如何簡(jiǎn)單集成Elasticsearch,關(guān)于es,可以理解為一個(gè)數(shù)據(jù)庫(kù),往es中插入數(shù)據(jù),然后使用es進(jìn)行檢索。 環(huán)境準(zhǔn)備 安裝es 和kibana :參考 安裝ik分詞器:參考 相關(guān)配置 pom.xml文件中引入es: yml文件配置es: ES查詢 往es插數(shù)據(jù) 需要讓mapper層繼承ElasticsearchReposito

    2024年02月22日
    瀏覽(91)
  • Spring Boot集成Elasticsearch實(shí)戰(zhàn)

    Spring Boot集成Elasticsearch實(shí)戰(zhàn)

    最近項(xiàng)目中要使用Elasticsearch所以就去簡(jiǎn)單的學(xué)習(xí)了一下怎么使用,具體的一些在高級(jí)的功能暫時(shí)展示不了,能力目前有點(diǎn)限,不過(guò)一些基本的需求還是可以滿足的。所以就寫了一篇整理一下也希望能夠指出不足之處 docker部署 正常部署 首先根據(jù)spring提供的findAll方法獲取所有

    2024年02月09日
    瀏覽(24)
  • Spring Boot 集成 Elasticsearch 實(shí)戰(zhàn)

    Spring Boot 集成 Elasticsearch 實(shí)戰(zhàn)

    @Configuration public class ElasticsearchConfiguration { @Value(“${elasticsearch.host}”) private String host; @Value(“${elasticsearch.port}”) private int port; @Value(“${elasticsearch.connTimeout}”) private int connTimeout; @Value(“${elasticsearch.socketTimeout}”) private int socketTimeout; @Value(“${elasticsearch.connectionRequestTimeout}”

    2024年04月10日
    瀏覽(32)
  • Java實(shí)戰(zhàn):SpringBoot+ElasticSearch 實(shí)現(xiàn)模糊查詢

    本文將詳細(xì)介紹如何使用SpringBoot整合ElasticSearch,實(shí)現(xiàn)模糊查詢、批量CRUD、排序、分頁(yè)和高亮功能。我們將深入探討ElasticSearch的相關(guān)概念和技術(shù)細(xì)節(jié),以及如何使用SpringData Elasticsearch庫(kù)簡(jiǎn)化開發(fā)過(guò)程。 ElasticSearch是一個(gè)基于Lucene構(gòu)建的開源搜索引擎,它提供了一個(gè)分布式、多

    2024年04月25日
    瀏覽(22)
  • ElasticSearch入門:使用ES來(lái)實(shí)現(xiàn)模糊查詢功能

    本文針對(duì)在工作中遇到的需求:通過(guò)es來(lái)實(shí)現(xiàn) 模糊查詢 來(lái)進(jìn)行總結(jié);模糊查詢的具體需求是:查詢基金/A股/港股等金融數(shù)據(jù),要求可以根據(jù) 字段 , 拼音首字母 , 部分拼音全稱 進(jìn)行聯(lián)想查詢;需要注意的是,金融數(shù)據(jù)名稱中可能不止包含漢字,還有英文,數(shù)字,特殊字符等

    2023年04月09日
    瀏覽(23)
  • Elasticsearch實(shí)現(xiàn)對(duì)同一字段既能精準(zhǔn)查詢也能模糊查詢

    Elasticsearch實(shí)現(xiàn)對(duì)同一字段既能精準(zhǔn)查詢也能模糊查詢

    ?使用@MultiField注解給字段取別名并設(shè)置為keyword類型 dao層如下 實(shí)體類如下 模糊查詢測(cè)試如下: 可以看到模糊查詢content中一共有3條數(shù)據(jù)有我這個(gè)分詞 ?精準(zhǔn)查詢?nèi)缦拢??可以看到精準(zhǔn)查詢就只有一條結(jié)果,符合精準(zhǔn)查詢。 注意:該方法需要版本支持,具體版本未知,但是在

    2024年02月02日
    瀏覽(19)
  • spring boot集成Elasticsearch-SpringBoot(25)

    spring boot集成Elasticsearch-SpringBoot(25)

    ??搜索引擎(search engine )通常意義上是指:根據(jù)特定策略,運(yùn)用特定的爬蟲程序從互聯(lián)網(wǎng)上搜集信息,然后對(duì)信息進(jìn)行處理后,為用戶提供檢索服務(wù),將檢索到的相關(guān)信息展示給用戶的系統(tǒng)。 ??而我們講解的是捜索的索引和檢索,不涉及爬蟲程序的內(nèi)容爬取。大部分公司

    2023年04月09日
    瀏覽(24)
  • spring boot集成mybatis-plus——Mybatis Plus 批量 Insert_新增數(shù)據(jù)(圖文講解)

    spring boot集成mybatis-plus——Mybatis Plus 批量 Insert_新增數(shù)據(jù)(圖文講解)

    ?更新時(shí)間 2023-01-10 16:02:58 大家好,我是小哈。 本小節(jié)中,我們將學(xué)習(xí)如何通過(guò) Mybatis Plus 實(shí)現(xiàn) MySQL 批量插入數(shù)據(jù)。 先拋出一個(gè)問(wèn)題:假設(shè)老板給你下了個(gè)任務(wù),向數(shù)據(jù)庫(kù)中添加 100 萬(wàn)條數(shù)據(jù),并且不能耗時(shí)太久! 通常來(lái)說(shuō),我們向 MySQL 中新增一條記錄,SQL 語(yǔ)句類似如下:

    2024年02月04日
    瀏覽(28)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包