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

Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)

這篇具有很好參考價值的文章主要介紹了Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

實戰(zhàn)環(huán)境

elastic search 8.5.0 + kibna 8.5.0 + springboot 3.0.2 + spring data elasticsearch 5.0.2 + jdk 17

一、集成 spring data elasticsearch

1 添加依賴

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

2 配置es連接

@Configuration
public class ElasticsearchConfig extends ElasticsearchConfiguration {

    @Override
    public ClientConfiguration clientConfiguration() {

            return ClientConfiguration.builder()
                    .connectedTo("127.0.0.1:9200")
                    .withBasicAuth("elastic", "********")
                    .build();

    }
}

3 配置打印DSL語句

# 日志配置
logging:
  level:
    #es日志
    org.springframework.data.elasticsearch.client.WIRE : trace

二、index及mapping 文件編寫

@Data
@Document(indexName = "news") //索引名
@Setting(shards = 1,replicas = 0,refreshInterval = "1s") //shards 分片數(shù) replicas 副本數(shù)
@Schema(name = "News",description = "新聞對象")
public class News implements Serializable {

    @Id  //索引主鍵
    @NotBlank(message = "新聞ID不能為空")
    @Schema(type = "integer",description = "新聞ID",example = "1")
    private Integer id;

    @NotBlank(message = "新聞標題不能為空")
    @Schema(type = "String",description = "新聞標題")
    @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart"),
            otherFields = {@InnerField(type = FieldType.Keyword, suffix = "keyword") }) //混合類型字段 指定 建立索引時分詞器與搜索時入?yún)⒎衷~器
    private String title;

    @Schema(type = "LocalDate",description = "發(fā)布時間")
    @Field(type = FieldType.Date,format = DateFormat.date)
    private LocalDate pubDate;

    @Schema(type = "String",description = "來源")
    @Field(type = FieldType.Keyword)
    private String source;

    @Schema(type = "String",description = "行業(yè)類型代碼",example = "1,2,3")
    @Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart")
    private String industry;

    @Schema(type = "String",description = "預警類型")
    @Field(type = FieldType.Keyword)
    private String type;

    @Schema(type = "String",description = "涉及公司")
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String companies;

    @Schema(type = "String",description = "新聞內(nèi)容")
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String content;

}

三、DAO層編寫

@Repository
public interface NewsRepository extends ElasticsearchRepository<News,Integer> {

    Page<News> findByType(String type, Pageable pageable);
}

四、簡單功能實現(xiàn)

4.1 簡單功能寫法

    /**
     * 新增新聞
     * @param news
     * @return
     */
    @Override
    public void saveNews(News news) {
        newsRepository.save(news);
    }

    /**
     * 刪除新聞
     * @param newsId
     */
    @Override
    public void delete(Integer newsId) {
        newsRepository.deleteById(newsId);
    }

    /**
     * 刪除新聞索引
     */
    @Override
    public void deleteIndex() {
        operations.indexOps(News.class).delete();
    }

    /**
     * 創(chuàng)建索引
     */
    @Override
    public void createIndex() {
        operations.indexOps(News.class).createWithMapping();
    }

    @Override
    public PageResult findByType(String type) {
        // 先發(fā)布日期排序
        Sort sort = Sort.by(new Order(Sort.Direction.DESC, "pubDate"));
        Pageable pageable = PageRequest.of(0,10,sort);
        final Page<News> newsPage = newsRepository.findByType(type, pageable);
        return new PageResult(newsPage.getTotalElements(),newsPage.getContent());

    }

實現(xiàn)效果圖片:
Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)

實際執(zhí)行的DSL語句:
Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)

注意: 當指定排序條件時 _score 會被置空

