首页 >> 大全

16.app端文章搜索

2023-06-20 大全 62 作者:考证青年

一、app端文章搜索 1、搭建环境 1.1拉取镜像

docker pull elasticsearch:7.4.0

1.2创建容器

docker run -id --name elasticsearch -d --restart=always -p 9200:9200 -p 9300:9300 -v /usr/share/elasticsearch/plugins:/usr/share/elasticsearch/plugins -e "discovery.type=single-node" elasticsearch:7.4.0

1.3 配置中文分词器 ik

因为在创建容器的时候,映射了目录,所以可以在宿主机上进行配置ik中文分词器

在去选择ik分词器的时候,需要与的版本好对应上

#切换目录
cd /usr/share/elasticsearch/plugins
#新建目录
mkdir analysis-ik
cd analysis-ik
#root根目录中拷贝文件
mv elasticsearch-analysis-ik-7.4.0.zip /usr/share/elasticsearch/plugins/analysis-ik
#解压文件
cd /usr/share/elasticsearch/plugins/analysis-ik
unzip elasticsearch-analysis-ik-7.4.0.zip

2.需求分析

思路分析

为了加快检索的效率,在查询的时候不会直接从数据库中查询文章,需要在中进行高速检索。

image-20221209133629802

3.创建索引和映射

使用添加映射

put请求 : :9200/

{"mappings":{"properties":{"id":{"type":"long"},"publishTime":{"type":"date"},"layout":{"type":"integer"},"images":{"type":"keyword","index": false},"staticUrl":{"type":"keyword","index": false},"authorId": {"type": "long"},"authorName": {"type": "text"},"title":{"type":"text","analyzer":"ik_smart"},"content":{"type":"text","analyzer":"ik_smart"}}}
}

4. 数据初始化到索引库

查询所有的文章信息,批量导入到es索引库中

package com.heima.es;import com.alibaba.fastjson.JSON;
import com.heima.es.mapper.ApArticleMapper;
import com.heima.es.pojo.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@SpringBootTest
@RunWith(SpringRunner.class)
public class ApArticleTest {@Autowiredprivate ApArticleMapper apArticleMapper;@Autowiredprivate RestHighLevelClient restHighLevelClient;/*** 注意:数据量的导入,如果数据量过大,需要分页导入* @throws Exception*/@Testpublic void init() throws Exception {//1.查询所有符合条件的文章数据List<SearchArticleVo> searchArticleVos = apArticleMapper.loadArticleList();//2.批量导入到es索引库BulkRequest bulkRequest = new BulkRequest("app_info_article");for (SearchArticleVo searchArticleVo : searchArticleVos) {IndexRequest indexRequest = new IndexRequest().id(searchArticleVo.getId().toString()).source(JSON.toJSONString(searchArticleVo), XContentType.JSON);//批量添加数据bulkRequest.add(indexRequest);}restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);}}

查询所有的es中数据 GET请求: :9200//

5. 文章搜索功能实现 5.1 搭建搜索微服务 1.)添加依赖


<dependency><groupId>org.elasticsearch.clientgroupId><artifactId>elasticsearch-rest-high-level-clientartifactId><version>7.4.0version>
dependency>
<dependency><groupId>org.elasticsearch.clientgroupId><artifactId>elasticsearch-rest-clientartifactId><version>7.4.0version>
dependency>
<dependency><groupId>org.elasticsearchgroupId><artifactId>elasticsearchartifactId><version>7.4.0version>
dependency>

2)nacos配置中心

spring:autoconfigure:exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
elasticsearch:host: 192.168.200.130port: 9200

3)ler

package com.heima.search.controller.v1;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.UserSearchDto;import com.heima.search.service.ArticleSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;@RestController
@RequestMapping("/api/v1/article/search")
public class ArticleSearchController {@Autowiredprivate ArticleSearchService articleSearchService;/*** es分页检索* @param dto* @return*/@PostMapping("/search")public ResponseResult articleSerache(@RequestBody UserSearchDto dto) throws IOException {ResponseResult responseResult = articleSearchService.articleSearch(dto);return responseResult;}
}

4)

package com.heima.search.service;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.UserSearchDto;import java.io.IOException;public interface ArticleSearchService {/*** es分页检索* @param dto* @return*/ResponseResult articleSearch(UserSearchDto dto) throws IOException;
}

5)实现

