赞
踩
最近跟着视频做仿牛客社区的项目,发现这个项目很老了(2019年的),但是还是挺全面的,用了mybatis,redis,kafka,elasticsearch等等,但是elasticsearch真的挺烦的,很多东西都弃用了,从7.x.x开始代码框架大改了(好像是),导致我和老师的版本基本脱节,很多功能都不一样。
比如上面的ElasticsearchTemplete直接弃用了,老师实现搜索功能调的就是这个
然后写了一长串:
- NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
- // 内容标题同时匹配
- .withQuery(QueryBuilders.multiMatchQuery("互联网寒冬", "title", "content"))
- // 分别按照三个字段排序
- .withSorts(SortBuilders.fieldSort("type").order(SortOrder.DESC))
- .withSorts(SortBuilders.fieldSort("score").order(SortOrder.DESC))
- .withSorts(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
- // 分页
- .withPageable(PageRequest.of(0, 10))
- //高亮显示
- .withHighlightFields(
- new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
- new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
- ).build();
- Page<DiscussPost> page = elasticsearchTemplate.search(nativeSearchQuery, DiscussPost, "discusspost");
我直接宕机,一点开的ElasticsearchTemplete源码:
好家伙,弃用真彻底,直接把@Bean都删了,倔强的我只能自食其力了。
c了一下发现现在elasticsearch居然可以根据方法命名自动处理接口(怎么做到的,太牛辣!)。
于是首先我处理了一下dao层,定义了个接口来处理我要搜索的对象。
- @Repository
- public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer> {
-
-
- Page<DiscussPost> findDiscussPostByTitleOrContent(String title, String content, Pageable pageable);
- //Page<DiscussPost> findDiscussPostByUsername(String username, Pageable pageable);
-
- }
然后又到对象类里面加上那些注解,可恶啊,这里和老师的又不太一样,很多字段又弃用了!!!注意这里索引名称一定要是小写的,不然elasticsearch识别不了。
- @Document(indexName = "discusspost", shards = 6 ,replicas = 3)
- public class DiscussPost {
- @Id
- private int id;
- @Field(type = FieldType.Integer)
- private int userId;
- @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
- private String title;
- @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart") // 分词器analyzer
- private String content;
- @Field(type = FieldType.Integer)
- private int type;
- @Field(type = FieldType.Integer)
- private int status;
- @Field(type = FieldType.Date)
- private Date createTime;
- @Field(type = FieldType.Integer)
- private int commentCount;
- @Field(type = FieldType.Double)
- private int score;
-
- public int getScore() {
- return score;
- }
-
- public void setScore(int score) {
- this.score = score;
- }
-
- @Override
- public String toString() {
- return "DiscussPost{" +
- "id=" + id +
- ", userId=" + userId +
- ", title='" + title + '\'' +
- ", content='" + content + '\'' +
- ", type=" + type +
- ", status=" + status +
- ", createTime=" + createTime +
- ", commentCount=" + commentCount +
- ", commentCount=" + score +
- '}';
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public int getUserId() {
- return userId;
- }
-
- public void setUserId(int userId) {
- this.userId = userId;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public int getType() {
- return type;
- }
-
- public void setType(int type) {
- this.type = type;
- }
-
- public int getStatus() {
- return status;
- }
-
- public void setStatus(int status) {
- this.status = status;
- }
-
- public Date getCreateTime() {
- return createTime;
- }
-
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
-
- public int getCommentCount() {
- return commentCount;
- }
-
- public void setCommentCount(int commentCount) {
- this.commentCount = commentCount;
- }
- }
然后处理一下service层。
- @Service
- public class SearchService {
- @Autowired
- private DiscussPostRepository discussPostRepository;
-
- @Autowired
- private DiscussPostMapper discussPostMapper;
- /*
- 每次项目重新部署就把mysql里的帖子全部导入elasticsearch
- */
- @PostConstruct
- public void init() {
- try {
- discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(0,0,discussPostMapper.selectDiscussPostRows(0)));
- } catch (Exception e) {
-
- }
- }
- /*
- */
- public List<DiscussPost> SearchDiscussPostByTitleOrContent(String title, String content, Pageable pageable) {
- return discussPostRepository.findDiscussPostByTitleOrContent(title, content, pageable).getContent();
- }
-
-
- // public List<DiscussPost> SearchDiscussPostByUserName(String username, Pageable pageable) {
- // return discussPostRepository.findDiscussPostByUsername(username, pageable).getContent();
- // }
-
- public DiscussPost saveDiscussPost(DiscussPost discussPost) {
-
- return discussPostRepository.save(discussPost);
- }
-
- }
这里我自己加了个方法从mysql同步数据到elasticsearch,这样部署到服务器上比较方便(因为这里版本不兼容,但是不影响正常使用,所以我每个调用接口的操作全都用try catch覆盖掉了,,不然一直报错很烦)。
- /*
- 每次项目重新部署就把mysql里的帖子全部导入elasticsearch
- */
- @PostConstruct
- public void init() {
- try {
- discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(0,0,discussPostMapper.selectDiscussPostRows(0)));
- } catch (Exception e) {
-
- }
- }
然后处理controller层,这个就比较简单了,但是我基础薄弱,这个Pageable搞了我半天。
- @RequestMapping(path = "/search", method = RequestMethod.GET)
- public String search(String keyword, Model model, Page page) {
-
- Sort sort = CommunityUtil.getSearchSort();
- Pageable pageable = PageRequest.of(page.getCurrent() - 1, page.getLimit(),sort);
- page.setPath("/search?keyword=" + keyword);
- int rows = searchService.SearchDiscussPostByTitleOrContent(keyword, keyword, null).size();
- page.setRows(rows == 0 ? 0 : rows);
-
- List<DiscussPost> list = searchService.SearchDiscussPostByTitleOrContent(keyword, keyword, pageable);
-
- List<Map<String,Object>> discussPosts = new ArrayList<>();
- if (list != null) {
- for (DiscussPost discussPost : list) {
- Map<String,Object> map = new HashMap<>();
- map.put("post",discussPost);
- User user = userService.findUserById(discussPost.getUserId());
- map.put("user",user);
- discussPosts.add(map);
-
- long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
- map.put("likeCount",likeCount);
- }
- }
- model.addAttribute("discussPosts",discussPosts);
- model.addAttribute("keyword",keyword);
- model.addAttribute("rows",rows);
- return "site/search";
- }
-
- }
但是我c了很久都没有找到怎么实现高亮显示,所以只能算是半成品,但是至少能用啊,如果有大佬知道麻烦告诉我一下!!!万分感谢!!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。