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

SpringBoot 整合ElasticSearch實(shí)現(xiàn)模糊查詢,批量CRUD,排序,分頁,高亮

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

準(zhǔn)備工作

準(zhǔn)備一個(gè)空的SpringBoot項(xiàng)目

寫入依賴

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

注意你的SpringBoot和你的es版本,一定要對應(yīng),如果不知道的可以查看這篇文章:https://blog.csdn.net/u014641168/article/details/130386872

我的版本是2.2.6,所以用的ES版本是 6.8.12,安裝es請看這篇文章:https://blog.csdn.net/u014641168/article/details/130622430
SpringBoot 整合ElasticSearch實(shí)現(xiàn)模糊查詢,批量CRUD,排序,分頁,高亮
查看ES版本
SpringBoot 整合ElasticSearch實(shí)現(xiàn)模糊查詢,批量CRUD,排序,分頁,高亮
SpringBoot 整合ElasticSearch實(shí)現(xiàn)模糊查詢,批量CRUD,排序,分頁,高亮

配置

創(chuàng)建ES配置文件,下面有2個(gè)Bean,一個(gè)是你的ES有賬號密碼的,另一個(gè)默認(rèn)是沒有的。

package cn.ityao.es.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author tongyao
 */
@Configuration
public class ElasticsearchConfig {
    @Value("${elasticsearch.port}")
    private int port;

    @Value("${elasticsearch.ip}")
    private String ip;

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    /**
     * 創(chuàng)建帶HTTP Basic Auth認(rèn)證rest客戶端
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost[]{
                    new HttpHost(ip, port, "http")
                }).setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
    }

    //不帶用戶名密碼驗(yàn)證
    //@Bean
    public RestHighLevelClient restClient() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost[]{
                new HttpHost(ip, port, "http")
        }));
    }
}

yml配置文件內(nèi)容

server:
  # 服務(wù)端口
  port: 9990

elasticsearch:
  port: 9200
  ip: 127.0.0.1
  username: elastic
  password: 123456


# 查看es信息時(shí)需要的序列化
spring:
  jackson:
    serialization:
      FAIL_ON_EMPTY_BEANS: false

注入依賴

在controller下注入依賴

@Autowired
private RestHighLevelClient restHighLevelClient;

對索引的CURD

1、創(chuàng)建索引

/**
 * 創(chuàng)建索引
 *
 * @return
 * @throws IOException
 */
@GetMapping("/createIndex")
public Object createIndex() throws IOException {
	//1.創(chuàng)建索引請求
	CreateIndexRequest request = new CreateIndexRequest("testindex");
	//2.客戶端執(zhí)行請求IndicesClient,執(zhí)行create方法創(chuàng)建索引,請求后獲得響應(yīng)
	CreateIndexResponse response =
			restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
	return response;
}

SpringBoot 整合ElasticSearch實(shí)現(xiàn)模糊查詢,批量CRUD,排序,分頁,高亮
可以看到已經(jīng)添加成功了,但是一定注意,索引名稱,一定要小寫!

2、查詢索引

/**
 * 查詢索引
 *
 * @return
 * @throws IOException
 */
@GetMapping("/searchIndex")
public Object searchIndex() throws IOException {
	//1.查詢索引請求
	GetIndexRequest request = new GetIndexRequest("testindex");
	//2.執(zhí)行exists方法判斷是否存在
	boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
	return exists;
}

3、刪除索引

/**
 * 刪除索引
 *
 * @return
 * @throws IOException
 */
@GetMapping("delIndex")
public Object delIndex() throws IOException {
	//1.刪除索引請求
	DeleteIndexRequest request = new DeleteIndexRequest("testindex");
	//執(zhí)行delete方法刪除指定索引
	AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
	return delete.isAcknowledged();
}

對文檔的CRUD

1、新增文檔

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

/**
 * 新增文檔
 *
 * @return
 * @throws IOException
 */
@GetMapping("/add")
public Object add() throws IOException {
	//1.創(chuàng)建對象
	User user = new User("張三", 21);
	//2.創(chuàng)建請求(索引的名字)
	IndexRequest request = new IndexRequest("indexdocument");
	//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");
	// 指定要寫入的 Index
	request.type("_doc");
	/*request.index("test");*/
	/*request.timeout(TimeValue.timeValueSeconds(1));*/
	request.timeout("1s");

	//4.將數(shù)據(jù)放入請求,要將對象轉(zhuǎn)化為json格式
	//XContentType.JSON,告訴它傳的數(shù)據(jù)是JSON類型
	request.source(JSON.toJSONString(user), XContentType.JSON);

	//5.客戶端發(fā)送請求,獲取響應(yīng)結(jié)果
	IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
	System.out.println(indexResponse.toString());
	System.out.println(indexResponse.status());
	return indexResponse;
}

2、查詢文檔中的數(shù)據(jù)

/**
 * 獲取文檔中的數(shù)據(jù)
 *
 * @return
 * @throws IOException
 */
@GetMapping("/get")
public Object get() throws IOException {
	//1.創(chuàng)建請求,指定索引、文檔id(索引的名字)
	GetRequest request = new GetRequest("indexdocument").id("6").type("_doc");
	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)化為字符串
	return getResponse;
}