package com.heima.search.service.impl;import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.util.QueryBuilder;
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.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.stereotype.Service;import org.elasticsearch.common.text.Text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {@Autowiredprivate RestHighLevelClient restHighLevelClient;/*** es分页检索* @param dto* @return*/public ResponseResult articleSearch(UserSearchDto dto) throws IOException {//1.检查参数//1.检查参数if(dto == null || StringUtils.isBlank(dto.getSearchWords())){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}//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("");highlightBuilder.postTags("");searchSourceBuilder.highlighter(highlightBuilder);searchSourceBuilder.query(boolQueryBuilder);searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//3.结果封装返回List<Map> 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 = StringUtils.join(titles);//高亮标题map.put("h_title",title);}else {//原始标题map.put("h_title",map.get("title"));}list.add(map);}return ResponseResult.okResult(list);}}

6)dto入参

package com.heima.model.search.dtos;import lombok.Data;import java.util.Date;@Data
public class UserSearchDto {/*** 搜索关键字*/String searchWords;/*** 当前页*/int pageNum;/*** 分页条数*/int pageSize;/*** 最小时间*/Date minBehotTime;public int getFromIndex(){if(this.pageNum<1)return 0;if(this.pageSize<1) this.pageSize = 10;return this.pageSize * (pageNum-1);}
}

7)测试

需要在app的网关中添加搜索微服务的路由配置

#搜索微服务
- id: leadnews-searchuri: lb://leadnews-searchpredicates:- Path=/search/**filters:- StripPrefix= 1

启动项目进行测试,至少要启动文章微服务,用户微服务,搜索微服务,app网关微服务,app前端工程

二、文章自动审核构建索引 1.思路分析

image-20221209135232342

自媒体端发表文章(自媒体微服务,保存或修改文章,判断文章是否是草稿,保存文章内容图片与素材的关系,保存文章封面与素材的关系)

==>>添加任务到延迟队列(延迟微服务,在自媒体微服务用feign远程调用,创建task对象封装数据)

==>>消费任务审核文章,如果成功

==>>保存自媒体文章到app端(文章微服务)

==>>用为文章内容生成html上传至minio,创建对象封装数据向kafka发送信息让搜索微服务监听消息

===>>搜索微服务接收消息,添加数据到索引库

2.文章微服务发送消息

把放到model工程下

package com.heima.model.search.vos;import lombok.Data;import java.util.Date;@Data
public class SearchArticleVo {// 文章idprivate Long id;// 文章标题private String title;// 文章发布时间private Date publishTime;// 文章布局private Integer layout;// 封面private String images;// 作者idprivate Long authorId;// 作者名词private String authorName;//静态urlprivate String staticUrl;//文章内容private String content;}

在文章微服务为文章内容生成html上传至minio后,创建对象封装数据向kafka发送信息让搜索微服务监听消息

@Autowiredprivate KafkaTemplate<String,String> kafkaTemplate;/**文章自动审核构建索引** @param article* @param content* @param path*/private void createArticleEsIndex(ApArticle article, String content, String path) {SearchArticleVo searchArticleVo = new SearchArticleVo();BeanUtils.copyProperties(article, searchArticleVo);searchArticleVo.setContent(content);searchArticleVo.setStaticUrl(path);kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));}

类常量

package com.heima.common.constants;public class ArticleConstants {public static final Short LOADTYPE_LOAD_MORE = 1;public static final Short LOADTYPE_LOAD_NEW = 2;public static final String DEFAULT_TAG = "__all__";public static final String ARTICLE_ES_SYNC_TOPIC = "article.es.sync.topic";public static final Integer HOT_ARTICLE_LIKE_WEIGHT = 3;public static final Integer HOT_ARTICLE_COMMENT_WEIGHT = 5;public static final Integer HOT_ARTICLE_COLLECTION_WEIGHT = 8;public static final String HOT_ARTICLE_FIRST_PAGE = "hot_article_first_page_";
}

在文章微服务的nacos的配置中心添加如下配置

kafka:bootstrap-servers: 192.168.200.130:9092producer:retries: 10key-serializer: org.apache.kafka.common.serialization.StringSerializervalue-serializer: org.apache.kafka.common.serialization.StringSerializer

3.搜索微服务接收消息并创建索引

1.搜索微服务中添加kafka的配置,nacos配置如下

spring:kafka:bootstrap-servers: 192.168.200.130:9092consumer:group-id: ${spring.application.name}key-deserializer: org.apache.kafka.common.serialization.StringDeserializervalue-deserializer: org.apache.kafka.common.serialization.StringDeserializer

2.定义监听接收消息,保存索引数据

package com.heima.search.listener;import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;import java.io.IOException;@Component
@Slf4j
public class SyncArticleListener {@Autowiredprivate RestHighLevelClient restHighLevelClient;@KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)public void onMessage(String message){if(StringUtils.isNotBlank(message)){log.info("SyncArticleListener,message={}",message);SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);IndexRequest indexRequest = new IndexRequest("app_info_article");indexRequest.id(searchArticleVo.getId().toString());indexRequest.source(message, XContentType.JSON);try {restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();log.error("sync es error={}",e);}}}
}

