当前位置:   article > 正文

比较邪门的elasticsearch的使用方式_nativesearchquerybuilder withsorts

nativesearchquerybuilder withsorts

        最近跟着视频做仿牛客社区的项目,发现这个项目很老了(2019年的),但是还是挺全面的,用了mybatis,redis,kafka,elasticsearch等等,但是elasticsearch真的挺烦的,很多东西都弃用了,从7.x.x开始代码框架大改了(好像是),导致我和老师的版本基本脱节,很多功能都不一样。

        比如上面的ElasticsearchTemplete直接弃用了,老师实现搜索功能调的就是这个

        然后写了一长串:

  1. NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
  2. // 内容标题同时匹配
  3. .withQuery(QueryBuilders.multiMatchQuery("互联网寒冬", "title", "content"))
  4. // 分别按照三个字段排序
  5. .withSorts(SortBuilders.fieldSort("type").order(SortOrder.DESC))
  6. .withSorts(SortBuilders.fieldSort("score").order(SortOrder.DESC))
  7. .withSorts(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
  8. // 分页
  9. .withPageable(PageRequest.of(0, 10))
  10. //高亮显示
  11. .withHighlightFields(
  12. new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
  13. new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
  14. ).build();
  15. Page<DiscussPost> page = elasticsearchTemplate.search(nativeSearchQuery, DiscussPost, "discusspost");

         我直接宕机,一点开的ElasticsearchTemplete源码:

        好家伙,弃用真彻底,直接把@Bean都删了,倔强的我只能自食其力了。

        c了一下发现现在elasticsearch居然可以根据方法命名自动处理接口(怎么做到的,太牛辣!)。

        于是首先我处理了一下dao层,定义了个接口来处理我要搜索的对象。

  1. @Repository
  2. public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer> {
  3. Page<DiscussPost> findDiscussPostByTitleOrContent(String title, String content, Pageable pageable);
  4. //Page<DiscussPost> findDiscussPostByUsername(String username, Pageable pageable);
  5. }

        然后又到对象类里面加上那些注解,可恶啊,这里和老师的又不太一样,很多字段又弃用了!!!注意这里索引名称一定要是小写的,不然elasticsearch识别不了。

  1. @Document(indexName = "discusspost", shards = 6 ,replicas = 3)
  2. public class DiscussPost {
  3. @Id
  4. private int id;
  5. @Field(type = FieldType.Integer)
  6. private int userId;
  7. @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
  8. private String title;
  9. @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart") // 分词器analyzer
  10. private String content;
  11. @Field(type = FieldType.Integer)
  12. private int type;
  13. @Field(type = FieldType.Integer)
  14. private int status;
  15. @Field(type = FieldType.Date)
  16. private Date createTime;
  17. @Field(type = FieldType.Integer)
  18. private int commentCount;
  19. @Field(type = FieldType.Double)
  20. private int score;
  21. public int getScore() {
  22. return score;
  23. }
  24. public void setScore(int score) {
  25. this.score = score;
  26. }
  27. @Override
  28. public String toString() {
  29. return "DiscussPost{" +
  30. "id=" + id +
  31. ", userId=" + userId +
  32. ", title='" + title + '\'' +
  33. ", content='" + content + '\'' +
  34. ", type=" + type +
  35. ", status=" + status +
  36. ", createTime=" + createTime +
  37. ", commentCount=" + commentCount +
  38. ", commentCount=" + score +
  39. '}';
  40. }
  41. public int getId() {
  42. return id;
  43. }
  44. public void setId(int id) {
  45. this.id = id;
  46. }
  47. public int getUserId() {
  48. return userId;
  49. }
  50. public void setUserId(int userId) {
  51. this.userId = userId;
  52. }
  53. public String getTitle() {
  54. return title;
  55. }
  56. public void setTitle(String title) {
  57. this.title = title;
  58. }
  59. public String getContent() {
  60. return content;
  61. }
  62. public void setContent(String content) {
  63. this.content = content;
  64. }
  65. public int getType() {
  66. return type;
  67. }
  68. public void setType(int type) {
  69. this.type = type;
  70. }
  71. public int getStatus() {
  72. return status;
  73. }
  74. public void setStatus(int status) {
  75. this.status = status;
  76. }
  77. public Date getCreateTime() {
  78. return createTime;
  79. }
  80. public void setCreateTime(Date createTime) {
  81. this.createTime = createTime;
  82. }
  83. public int getCommentCount() {
  84. return commentCount;
  85. }
  86. public void setCommentCount(int commentCount) {
  87. this.commentCount = commentCount;
  88. }
  89. }

         然后处理一下service层。

  1. @Service
  2. public class SearchService {
  3. @Autowired
  4. private DiscussPostRepository discussPostRepository;
  5. @Autowired
  6. private DiscussPostMapper discussPostMapper;
  7. /*
  8. 每次项目重新部署就把mysql里的帖子全部导入elasticsearch
  9. */
  10. @PostConstruct
  11. public void init() {
  12. try {
  13. discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(0,0,discussPostMapper.selectDiscussPostRows(0)));
  14. } catch (Exception e) {
  15. }
  16. }
  17. /*
  18. */
  19. public List<DiscussPost> SearchDiscussPostByTitleOrContent(String title, String content, Pageable pageable) {
  20. return discussPostRepository.findDiscussPostByTitleOrContent(title, content, pageable).getContent();
  21. }
  22. // public List<DiscussPost> SearchDiscussPostByUserName(String username, Pageable pageable) {
  23. // return discussPostRepository.findDiscussPostByUsername(username, pageable).getContent();
  24. // }
  25. public DiscussPost saveDiscussPost(DiscussPost discussPost) {
  26. return discussPostRepository.save(discussPost);
  27. }
  28. }

        这里我自己加了个方法从mysql同步数据到elasticsearch,这样部署到服务器上比较方便(因为这里版本不兼容,但是不影响正常使用,所以我每个调用接口的操作全都用try catch覆盖掉了,,不然一直报错很烦)。

  1. /*
  2. 每次项目重新部署就把mysql里的帖子全部导入elasticsearch
  3. */
  4. @PostConstruct
  5. public void init() {
  6. try {
  7. discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(0,0,discussPostMapper.selectDiscussPostRows(0)));
  8. } catch (Exception e) {
  9. }
  10. }

        然后处理controller层,这个就比较简单了,但是我基础薄弱,这个Pageable搞了我半天。

  1. @RequestMapping(path = "/search", method = RequestMethod.GET)
  2. public String search(String keyword, Model model, Page page) {
  3. Sort sort = CommunityUtil.getSearchSort();
  4. Pageable pageable = PageRequest.of(page.getCurrent() - 1, page.getLimit(),sort);
  5. page.setPath("/search?keyword=" + keyword);
  6. int rows = searchService.SearchDiscussPostByTitleOrContent(keyword, keyword, null).size();
  7. page.setRows(rows == 0 ? 0 : rows);
  8. List<DiscussPost> list = searchService.SearchDiscussPostByTitleOrContent(keyword, keyword, pageable);
  9. List<Map<String,Object>> discussPosts = new ArrayList<>();
  10. if (list != null) {
  11. for (DiscussPost discussPost : list) {
  12. Map<String,Object> map = new HashMap<>();
  13. map.put("post",discussPost);
  14. User user = userService.findUserById(discussPost.getUserId());
  15. map.put("user",user);
  16. discussPosts.add(map);
  17. long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
  18. map.put("likeCount",likeCount);
  19. }
  20. }
  21. model.addAttribute("discussPosts",discussPosts);
  22. model.addAttribute("keyword",keyword);
  23. model.addAttribute("rows",rows);
  24. return "site/search";
  25. }
  26. }

       但是我c了很久都没有找到怎么实现高亮显示,所以只能算是半成品,但是至少能用啊,如果有大佬知道麻烦告诉我一下!!!万分感谢!!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1000915
推荐阅读
相关标签
  

闽ICP备14008679号