牛客网项目——项目开发(八):开发社区搜索功能

在这里插入图片描述

1. ElasticsearchService

1.1 注入bean

@Autowired
private DiscussPostRepository discussRepository;

@Autowired
private ElasticsearchTemplate elasticTemplate;

1.2 保存(修改)和删除

public void saveDiscussPost(DiscussPost post) {
   
    discussRepository.save(post);
}

public void deleteDiscussPost(int id) {
   
    discussRepository.deleteById(id);
}

1.3 搜索 searchDiscussPost

  1. 返回参数:Page类型数据,封装多条数据
  2. 传入参数:关键字keyword,当前页数current,每页显示数据limit
  3. 搜索逻辑,参考前置技术(九)
    1. 查询关键字
    2. 排序
    3. 分页
    4. 高亮显示
public Page<DiscussPost> searchDiscussPost(String keyword, int current, int limit) {
   
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
            .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
            .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
            .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
            .withPageable(PageRequest.of(current, limit))
            .withHighlightFields(
                    new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                    new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
            ).build();

    return elasticTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper() {
   
        @Override
        public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable) {
   
            SearchHits hits = response.getHits();
            if (hits.getTotalHits() <= 0) {
   
                return null;
            }

            List<DiscussPost> list = new ArrayList<>();
            for (SearchHit hit : hits) {
   
                DiscussPost post = new DiscussPost();

                String id = hit.getSourceAsMap().get("id").toString();
                post.setId(Integer.valueOf(id));

                String userId = hit.getSourceAsMap().get("userId").toString();<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平什么阿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值