三、app端搜索-搜索记录 3.1 需求分析 3.2 数据存储说明

用户的搜索记录,需要给每一个用户都保存一份,数据量较大,要求加载速度快,通常这样的数据存储到更合适,不建议直接存储到关系型数据库中

image-20221210131538585

3.3 安装及集成 安装

拉取镜像

docker pull mongo

创建容器

docker run -di --name mongo-service --restart=always -p 27017:27017 -v ~/data/mongodata:/data mongo

3.4 保存搜索记录 1)实现思路

image-20221210131813830

用户输入关键字进行搜索的异步记录关键字

image-20221210131847496

3.5 搜索微服务集成 1)pom依赖

<dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>

2)nacos配置

spring:data:mongodb:host: 192.168.200.130port: 27017database: leadnews-history

3) 用户搜索记录对应的集合,对应实体类:

package com.heima.search.pojos;import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;import java.io.Serializable;
import java.util.Date;/*** 

* APP用户搜索信息表*

* @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;}

4) .创建新增方法

package com.heima.search.service;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.HistorySearchDto;public interface ApUserSearchService {/*** 保存app端用户搜索记录*/void saveApUserSearche(String keyword,Integer userId);}

5) 实现


@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {@Autowiredprivate MongoTemplate mongoTemplate;/*** 保存用户搜索记录* 1.根据关键词与用户id查询ApUserSearch对象* 2.如果存在,更新一下时间再保存即可* 3.如果不存在,则要判断当前用户的搜索记录是否大于十,如果小于时,直接保存* 3.1先根据用户id查询所有的搜索记录,根据创建时间倒序查* 3.2 如果大于等于十,则把最后一条记录替换掉,最后一条记录是时间最早,最早的* @param keyword* @param userId*/@Asyncpublic void saveApUserSearche(String keyword, Integer userId) {//1.根据关键词与用户id查询ApUserSearch对象Criteria criteria = Criteria.where("keyword").is(keyword).and("userId").is(userId);Query query = Query.query(criteria);ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);//2.如果存在,更新一下时间再保存即可if(apUserSearch != null){apUserSearch.setCreatedTime(new Date());mongoTemplate.save(apUserSearch);return;}//3.如果不存在,则要判断当前用户的搜索记录是否大于十,如果小于时,直接保存//3.1先根据用户id查询所有的搜索记录,根据创建时间倒序查apUserSearch = new ApUserSearch();apUserSearch.setUserId(userId);apUserSearch.setKeyword(keyword);apUserSearch.setCreatedTime(new Date());Criteria criteria2 = Criteria.where("userId").is(userId);Query query2 = Query.query(criteria2);query2.with(Sort.by(Sort.Order.desc("createdTime")));List<ApUserSearch> apUserSearches = mongoTemplate.find(query2, ApUserSearch.class);//3.2if(apUserSearches == null && apUserSearches.size() < 10){mongoTemplate.save(apUserSearch);}else {//如果大于等于十,则把最后一条记录替换掉,最后一条记录是时间最早,最早的ApUserSearch lastUserSearch = apUserSearches.get(apUserSearches.size() - 1);mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),apUserSearch);}}

6)参考自媒体相关微服务,在搜索微服务中获取当前登录的用户(业务是异步调用,开启了另外一条线程,拿不到当前用户id) 7)在的方法中调用保存历史记录

//异步保存用户搜索记录Integer apUserId = ApUserThreadLocalUtil.getApUserId();if(apUserId != null && dto.getFromIndex() == 0){apUserSearchService.saveApUserSearche(dto.getSearchWords(), apUserId);}

8).保存历史记录中开启异步调用,添加注解@Async 9).在搜索微服务引导类上开启异步调用 四、加载搜索记录列表 4.1 思路分析

按照当前用户,按照时间倒序查询

说明

接口路径

/api/v1//load

请求方式

POST

参数

响应结果

4.2

/*** 

* APP用户搜索信息表 前端控制器*

** @author itheima*/
@Slf4j @RestController @RequestMapping("/api/v1/history") public class ApUserSearchController{/*** 查询用户历史搜索* @return*/@PostMapping("/load")public ResponseResult findUserSearch() {Integer apUserId = ApUserThreadLocalUtil.getApUserId();ResponseResult responseResult = apUserSearchService.findUserSearch(apUserId);return responseResult;}}

4.3 业务层

