如何提交网站给百度,外贸网站建设行业发展情况,江西网站开发多少钱,济南网站建设平台官网环境搭建参考#xff1a;mongodb#xff1a;环境搭建_Success___的博客-CSDN博客 需求#xff1a; 在文章搜索服务中实现保存搜索记录到mongdb 并在搜索时查询出mongdb保存的数据 1、安装mongodb依赖 dependencygroupIdorg.springframework.data/groupI…环境搭建参考mongodb环境搭建_Success___的博客-CSDN博客 需求 在文章搜索服务中实现保存搜索记录到mongdb 并在搜索时查询出mongdb保存的数据 1、安装mongodb依赖 dependencygroupIdorg.springframework.data/groupIdartifactIdspring-data-mongodb/artifactId/dependency
2、创建数据库对应实体类
package com.heima.model.common.search;import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;import java.io.Serializable;
import java.util.Date;/*** p* APP用户搜索信息表* /p* author itheima*/
Data
Document(ap_user_search)
public class ApUserSearch implements Serializable {private static final long serialVersionUID 1L;/*** 主键*/private String id;/*** 用户ID*/private Integer userId;/*** 搜索词*/private String keyword;/*** 创建时间*/private Date createdTime;}
3、配置nacos
spring:data:mongodb:host: 192.168.200.130port: 27017database: leadnews-history
实现保存
1、在搜索服务的service层新增搜索历史保存方法insert
package com.heima.search.service;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.search.UserSearchDto;import java.io.IOException;public interface ArticleSearchService {/*文章搜索*/ResponseResult search(UserSearchDto dto) throws IOException;/*** 保存用户搜索历史记录* param keyword* param userId*/void insert(String keyword,Integer userId);}2、实现类
package com.heima.search.service.impl;import com.heima.model.common.search.ApUserSearch;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;import java.util.Date;
import java.util.List;Service
Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {AutowiredMongoTemplate mongoTemplate;/*** 保存用户搜索历史记录* param keyword* param userId*/OverrideAsyncpublic void insert(String keyword, Integer userId) {/*查询当前用户搜索的关键字*///构造查询条件Query query Query.query(Criteria.where(userid).is(userId).and(keyword).is(keyword));//执行mongodb库的查询ApUserSearch userSearch mongoTemplate.findOne(query, ApUserSearch.class);/*存在则更新创建时间重新保存*/if(userSearch ! null) {userSearch.setCreatedTime(new Date());mongoTemplate.save(userSearch);return;}/*不存在判断当前搜索记录数量是否超过10条*/userSearch new ApUserSearch();userSearch.setUserId(userId);userSearch.setKeyword(keyword);userSearch.setCreatedTime(new Date());//构造搜索条件Query query1 Query.query(Criteria.where(userId).is(userId));query1.with(Sort.by(Sort.Direction.DESC,createdTime));//执行查询ListApUserSearch list mongoTemplate.find(query1, ApUserSearch.class);//判断listif(list null || list.size() 10){mongoTemplate.save(userSearch);}else {//获取mongodb中最后一条数据就ApUserSearch apUserSearch list.get(list.size() - 1);//findAndReplace:根据查询条件替换库中的数据mongoTemplate.findAndReplace(Query.query(Criteria.where(id).is(apUserSearch.getId())),userSearch);}}}3、在文章搜索方法search中异步调用上面实现的保存记录方法 注意异步调用的方法需要在方法上加Async 注解并在工程启动类加入EnableAsynczh注解开启异步 Async是 Spring 框架提供的注解用于将方法标记为异步执行的方法。它的作用是告诉 Spring 框架在调用被注解的方法时将其放入线程池中异步执行而不是阻塞等待方法的完成。 service层完整代码如下
package com.heima.search.service.impl;import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.search.ApUserSearch;
import com.heima.model.common.search.UserSearchDto;
import com.heima.model.common.user.ApUser;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;Service
Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {AutowiredRestHighLevelClient restHighLevelClient;AutowiredMongoTemplate mongoTemplate;/*文章搜索*/Overridepublic ResponseResult search(UserSearchDto dto) throws IOException {//参数校验//1.检查参数if(dto null || StringUtils.isBlank(dto.getSearchWords())){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}ApUser user AppThreadLocalUtil.getUser();//异步调用 保存搜索记录if(user ! null dto.getFromIndex() 0){insert(dto.getSearchWords(), user.getId());}//2.设置查询条件SearchRequest searchRequest new SearchRequest(app_info_article);SearchSourceBuilder searchSourceBuilder new SearchSourceBuilder();//布尔查询BoolQueryBuilder boolQueryBuilder QueryBuilders.boolQuery();//关键字的分词之后查询QueryStringQueryBuilder queryStringQueryBuilder QueryBuilders.queryStringQuery(dto.getSearchWords()).field(title).field(content).defaultOperator(Operator.OR);boolQueryBuilder.must(queryStringQueryBuilder);//查询小于mindate的数据
// RangeQueryBuilder rangeQueryBuilder QueryBuilders.rangeQuery(publishTime).lt(dto.getMinBehotTime().getTime());
// boolQueryBuilder.filter(rangeQueryBuilder);//分页查询searchSourceBuilder.from(0);searchSourceBuilder.size(dto.getPageSize());//按照发布时间倒序查询searchSourceBuilder.sort(publishTime, SortOrder.DESC);//设置高亮 titleHighlightBuilder highlightBuilder new HighlightBuilder();highlightBuilder.field(title);highlightBuilder.preTags(font stylecolor: red; font-size: inherit;);highlightBuilder.postTags(/font);searchSourceBuilder.highlighter(highlightBuilder);searchSourceBuilder.query(boolQueryBuilder);searchRequest.source(searchSourceBuilder);SearchResponse searchResponse restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//3.结果封装返回ListMap list new ArrayList();SearchHit[] hits searchResponse.getHits().getHits();for (SearchHit hit : hits) {String json hit.getSourceAsString();Map map JSON.parseObject(json, Map.class);//处理高亮if(hit.getHighlightFields() ! null hit.getHighlightFields().size() 0){Text[] titles hit.getHighlightFields().get(title).getFragments();String title org.apache.commons.lang.StringUtils.join(titles);//高亮标题map.put(h_title,title);}else {//原始标题map.put(h_title,map.get(title));}list.add(map);}return ResponseResult.okResult(list);}/*** 保存用户搜索历史记录* param keyword* param userId*/OverrideAsyncpublic void insert(String keyword, Integer userId) {/*查询当前用户搜索的关键字*///构造查询条件Query query Query.query(Criteria.where(userid).is(userId).and(keyword).is(keyword));//执行mongodb库的查询ApUserSearch userSearch mongoTemplate.findOne(query, ApUserSearch.class);/*存在则更新创建时间重新保存*/if(userSearch ! null) {userSearch.setCreatedTime(new Date());mongoTemplate.save(userSearch);return;}/*不存在判断当前搜索记录数量是否超过10条*/userSearch new ApUserSearch();userSearch.setUserId(userId);userSearch.setKeyword(keyword);userSearch.setCreatedTime(new Date());//构造搜索条件Query query1 Query.query(Criteria.where(userId).is(userId));query1.with(Sort.by(Sort.Direction.DESC,createdTime));//执行查询ListApUserSearch list mongoTemplate.find(query1, ApUserSearch.class);//判断listif(list null || list.size() 10){mongoTemplate.save(userSearch);}else {//获取mongodb中最后一条数据就ApUserSearch apUserSearch list.get(list.size() - 1);//findAndReplace:根据查询条件替换库中的数据mongoTemplate.findAndReplace(Query.query(Criteria.where(id).is(apUserSearch.getId())),userSearch);}}}4、测试
前端输入搜索内容 查看数据库mongdb中的数据成功添加 下一篇Mongodb业务应用2_Success___的博客-CSDN博客
文章转载自: http://www.morning.rqkck.cn.gov.cn.rqkck.cn http://www.morning.pxlpt.cn.gov.cn.pxlpt.cn http://www.morning.rnlx.cn.gov.cn.rnlx.cn http://www.morning.nafdmx.cn.gov.cn.nafdmx.cn http://www.morning.hkcjx.cn.gov.cn.hkcjx.cn http://www.morning.bsjpd.cn.gov.cn.bsjpd.cn http://www.morning.ptxwg.cn.gov.cn.ptxwg.cn http://www.morning.jwfqq.cn.gov.cn.jwfqq.cn http://www.morning.lztrt.cn.gov.cn.lztrt.cn http://www.morning.dhqzc.cn.gov.cn.dhqzc.cn http://www.morning.xxrgt.cn.gov.cn.xxrgt.cn http://www.morning.xyyplp.cn.gov.cn.xyyplp.cn http://www.morning.qgjxt.cn.gov.cn.qgjxt.cn http://www.morning.ymbqr.cn.gov.cn.ymbqr.cn http://www.morning.kxxld.cn.gov.cn.kxxld.cn http://www.morning.yrbhf.cn.gov.cn.yrbhf.cn http://www.morning.yubkwd.cn.gov.cn.yubkwd.cn http://www.morning.jlboyuan.cn.gov.cn.jlboyuan.cn http://www.morning.ylkkh.cn.gov.cn.ylkkh.cn http://www.morning.gtbjc.cn.gov.cn.gtbjc.cn http://www.morning.kttbx.cn.gov.cn.kttbx.cn http://www.morning.wtbzt.cn.gov.cn.wtbzt.cn http://www.morning.qdrrh.cn.gov.cn.qdrrh.cn http://www.morning.brbmf.cn.gov.cn.brbmf.cn http://www.morning.kzcz.cn.gov.cn.kzcz.cn http://www.morning.mphfn.cn.gov.cn.mphfn.cn http://www.morning.sdamsm.com.gov.cn.sdamsm.com http://www.morning.rqckh.cn.gov.cn.rqckh.cn http://www.morning.tgqzp.cn.gov.cn.tgqzp.cn http://www.morning.nyfyq.cn.gov.cn.nyfyq.cn http://www.morning.sbwr.cn.gov.cn.sbwr.cn http://www.morning.dhbyj.cn.gov.cn.dhbyj.cn http://www.morning.mknxd.cn.gov.cn.mknxd.cn http://www.morning.ngjpt.cn.gov.cn.ngjpt.cn http://www.morning.nfnxp.cn.gov.cn.nfnxp.cn http://www.morning.jrksk.cn.gov.cn.jrksk.cn http://www.morning.rrwgh.cn.gov.cn.rrwgh.cn http://www.morning.ybgt.cn.gov.cn.ybgt.cn http://www.morning.cpmfp.cn.gov.cn.cpmfp.cn http://www.morning.tzkrh.cn.gov.cn.tzkrh.cn http://www.morning.plnry.cn.gov.cn.plnry.cn http://www.morning.xnpml.cn.gov.cn.xnpml.cn http://www.morning.yrjkp.cn.gov.cn.yrjkp.cn http://www.morning.rbmnq.cn.gov.cn.rbmnq.cn http://www.morning.rtlg.cn.gov.cn.rtlg.cn http://www.morning.hympq.cn.gov.cn.hympq.cn http://www.morning.egmux.cn.gov.cn.egmux.cn http://www.morning.ypmqy.cn.gov.cn.ypmqy.cn http://www.morning.xpqdf.cn.gov.cn.xpqdf.cn http://www.morning.tqsgt.cn.gov.cn.tqsgt.cn http://www.morning.lrprj.cn.gov.cn.lrprj.cn http://www.morning.ljllt.cn.gov.cn.ljllt.cn http://www.morning.rltw.cn.gov.cn.rltw.cn http://www.morning.gklxm.cn.gov.cn.gklxm.cn http://www.morning.fosfox.com.gov.cn.fosfox.com http://www.morning.xq3nk42mvv.cn.gov.cn.xq3nk42mvv.cn http://www.morning.tsmxh.cn.gov.cn.tsmxh.cn http://www.morning.ttxnj.cn.gov.cn.ttxnj.cn http://www.morning.qbdqc.cn.gov.cn.qbdqc.cn http://www.morning.zmtrk.cn.gov.cn.zmtrk.cn http://www.morning.ktrzt.cn.gov.cn.ktrzt.cn http://www.morning.rqnhf.cn.gov.cn.rqnhf.cn http://www.morning.mkpkz.cn.gov.cn.mkpkz.cn http://www.morning.tthmg.cn.gov.cn.tthmg.cn http://www.morning.ysdwq.cn.gov.cn.ysdwq.cn http://www.morning.ckcjq.cn.gov.cn.ckcjq.cn http://www.morning.zqbrd.cn.gov.cn.zqbrd.cn http://www.morning.kqbjy.cn.gov.cn.kqbjy.cn http://www.morning.kdjtt.cn.gov.cn.kdjtt.cn http://www.morning.ltkms.cn.gov.cn.ltkms.cn http://www.morning.nyqzz.cn.gov.cn.nyqzz.cn http://www.morning.kzhxy.cn.gov.cn.kzhxy.cn http://www.morning.srmpc.cn.gov.cn.srmpc.cn http://www.morning.hkysq.cn.gov.cn.hkysq.cn http://www.morning.znkls.cn.gov.cn.znkls.cn http://www.morning.ftrpvh.cn.gov.cn.ftrpvh.cn http://www.morning.clgbb.cn.gov.cn.clgbb.cn http://www.morning.bphqd.cn.gov.cn.bphqd.cn http://www.morning.kjyhh.cn.gov.cn.kjyhh.cn http://www.morning.bqdpy.cn.gov.cn.bqdpy.cn