首页 > 其他分享 > Elasticsearch搜索功能的实现(五)-- 实战

Elasticsearch搜索功能的实现(五)-- 实战

时间:2023-04-18 23:34:52浏览次数:54  
标签:实战 search String title -- Elasticsearch boolBuilder new type

实战环境

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 分片数 replicas 副本数
@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") }) //混合类型字段 指定 建立索引时分词器与搜索时入参分词器
    private String title;

    @Schema(type = "LocalDate",description = "发布时间")
    @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 = "行业类型代码",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 = "新闻内容")
    @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);
}

四、简单功能实现

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();
    }

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

    @Override
    public PageResult findByType(String type) {
        // 先发布日期排序
        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());

    }

实现效果图片:
image

实际执行的DSL语句:
image

注意: 当指定排序条件时 _score 会被置空

4.2 搜索功能的实现

    @Override
    public PageResult searchNews(NewsPageSearch search) {

        //创建原生查询DSL对象
        final NativeQueryBuilder nativeQueryBuilder = new NativeQueryBuilder();

        // 先发布日期再得分排序
        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);

    }

    /**
     * 设置过滤条件 行业类型 来源 预警类型
     * @param search
     * @param boolBuilder
     */
    private void setFilter(NewsPageSearch search, BoolQuery.Builder boolBuilder) {
        //行业类型
        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)));
        }

        //范围区间
        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));

    }

实现效果

加权前效果:
image

加权后效果:
image

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": "立足优势稳住外贸基本盘"
						}
					}
				},
				"weight": 100.0
			}, {
				"filter": {
					"match": {
						"content": {
							"query": "立足优势稳住外贸基本盘"
						}
					}
				},
				"weight": 20.0
			}, {
				"filter": {
					"match": {
						"companies": {
							"query": "立足优势稳住外贸基本盘"
						}
					}
				},
				"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": "中国经济网"
									}
								}
							}]
						}
					}, {
						"bool": {
							"should": [{
								"term": {
									"type": {
										"value": "经济简报"
									}
								}
							}, {
								"term": {
									"type": {
										"value": "外贸简报"
									}
								}
							}]
						}
					}, {
						"range": {
							"pubDate": {
								"gte": "2023-03-29",
								"lte": "2023-03-30"
							}
						}
					}],
					"must": [{
						"multi_match": {
							"fields": ["title", "content", "companies"],
							"query": "立足优势稳住外贸基本盘"
						}
					}]
				}
			},
			"score_mode": "sum"
		}
	},
	"track_scores": false,
	"version": true
}

4.3 接口测试

image

标签:实战,search,String,title,--,Elasticsearch,boolBuilder,new,type
From: https://www.cnblogs.com/gdwkong/p/17331639.html

相关文章

  • 2023/4/18
    7-1用虚函数分别计算各种图形的面积分数 20全屏浏览题目切换布局作者 沙金单位 石家庄铁道大学定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle(长方形)、Trapezoid(梯形)和Triangle(三角形),用虚函数分别计算各种图形的......
  • 【PR制作】鸣神组混剪第一期 如何制作蒙版遮罩
    【PR制作】鸣神组混剪第一期——蒙版遮罩滑动效果 一、前言:偶然看到一个《咒术回战》乙骨忧太和《电锯人》早川秋的混剪。真的很帅,尤其是里面翻页和百叶窗效果。感觉好牛,但当自己学会会发现其实并不是很难。跟着教程一点点做就可以,但跟着做一遍,知识并不是自己,视频也不是,只......
  • cpp:Double Dimensional Array using vector 2
     //StudentArry.h:此文件包含"StudentArry"类。学生数组成绩显示方法C++14//2023年4月9日涂聚文GeovinDuedit.//(1)vec1.size()就是”二维数组”的行数//(2)vec1[0].size()就是”二维数组”的列数//vector<vector<double>>geovindu#pragmaonce#ifndefSTUD......
  • YOLOV8中文类名显示报错
    YOLOV8中文显示问题问题引出:​ 最近再跑YOLOV8项目,跑到这份数据集的类名是中文类名,自己也没有太在意,知道的过程出现些报错,这些爆错如下:/usr/local/lib/python3.8/dist-packages/ultralytics/yolo/utils/metrics.py:399:UserWarning:Glyph24102(\N{CJKUNIFIEDIDEOGRAPH-5E......
  • k8s中command、args && dockerfile中entrypoint、cmd之间的比较
    k8s中command、args&&dockerfile中entrypoint、cmd之间的比较标签(空格分隔):K8SDockerfile中ENTRYPOINT,CMD的比较ENTRYPOINT的两种格式:ENTRYPOINT["executable","param1","param2"](exec格式,推荐)ENTRYPOINTcommandparam1param2(shell格式)C......
  • 抽象基类
    一:声明抽象基类Shape,由它派生出三个类,圆形Circle,矩形Rectangle,三角形Triangle,用一个函数输出三个面积。输入格式:在一行中依次输入5个数,圆的半径,长方形的高和宽,三角形的高和底,中间用空格分隔输出格式:圆的面积,长方形的面积,三角形的面积,小数点后保留2位有效数字,每个面积占一行......
  • 冲刺4
    这个作业属于哪个课程2023软件工程-双学位这个作业要求在哪里团队作业4——项目冲刺这个作业的目标团队项目Scrum冲刺day4目录1.会议1.1今日已完成的工作1.2明日计划完成的工作1.3工作中遇到的困难2.燃尽图3.代码/文档签入记录签入记录对应的Issue内容与链接,代......
  • flask案例
    简单的flask‘sDemo#app.pyfromflaskimportFlask,render_template,jsonify,request,redirect,url_for,sessionimportfunctoolsapp=Flask(__name__)app.secret_key='adsa12dsa3456dasdsadsa'DATA_DICT={1:{"name":"陈三&......
  • Auto-GPT尝鲜使用
    Auto-GPT尝鲜使用注:部署所需:OpenAI的APIKey1.Auto-GPT本地部署1.1.环境准备需要Python环境,Python版本建议>=3.8(官方写的>=3.10)建议用Conda(Minconda或Anaconda)创建单独的虚拟环境Git:有没有无所谓了1.2.项目下载Auto-GPT项目地址:Significant-Gravitas/Auto-......
  • 4月18日笔记
    今天完成了空调调节温度、风速也面的设计。学会了如何添加一个小图标。我们在添加一个已经扣完图的小图标时,尽管已经扣的很干净了但是依旧会在图表外又一层灰色的背景,这时,我们只需要将背景设为透明就可以。通过android:background="#0000"这样我们就可以得到一个干净的图标。......