在中新增方法

 /*** 查询用户历史搜索* @return*/ResponseResult findUserSearch(Integer apUserId);

4.4 实现

 /*** 查询用户的历史搜索* @return*/@Overridepublic ResponseResult findUserSearch(Integer apUserId) {if(apUserId == null){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}Criteria criteria = Criteria.where("userId").is(apUserId);Query query = Query.query(criteria);query.with(Sort.by(Sort.Order.desc("createdTime")));List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);return ResponseResult.okResult(apUserSearches);}

五、删除搜索记录 5.1 思路分析

按照搜索历史id删除

说明

接口路径

/api/v1//del

请求方式

POST

参数

响应结果

5.2 接口定义

在er接口新增方法

 /*** 根据id删除历史搜索*/@PostMapping("/del")public ResponseResult delUserSearch(@RequestBody HistorySearchDto dto) {ResponseResult responseResult = apUserSearchService.delUserSearch(dto);return responseResult;}

@Data
public class HistorySearchDto {/*** 接收搜索历史记录id*/String id;
}

5.3 业务层

在中新增方法

 /**删除搜索历史@param historySearchDto@return*/
ResponseResult delUserSearch(HistorySearchDto historySearchDto);

5.4实现方法

/*** 删除历史记录** @param dto* @return*/
@Override
public ResponseResult delUserSearch(HistorySearchDto dto) {//1.检查参数if(dto.getId() == null){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}//2.判断是否登录ApUser user = AppThreadLocalUtil.getUser();if(user == null){return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);}//3.删除//3.构造查询条件Criteria criteria = Criteria.where("id").is(dto.getId()).and("userId").is(apUser.getId());Query query = Query.query(criteria);mongoTemplate.remove(query, ApUserSearch.class);return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}

陆、 app端搜索-关键字联想词

根据用户输入的关键字展示联想词

1.搜索词-数据来源

通常是网上搜索频率比较高的一些词,通常在企业中有两部分来源:

第一:自己维护搜索词

通过分析用户搜索频率较高的词,按照排名作为搜索词

第二:第三方获取

关键词规划师(百度)、5118、爱站网

2.功能实现 2.1 实体类

package com.heima.search.pojos;import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;import java.io.Serializable;
import java.util.Date;/*** 

* 联想词表*

** @author itheima*/
@Data @Document("ap_associate_words") public class ApAssociateWords implements Serializable {private static final long serialVersionUID = 1L;private String id;/*** 联想词*/private String associateWords;/*** 创建时间*/private Date createdTime;}

2.2.


package com.heima.search.controller.v1;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/api/v1/associate")
public class ApAssociateWordsController {@Autowiredprivate ApAssociateWordsService apAssociateWordsService;/*** 当用户搜索输入关键字,查询关键字联想词* @param dto* @return*/@PostMapping("/search")public ResponseResult search(@RequestBody UserSearchDto dto) {ResponseResult responseResult = apAssociateWordsService.search(dto);return responseResult;}
}

2.3 业务层

package com.heima.search.service;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.UserSearchDto;public interface ApAssociateWordsService {//查询关键字联线词ResponseResult search(UserSearchDto dto);
}

2.4 实现

package com.heima.search.service.impl;import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;import java.util.List;@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {@Autowiredprivate MongoTemplate mongoTemplate;/*** 查询关键字联线词* @param dto* @return*/public ResponseResult search(UserSearchDto dto) {//1.参数校验if(dto == null  || StringUtils.isBlank(dto.getSearchWords())){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}//分页if(dto.getPageSize() > 20){dto.setPageSize(20);}// //3 执行查询 模糊查询(正则表达式)Criteria criteria = Criteria.where("associateWords").regex(".*?\\" + dto.getSearchWords() + ".*");Query query = Query.query(criteria);query.limit(dto.getPageSize());List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);return ResponseResult.okResult(apAssociateWords);}
}

work.data..core.query.;

org..data..core.query.Query;

org...;

java.util.List;

@

@Slf4j

class ice {

@Autowired
private MongoTemplate mongoTemplate;
/*** 查询关键字联线词* @param dto* @return*/
public ResponseResult search(UserSearchDto dto) {//1.参数校验if(dto == null  || StringUtils.isBlank(dto.getSearchWords())){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}//分页if(dto.getPageSize() > 20){dto.setPageSize(20);}// //3 执行查询 模糊查询(正则表达式)Criteria criteria = Criteria.where("associateWords").regex(".*?\\" + dto.getSearchWords() + ".*");Query query = Query.query(criteria);query.limit(dto.getPageSize());List apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);return ResponseResult.okResult(apAssociateWords);
}

}


关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了