ElasticSearch实战(四) 匹配查询、高亮显示

释放双眼,带上耳机,听听看~!

接下来处理模糊查询功能

ElasticSearch实战(四) 匹配查询、高亮显示

  • 匹配查询

 修改controller代码,如果传入的keyword不是空值,则改为使用匹配查询


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1    @RequestMapping("/blogs")
2    public String query(Model model, String keyword, Integer pageNum, Integer pageSize) {
3
4        if(pageNum == null || pageNum <= 0)
5            pageNum = 1;
6        if(pageSize == null || pageSize <= 0)
7            pageSize = 5;
8
9        SearchQuery searchQuery = null;
10        if (StringUtils.isNotBlank(keyword)) {
11            searchQuery = new NativeSearchQueryBuilder()
12                    .withPageable(new QPageRequest(pageNum - 1, pageSize))
13                    .withQuery(QueryBuilders.multiMatchQuery(keyword, "text", "author"))
14                    .withSort(SortBuilders.fieldSort("date").order(SortOrder.DESC))
15                    .build();
16        } else {
17            searchQuery = new NativeSearchQueryBuilder()
18                    .withPageable(new QPageRequest(pageNum - 1, pageSize))
19                    .withQuery(QueryBuilders.matchAllQuery())
20                    .withSort(SortBuilders.fieldSort("date").order(SortOrder.DESC))
21                    .build();
22        }
23        Page<Blog> blogs = elasticsearchTemplate.queryForPage(searchQuery, Blog.class);
24        model.addAttribute("blogs", blogs.getContent());
25        model.addAttribute("pageHelper", new PageHelper<>(blogs, pageNum, pageSize));
26        model.addAttribute("keyword", keyword);
27        return "index";
28    }
29
  • ** 高亮显示**

spring-data-elasticsearch使用SearchResultMapper接口实现对搜索结果的再加工,搜索结果的高亮显示可以通过该接口的实现类来实现。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
1import com.alibaba.fastjson.JSON;
2import org.elasticsearch.action.search.SearchResponse;
3import org.elasticsearch.search.SearchHit;
4import org.elasticsearch.search.SearchHits;
5import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
6import org.springframework.data.domain.Pageable;
7import org.springframework.data.elasticsearch.core.SearchResultMapper;
8import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
9import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
10
11import java.lang.reflect.Field;
12import java.util.ArrayList;
13import java.util.List;
14import java.util.Map;
15
16public class HighlightResultMapper implements SearchResultMapper {
17    @Override
18    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> clazz, Pageable pageable) {
19        long totalHits = searchResponse.getHits().getTotalHits();
20        List<T> list = new ArrayList<>();
21        SearchHits hits = searchResponse.getHits();
22        if (hits.getHits().length> 0) {
23            for (SearchHit searchHit : hits) {
24                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
25                T item = JSON.parseObject(searchHit.getSourceAsString(), clazz);
26                Field[] fields = clazz.getDeclaredFields();
27                for (Field field : fields) {
28                    field.setAccessible(true);
29                    if (highlightFields.containsKey(field.getName())) {
30                        try {
31                            field.set(item, highlightFields.get(field.getName()).fragments()[0].toString());
32                        } catch (IllegalAccessException e) {
33                            e.printStackTrace();
34                        }
35                    }
36                }
37                list.add(item);
38            }
39        }
40        return new AggregatedPageImpl<>(list, pageable, totalHits);
41    }
42}
43

对controller代码稍作修改


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1        String authorFieldName = "author";
2        String textFieldName = "text";
3        String preTags = "<span style=\"color:#F56C6C\">";
4        String postTags = "</span>";
5        HighlightBuilder.Field authorField = new HighlightBuilder.Field(authorFieldName).preTags(preTags).postTags(postTags);
6        HighlightBuilder.Field textField = new HighlightBuilder.Field(textFieldName).preTags(preTags).postTags(postTags);
7
8        SearchQuery searchQuery = null;
9        if (StringUtils.isNotBlank(keyword)) {
10            searchQuery = new NativeSearchQueryBuilder()
11                    .withPageable(new QPageRequest(pageNum - 1, pageSize))
12                    .withQuery(QueryBuilders.multiMatchQuery(keyword, "text", "author"))
13                    .withHighlightFields(authorField, textField)
14                    .withSort(SortBuilders.fieldSort("date").order(SortOrder.DESC))
15                    .build();
16        } else {
17            searchQuery = new NativeSearchQueryBuilder()
18                    .withPageable(new QPageRequest(pageNum - 1, pageSize))
19                    .withQuery(QueryBuilders.matchAllQuery())
20                    .withSort(SortBuilders.fieldSort("date").order(SortOrder.DESC))
21                    .build();
22        }
23        Page<Blog> blogs = elasticsearchTemplate.queryForPage(searchQuery, Blog.class, new HighlightResultMapper());
24

效果

ElasticSearch实战(四) 匹配查询、高亮显示

 

代码

链接:https://pan.baidu.com/s/13pAWNl_KLQg4RdAClYH9Rg 
提取码:qm0l 

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索