3、更新文檔中的數(shù)據(jù)

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

/**
 * 更新文檔數(shù)據(jù)
 *
 * @return
 * @throws IOException
 */
@GetMapping("/update")
public Object update() throws IOException {
	//1.創(chuàng)建請求,指定索引、文檔id(索引的名字)
	UpdateRequest request = new UpdateRequest("indexdocument","_doc","6");

	User user = new User("小明", 21);
	//將創(chuàng)建的對象放入文檔中
	request.doc(JSON.toJSONString(user), XContentType.JSON);
	UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
	System.out.println(updateResponse.status());//更新成功返回OK
	return updateResponse;
}

3、刪除文檔中的數(shù)據(jù)

/**
 * 刪除文檔數(shù)據(jù)
 *
 * @return
 * @throws IOException
 */
@GetMapping("/delete")
public Object delete() throws IOException {
	//1.創(chuàng)建刪除文檔請求
	DeleteRequest request = new DeleteRequest("indexdocument").id("6").type("_doc");
	DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
	System.out.println(deleteResponse.status());//更新成功返回OK
	return deleteResponse;
}

4、批量新增文檔中的數(shù)據(jù)

/**
 * 批量新增文檔數(shù)據(jù)
 *
 * @return
 * @throws IOException
 */
@GetMapping("/addBatch")
public Object addBatch() throws IOException {
	BulkRequest bulkRequest = new BulkRequest();
	//設(shè)置超時(shí)
	bulkRequest.timeout("10s");

	List<User> list = new ArrayList<>();
	list.add(new User("李四", 25));
	list.add(new User("王五", 18));
	list.add(new User("趙六", 30));
	list.add(new User("田七", 26));
	list.add(new User("劉八", 20));

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

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

5、詢所有、模糊查詢、分頁查詢、排序、高亮顯示

/**
 * 復(fù)雜的es查詢
 * @return
 * @throws IOException
 */
@GetMapping("test")
public Object test() throws IOException {
	SearchRequest searchRequest = new SearchRequest("indexdocument");//里面可以放多個(gè)索引
	SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//構(gòu)造搜索條件
	//此處可以使用QueryBuilders工具類中的方法
	//1.查詢所有
	sourceBuilder.query(QueryBuilders.matchAllQuery());
	//2.查詢name中含有Java的
	sourceBuilder.query(QueryBuilders.multiMatchQuery("張三", "name"));
	//3.分頁查詢
	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());
	//輸出結(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());
		}
	}
	return searchResponse;
}

總結(jié)

1.大致流程

創(chuàng)建對應(yīng)的請求 --> 設(shè)置請求(添加規(guī)則,添加數(shù)據(jù)等) --> 執(zhí)行對應(yīng)的方法(傳入請求,默認(rèn)請求選項(xiàng))–> 接收響應(yīng)結(jié)果(執(zhí)行方法返回值)–> 輸出響應(yīng)結(jié)果中需要的數(shù)據(jù)(source,status等)

2.注意事項(xiàng)

如果不指定id,會(huì)自動(dòng)生成一個(gè)隨機(jī)id