4.2 搜索功能的實現(xiàn)

    @Override
    public PageResult searchNews(NewsPageSearch search) {

        //創(chuàng)建原生查詢DSL對象
        final NativeQueryBuilder nativeQueryBuilder = new NativeQueryBuilder();

        // 先發(fā)布日期再得分排序
        Sort sort = Sort.by(new Order(Sort.Direction.DESC, "pubDate"),new Order(Sort.Direction.DESC, "_score"));

        Pageable pageable = PageRequest.of(search.getCurPage(), search.getPageSize(),sort);


        final BoolQuery.Builder boolBuilder = new BoolQuery.Builder();
        //過濾條件
        setFilter(search, boolBuilder);

        //關鍵字搜索
        if (StringUtils.isNotBlank(search.getKeyword())){
            setKeyWordAndHighlightField(search, nativeQueryBuilder, boolBuilder);
        }else {
            nativeQueryBuilder.withQuery(q -> q.bool(boolBuilder.build()));
        }

        nativeQueryBuilder.withPageable(pageable);

        SearchHits<News> searchHits = operations.search(nativeQueryBuilder.build(), News.class);
        //高亮回填封裝
        final List<News> newsList = searchHits.getSearchHits().stream()
                .map(s -> {
                    final News content = s.getContent();
                    final List<String> title = s.getHighlightFields().get("title");
                    final List<String> contentList = s.getHighlightFields().get("content");
                    if (!CollectionUtils.isEmpty(title)){
                        s.getContent().setTitle(title.get(0));
                    }
                    if (!CollectionUtils.isEmpty(contentList)){
                        s.getContent().setContent(contentList.get(0));
                    }
                    return content;

                }).collect(Collectors.toList());

        return new PageResult<News>(searchHits.getTotalHits(),newsList);

    }

    /**
     * 設置過濾條件 行業(yè)類型 來源 預警類型
     * @param search
     * @param boolBuilder
     */
    private void setFilter(NewsPageSearch search, BoolQuery.Builder boolBuilder) {
        //行業(yè)類型
        if(StringUtils.isNotBlank(search.getIndustry())){
            // 按逗號拆分
            List<Query> industryQueries = Arrays.asList(search.getIndustry().split(",")).stream().map(p -> {
                Query.Builder queryBuilder = new Query.Builder();
                queryBuilder.term(t -> t.field("industry").value(p));
                return queryBuilder.build();
            }).collect(Collectors.toList());
            boolBuilder.filter(f -> f.bool(t -> t.should(industryQueries)));
        }
        // 來源
        if(StringUtils.isNotBlank(search.getSource())){
            // 按逗號拆分
            List<Query> sourceQueries = Arrays.asList(search.getSource().split(",")).stream().map(p -> {
                Query.Builder queryBuilder = new Query.Builder();
                queryBuilder.term(t -> t.field("source").value(p));
                return queryBuilder.build();
            }).collect(Collectors.toList());
            boolBuilder.filter(f -> f.bool(t -> t.should(sourceQueries)));
        }
        // 預警類型
        if(StringUtils.isNotBlank(search.getType())){
            // 按逗號拆分
            List<Query> typeQueries = Arrays.asList(search.getType().split(",")).stream().map(p -> {
                Query.Builder queryBuilder = new Query.Builder();
                queryBuilder.term(t -> t.field("type").value(p));
                return queryBuilder.build();
            }).collect(Collectors.toList());
            boolBuilder.filter(f -> f.bool(t -> t.should(typeQueries)));
        }

        //范圍區(qū)間
        if (StringUtils.isNotBlank(search.getStartDate())){
            boolBuilder.filter(f -> f.range(r -> r.field("pubDate")
                    .gte(JsonData.of(search.getStartDate()))
                    .lte(JsonData.of(search.getEndDate()))));
        }
    }

    /**
     * 關鍵字搜索 title 權重更高
     * 高亮字段  title 、content
     * @param search
     * @param nativeQueryBuilder
     * @param boolBuilder
     */
    private void setKeyWordAndHighlightField(NewsPageSearch search, NativeQueryBuilder nativeQueryBuilder, BoolQuery.Builder boolBuilder) {
        final String keyword = search.getKeyword();
        //查詢條件
        boolBuilder.must(b -> b.multiMatch(m -> m.fields("title","content","companies").query(keyword)));

        //高亮
        final HighlightFieldParameters.HighlightFieldParametersBuilder builder = HighlightFieldParameters.builder();
        builder.withPreTags("<font color='red'>")
                .withPostTags("</font>")
                .withRequireFieldMatch(true) //匹配才加標簽
                .withNumberOfFragments(0); //顯示全文
        final HighlightField titleHighlightField = new HighlightField("title", builder.build());
        final HighlightField contentHighlightField = new HighlightField("content", builder.build());
        final Highlight titleHighlight = new Highlight(List.of(titleHighlightField,contentHighlightField));

        nativeQueryBuilder.withQuery(
                        f -> f.functionScore(
                                fs -> fs.query(q -> q.bool(boolBuilder.build()))
                                        .functions( FunctionScore.of(func -> func.filter(
                                                        fq -> fq.match(ft -> ft.field("title").query(keyword))).weight(100.0)),
                                                FunctionScore.of(func -> func.filter(
                                                        fq -> fq.match(ft -> ft.field("content").query(keyword))).weight(20.0)),
                                                FunctionScore.of(func -> func.filter(
                                                        fq -> fq.match(ft -> ft.field("companies").query(keyword))).weight(10.0)))
                                        .scoreMode(FunctionScoreMode.Sum)
                                        .boostMode(FunctionBoostMode.Sum)
                                        .minScore(1.0)))
                .withHighlightQuery(new HighlightQuery(titleHighlight,News.class));

    }

