生活随笔
收集整理的這篇文章主要介紹了
牛客网项目——项目开发(八):开发社区搜索功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. ElasticsearchService
- 1.1 注入bean
- 1.2 保存(修改)和刪除
- 1.3 搜索 searchDiscussPost
- 2. DiscussPostController.addDiscussPost
- 3. CommentController.addComment
- 4. EventConsumer.handlePublishMessage
- 5. SearchController
- 6. index.html
- 7. search.html
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
返回參數:Page類型數據,封裝多條數據傳入參數:關鍵字keyword,當前頁數current,每頁顯示數據limit搜索邏輯,參考前置技術(九) 查詢關鍵字排序分頁高亮顯示
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() {@Overridepublic <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();post
.setUserId(Integer.valueOf(userId
));String title
= hit
.getSourceAsMap().get("title").toString();post
.setTitle(title
);String content
= hit
.getSourceAsMap().get("content").toString();post
.setContent(content
);String status
= hit
.getSourceAsMap().get("status").toString();post
.setStatus(Integer.valueOf(status
));String createTime
= hit
.getSourceAsMap().get("createTime").toString();post
.setCreateTime(new Date(Long.valueOf(createTime
)));String commentCount
= hit
.getSourceAsMap().get("commentCount").toString();post
.setCommentCount(Integer.valueOf(commentCount
));HighlightField titleField
= hit
.getHighlightFields().get("title");if (titleField
!= null) {post
.setTitle(titleField
.getFragments()[0].toString());}HighlightField contentField
= hit
.getHighlightFields().get("content");if (contentField
!= null) {post
.setContent(contentField
.getFragments()[0].toString());}list
.add(post
);}return new AggregatedPageImpl(list
, pageable
,hits
.getTotalHits(), response
.getAggregations(), response
.getScrollId(), hits
.getMaxScore());}});
}
2. DiscussPostController.addDiscussPost
發帖后把帖子存入es
@Autowired
private EventProducer eventProducer
;
Event event
= new Event().setTopic(TOPIC_PUBLISH
).setUserId(user
.getId()).setEntityType(ENTITY_TYPE_POST
).setEntityId(post
.getId());
eventProducer
.fireEvent(event
);
CommunityConstant 中增加常量
String TOPIC_PUBLISH
= "publish";
3. CommentController.addComment
觸發評論帖子事后后觸發發帖事件
if (comment
.getEntityType() == ENTITY_TYPE_POST
) {event
= new Event().setTopic(TOPIC_PUBLISH
).setUserId(comment
.getUserId()).setEntityType(ENTITY_TYPE_POST
).setEntityId(discussPostId
);eventProducer
.fireEvent(event
);
}
4. EventConsumer.handlePublishMessage
消費發帖事件
@KafkaListener(topics
= {TOPIC_PUBLISH
})
public void handlePublishMessage(ConsumerRecord record) {if (record == null || record.value() == null) {logger
.error("消息的內容為空!");return;}Event event
= JSONObject.parseObject(record.value().toString(), Event.class);if (event
== null) {logger
.error("消息格式錯誤!");return;}DiscussPost post
= discussPostService
.findDiscussPostById(event
.getEntityId());elasticsearchService
.saveDiscussPost(post
);
}
5. SearchController
5.1 注入屬性
@Autowired
private ElasticsearchService elasticsearchService
;@Autowired
private UserService userService
;@Autowired
private LikeService likeService
;
5.2 搜索帖子
調用service查詢把數據存入一個map把數據傳給模板傳遞分頁信息
@RequestMapping(path
= "/search", method
= RequestMethod.GET
)
public String search(String keyword
, Page page
, Model model
) {org.springframework.data.domain.Page<DiscussPost> searchResult
=elasticsearchService
.searchDiscussPost(keyword
, page
.getCurrent() - 1, page
.getLimit());List<Map<String, Object>> discussPosts
= new ArrayList<>();if (searchResult
!= null) {for (DiscussPost post
: searchResult
) {Map<String, Object> map
= new HashMap<>();map
.put("post", post
);map
.put("user", userService
.findUserById(post
.getUserId()));map
.put("likeCount", likeService
.findEntityLikeCount(ENTITY_TYPE_POST
, post
.getId()));discussPosts
.add(map
);}}model
.addAttribute("discussPosts", discussPosts
);model
.addAttribute("keyword", keyword
);page
.setPath("/search?keyword=" + keyword
);page
.setRows(searchResult
== null ? 0 : (int) searchResult
.getTotalElements());return "/site/search";
}
6. index.html
<form class="form-inline my-2 my-lg-0" method="get" th:action="@{/search}"><input class="form-control mr-sm-2" type="search" aria-label="Search" name="keyword" th:value="${keyword}"/><button class="btn btn-outline-light my-2 my-sm-0" type="submit">搜索
</button>
</form>
7. search.html
模板路徑頭部復用js路徑遍歷
<li class="media pb-3 pt-3 mb-3 border-bottom" th:each="map:${discussPosts}">
頭像
<img th:src="${map.user.headerUrl}" class="mr-4 rounded-circle" alt="用戶頭像" style="width:50px;height:50px;">
標題
<h6 class="mt-0 mb-3"><a th:href="@{|/discuss/detail/${map.post.id}|}" th:utext="${map.post.title}">備戰
<em>春招
</em>,面試刷題跟他復習,一個月全搞定!
</a>
</h6>
帖子作者
<u class="mr-3" th:utext="${map.user.username}">寒江雪
</u>
發布時間,贊,回復信息
發布于
<b th:text="${#dates.format(map.post.createTime,'yyyy-MM-dd HH:mm:ss')}">2019-04-15 15:32:18
</b>
<ul class="d-inline float-right"><li class="d-inline ml-2">贊
<i th:text="${map.likeCount}">11
</i></li><li class="d-inline ml-2">|
</li><li class="d-inline ml-2">回復
<i th:text="${map.post.commentCount}">7
</i></li>
</ul>
分頁復用
<nav class="mt-5" th:replace="index::pagination"><ul class="pagination justify-content-center"><li class="page-item"><a class="page-link" href="#">首頁
</a></li><li class="page-item disabled"><a class="page-link" href="#">上一頁
</a></li><li class="page-item active"><a class="page-link" href="#">1
</a></li><li class="page-item"><a class="page-link" href="#">2
</a></li><li class="page-item"><a class="page-link" href="#">3
</a></li><li class="page-item"><a class="page-link" href="#">4
</a></li><li class="page-item"><a class="page-link" href="#">5
</a></li><li class="page-item"><a class="page-link" href="#">下一頁
</a></li><li class="page-item"><a class="page-link" href="#">末頁
</a></li></ul>
</nav>
總結
以上是生活随笔為你收集整理的牛客网项目——项目开发(八):开发社区搜索功能的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。