正常情況下,不應(yīng)該這樣使用new IndexRequest(“indexName”),如果索引發(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

文章參考:https://blog.csdn.net/zhiyikeji/article/details/128902860文章來源地址http://www.zghlxwxcb.cn/news/detail-478179.html

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

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

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

相關(guān)文章

  • Java實(shí)戰(zhàn):SpringBoot+ElasticSearch 實(shí)現(xiàn)模糊查詢

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

    2024年04月25日
    瀏覽(22)
  • SpringBoot整合ElasticSearch實(shí)現(xiàn)分頁查詢

    SpringBoot整合ElasticSearch實(shí)現(xiàn)分頁查詢

    本文使用SpringBoot整合ElasticSearch實(shí)現(xiàn)分頁查詢 還是繼續(xù)使用spring-boot-starter-data-elasticsearch來實(shí)現(xiàn)分頁查詢操作 數(shù)據(jù)準(zhǔn)備 使用ElasticsearchRestTemplate來實(shí)現(xiàn) 程序結(jié)果 使用ElasticsearchOperations來實(shí)現(xiàn) 程序結(jié)果 本文記錄了SpringBoot整合ElasticSearch來實(shí)現(xiàn)分頁查詢的兩種方式

    2024年01月25日
    瀏覽(19)
  • springboot整合neo4j模糊查詢

    1.場景 查詢與content相似的實(shí)體 解決方案: 1.直接從neo4j中查詢所有實(shí)體并使用杰卡德相似度算法計(jì)算相似度,返回top n,該方案由于要匹配圖中所有實(shí)體,性能較差。 2.模糊查詢neo4j中的實(shí)體,并對查詢結(jié)果與content做相似度計(jì)算,相似度算法為hutool中的TextSimilarity.similar()接口

    2024年02月13日
    瀏覽(23)
  • springboot整合elasticsearch實(shí)現(xiàn)類似于mysql的like查詢

    目錄 一、ES分頁查詢常用方式 二、引入es的依賴 三、es配置文件 四、es工具類 五、分頁查詢示例 1.from + size from表示從第幾行開始,size表示查詢多少條文檔。from默認(rèn)為0,size默認(rèn)為10,最靈活的分頁方式。 2.scroll 不適合用來做實(shí)時(shí)搜索,而更適用于后臺(tái)批處理任務(wù),如日志導(dǎo)

    2023年04月09日
    瀏覽(19)
  • SpringBoot整合Elasticsearch實(shí)現(xiàn)分頁條件查詢及注意事項(xiàng)

    項(xiàng)目環(huán)境: springboot 2.3.7.RELEASE es 6.8.3 這里需要注意es中日期格式,ES默認(rèn)是不支持yyyy-MM-dd HH:mm:ss格式的,需要通過 @Field(type = FieldType.Date, format = DateFormat.custom,pattern = \\\"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_second\\\") 來指定日期格式。 直接看業(yè)務(wù)層實(shí)現(xiàn)分頁條件查詢: 范圍查詢: es en

    2023年04月16日
    瀏覽(20)
  • Springboot整合mybatis實(shí)現(xiàn)增刪改查(crud)

    Springboot整合mybatis實(shí)現(xiàn)增刪改查(crud)

    今天我們來學(xué)習(xí)一個(gè)Springboot案例??! 那么什么是SpringBoot技術(shù)呢? Spring Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。 該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。 Spring Boot致力于在蓬

    2024年01月22日
    瀏覽(21)
  • springboot整合elasticsearch8組合條件查詢

    整合過程見上一篇文章 springboot整合elasticsearch8 1.es8多條件組合查詢 2.使用scroll進(jìn)行大數(shù)據(jù)量查詢

    2024年02月16日
    瀏覽(19)
  • Springboot整合Elasticsearch 7.X 復(fù)雜查詢

    Springboot整合Elasticsearch 7.X 復(fù)雜查詢

    這里使用Springboot 2.7.12版本,Elasticsearch為7.15.0。 導(dǎo)入依賴 yaml文件配置: 構(gòu)建實(shí)體類,這里為商品的SKU屬性表 構(gòu)建service層進(jìn)行復(fù)雜查詢:指定條件查詢,聚合查詢,分頁查詢,排序查詢,高亮等等 接口測試: 查詢?nèi)缦拢?? ? ?

    2024年02月03日
    瀏覽(19)
  • Springboot整合Elasticsearch新版分頁查詢

    其它插入、刪除、簡單查詢都可以通過Repository調(diào)用方法查詢。 Elasticsearch現(xiàn)在的新版本已經(jīng)棄用了ElasticsearchTemplate類,Repository里原來的search方法也已經(jīng)棄用了。下面是使用ElasticsearchRestTemplate類實(shí)現(xiàn)的分頁查詢 代碼

    2024年02月11日
    瀏覽(15)
  • ElasticSearch系列 - SpringBoot整合ES:組合多個(gè)查詢條件 bool 查詢

    01. ElasticSearch 布爾查詢是什么? 在實(shí)際應(yīng)用中,我們很有可能會(huì)查詢多個(gè)值或字段。 一個(gè) bool 查詢由三部分組成: must:所有的語句都必須(must) 匹配,與 AND 等價(jià)。 must_not:所有的語句都不能(must not)匹配,與 NOT 等價(jià)。 should:至少有一個(gè)語句要匹配,與 OR 等價(jià)。 02.

    2023年04月08日
    瀏覽(27)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包