實現(xiàn)效果

加權前效果:
Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)

加權后效果:
Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)

DSL 語句:

{
	"from": 0,
	"size": 6,
	"sort": [{
		"pubDate": {
			"mode": "min",
			"order": "desc"
		}
	}, {
		"_score": {
			"order": "desc"
		}
	}],
	"highlight": {
		"fields": {
			"title": {
				"number_of_fragments": 0,
				"post_tags": ["</font>"],
				"pre_tags": ["<font color='red'>"]
			},
			"content": {
				"number_of_fragments": 0,
				"post_tags": ["</font>"],
				"pre_tags": ["<font color='red'>"]
			}
		}
	},
	"query": {
		"function_score": {
			"boost_mode": "sum",
			"functions": [{
				"filter": {
					"match": {
						"title": {
							"query": "立足優(yōu)勢穩(wěn)住外貿(mào)基本盤"
						}
					}
				},
				"weight": 100.0
			}, {
				"filter": {
					"match": {
						"content": {
							"query": "立足優(yōu)勢穩(wěn)住外貿(mào)基本盤"
						}
					}
				},
				"weight": 20.0
			}, {
				"filter": {
					"match": {
						"companies": {
							"query": "立足優(yōu)勢穩(wěn)住外貿(mào)基本盤"
						}
					}
				},
				"weight": 10.0
			}],
			"min_score": 1.0,
			"query": {
				"bool": {
					"filter": [{
						"bool": {
							"should": [{
								"term": {
									"industry": {
										"value": "1"
									}
								}
							}, {
								"term": {
									"industry": {
										"value": "2"
									}
								}
							}, {
								"term": {
									"industry": {
										"value": "3"
									}
								}
							}]
						}
					}, {
						"bool": {
							"should": [{
								"term": {
									"source": {
										"value": "新華社"
									}
								}
							}, {
								"term": {
									"source": {
										"value": "中國經(jīng)濟網(wǎng)"
									}
								}
							}]
						}
					}, {
						"bool": {
							"should": [{
								"term": {
									"type": {
										"value": "經(jīng)濟簡報"
									}
								}
							}, {
								"term": {
									"type": {
										"value": "外貿(mào)簡報"
									}
								}
							}]
						}
					}, {
						"range": {
							"pubDate": {
								"gte": "2023-03-29",
								"lte": "2023-03-30"
							}
						}
					}],
					"must": [{
						"multi_match": {
							"fields": ["title", "content", "companies"],
							"query": "立足優(yōu)勢穩(wěn)住外貿(mào)基本盤"
						}
					}]
				}
			},
			"score_mode": "sum"
		}
	},
	"track_scores": false,
	"version": true
}

4.3 接口測試

Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)文章來源地址http://www.zghlxwxcb.cn/news/detail-417819.html

到了這里,關于Elasticsearch搜索功能的實現(xiàn)(五)-- 實戰(zhàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

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

領支付寶紅包贊助服務器費用

相關文章

  • Spring Boot 中使用 Elasticsearch 實現(xiàn)商品搜索功能

    作者:禪與計算機程序設計藝術 Elasticsearch 是開源分布式搜索引擎,它提供了一個分布式、RESTful 搜索接口?;?Elasticsearch 的搜索方案能夠輕松應對復雜的檢索場景并提供高擴展性。在 Web 應用中,Elasticsearch 可以作為后臺服務支持用戶的檢索需求。本文將會教你如何使用

    2024年02月06日
    瀏覽(18)
  • Elasticsearch實戰(zhàn)(五):Springboot實現(xiàn)Elasticsearch電商平臺日志埋點與搜索熱詞

    Elasticsearch實戰(zhàn)(五):Springboot實現(xiàn)Elasticsearch電商平臺日志埋點與搜索熱詞

    Elasticsearch實戰(zhàn)(一):Springboot實現(xiàn)Elasticsearch統(tǒng)一檢索功能 Elasticsearch實戰(zhàn)(二):Springboot實現(xiàn)Elasticsearch自動漢字、拼音補全,Springboot實現(xiàn)自動拼寫糾錯 Elasticsearch實戰(zhàn)(三):Springboot實現(xiàn)Elasticsearch搜索推薦 Elasticsearch實戰(zhàn)(四):Springboot實現(xiàn)Elasticsearch指標聚合與下鉆分析

    2024年02月09日
    瀏覽(23)
  • 網(wǎng)頁搜索自動補全功能如何實現(xiàn),Elasticsearch來祝佬“一臂之力”

    網(wǎng)頁搜索自動補全功能如何實現(xiàn),Elasticsearch來祝佬“一臂之力”

    前言:大家好,我是小威,24屆畢業(yè)生,在一家滿意的公司實習。本篇文章參考網(wǎng)上的課程,介紹Elasticsearch搜索引擎之自動補全功能的介紹與使用,這塊內(nèi)容不作為面試中的重點。 如果文章有什么需要改進的地方還請大佬不吝賜教 ????。 小威在此先感謝各位大佬啦~~????

    2023年04月15日
    瀏覽(16)
  • Elasticsearch實戰(zhàn)(一):Springboot實現(xiàn)Elasticsearch統(tǒng)一檢索功能

    Elasticsearch實戰(zhàn)(一):Springboot實現(xiàn)Elasticsearch統(tǒng)一檢索功能 Elasticsearch實戰(zhàn)(二):Springboot實現(xiàn)Elasticsearch自動漢字、拼音補全,Springboot實現(xiàn)自動拼寫糾錯 Elasticsearch實戰(zhàn)(三):Springboot實現(xiàn)Elasticsearch搜索推薦 Elasticsearch實戰(zhàn)(四):Springboot實現(xiàn)Elasticsearch指標聚合與下鉆分析

    2024年02月12日
    瀏覽(20)
  • ElasticSearch - 基于 拼音分詞器 和 IK分詞器 模擬實現(xiàn)“百度”搜索框自動補全功能

    ElasticSearch - 基于 拼音分詞器 和 IK分詞器 模擬實現(xiàn)“百度”搜索框自動補全功能

    目錄 一、自動補全 1.1、效果說明 1.2、安裝拼音分詞器 1.3、自定義分詞器 1.3.1、為什么要自定義分詞器 1.3.2、分詞器的構成 1.3.3、自定義分詞器 1.3.4、面臨的問題和解決辦法 問題 解決方案 1.4、completion suggester 查詢 1.4.1、基本概念和語法 1.4.2、示例 1.4.3、示例(黑馬旅游)

    2024年02月07日
    瀏覽(31)
  • 《Spring Boot 實戰(zhàn)派》--13.集成NoSQL數(shù)據(jù)庫,實現(xiàn)Elasticsearch和Solr搜索引擎

    《Spring Boot 實戰(zhàn)派》--13.集成NoSQL數(shù)據(jù)庫,實現(xiàn)Elasticsearch和Solr搜索引擎

    ?????????關于搜索引擎 我們很難實現(xiàn) Elasticseach 和 Solr兩大搜索框架的效果;所以本章針對兩大搜索框架,非常詳細地講解 它們的原理和具體使用方法, 首先 介紹什么是搜索引擎 、如何用 MySQL實現(xiàn)簡單的搜索引擎,以及Elasticseach 的 概念和接口類; 然后介紹Elasticseach

    2023年04月09日
    瀏覽(25)
  • 數(shù)據(jù)結構與算法之美學習筆記:42 | 動態(tài)規(guī)劃實戰(zhàn):如何實現(xiàn)搜索引擎中的拼寫糾錯功能?

    數(shù)據(jù)結構與算法之美學習筆記:42 | 動態(tài)規(guī)劃實戰(zhàn):如何實現(xiàn)搜索引擎中的拼寫糾錯功能?

    本節(jié)課程思維導圖: 利用 Trie 樹,可以實現(xiàn)搜索引擎的提示功能,這樣可以節(jié)省用戶輸入搜索的時間。實際上,搜索引擎在用戶體驗方面的優(yōu)化還有很多,比如你可能經(jīng)常會用的拼寫糾錯功能。 當你在搜索框中,一不小心輸錯單詞時,搜索引擎會非常智能地檢

    2024年02月03日
    瀏覽(24)
  • Elasticsearch(十四)搜索---搜索匹配功能⑤--全文搜索

    Elasticsearch(十四)搜索---搜索匹配功能⑤--全文搜索

    不同于之前的term。terms等結構化查詢,全文搜索首先對查詢詞進行分析,然后根據(jù)查詢詞的分詞結果構建查詢。這里所說的全文指的是文本類型數(shù)據(jù)(text類型),默認的數(shù)據(jù)形式是人類的自然語言,如對話內(nèi)容、圖書名稱、商品介紹和酒店名稱等。結構化搜索關注的是數(shù)據(jù)是

    2024年02月11日
    瀏覽(21)
  • 分布式搜索引擎——elasticsearch搜索功能

    分布式搜索引擎——elasticsearch搜索功能

    Elasticsearch提供了基于JSON的DSL (Domain Specific Language)來定義查詢。常見的查詢類型包括: 查詢所有:查詢出所有數(shù)據(jù),一般測試用。例如:match_all 全文檢索(full text)查詢:利用分詞器對用戶輸入內(nèi)容分詞,然后去倒排索引庫中匹配。例如: match_query multi_match_query 精確查詢:根據(jù)精確詞條

    2024年02月05日
    瀏覽(35)
  • 分布式搜索引擎ElasticSearch——搜索功能

    分布式搜索引擎ElasticSearch——搜索功能

    DSL查詢分類 DSL官方文檔 全文檢索查詢 精確查詢 地理查詢 復合查詢 Function Score Query function score query Boolean Query 排序 分頁 官方文檔 高亮 快速入門 match,term,range,bool查詢 排序和分頁 高亮顯示 就是在前面抽取的解析代碼中進一步添加關于高亮的解析部分,因為highlight和so

    2024年02月01日
    瀏覽(28)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領取紅包

二維碼2

領紅包