基于数据库的全文检索实现

news/2024/4/28 0:59:52

对于内容摘要,信件内容进行全文检索
基于SpringBoot 2.5.6+Postgresql+jpa+hibernate实现

依赖

<spring-boot.version>2.5.6</spring-boot.version>
<hibernate-types-52.version>2.14.0</hibernate-types-52.version><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- hibernate支持配置 -->
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId>
</dependency>
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-ehcache</artifactId>
</dependency>
<dependency><groupId>com.vladmihalcea</groupId><artifactId>hibernate-types-52</artifactId><version>${hibernate-types-52.version}</version>
</dependency>
<!-- hibernate支持配置 --><dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId>
</dependency><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>

业务逻辑

登记保存之后,处理完成业务逻辑,发送全文检索事件

//附加类型对应的附件ids
Map<String, List<String>> attCategoryToAttIds = new HashMap<String, List<String>>();
attCategoryToAttIds.put(cmpRecord.getFileCategory(), files==null?null:files.stream().map(d->d.getId()).collect(Collectors.toList()));
//处理监听事件所需要的数据
Map<String,Object>eventData = Utils.buildMap("recordId", cmpRecord.getId(),"newRecord", true,"attCategoryToAttIds", attCategoryToAttIds);
//创建全文检索事件
DomainEvent de = new DefaultDomainEvent(cmpRecord.getId() + "_Handle_CmpRecord_FullTextSearch", operateInfo, ExecutePoint.CURR_THREAD,eventData, new Date(), "Handle_CmpRecord_FullTextSearch");
//发布事件
DomainEventPublisherFactory.getRegisteredPublisher().publishEvent(de);

处理业务发送全文检索事件

@Service
@Transactional
@SuppressWarnings("unchecked")
public class HandleCmpRecordFullTextSearchListener implements IDomainEventListener {@Autowiredprivate CmpRecordRepository cmpRecordRepository;@Autowiredprivate DataChangeLogEventRepository dataChangeLogEventRepository;@Overridepublic void onEvent(DomainEvent event) {AccessTokenUser operator=event.getOperator();Date operateTime=event.obtainEventTime();Map<String,Object> otherData=(Map<String,Object>)event.getEventData();String recordId = (String) otherData.get("recordId");boolean newRecord=(boolean)otherData.get("newRecord");String comment = (String) otherData.get("comment");//办理记录的备注if(StringUtils.isBlank(recordId)) {throw new RuntimeException("未指定信访记录id");}//获取登记信息CmpRecord cmdRecord = cmpRecordRepository.getCmpRecordById(recordId);//指定关联关系RelateProjValObj cmpRdProj=new RelateProjValObj(recordId,RelateProjConstants.PROJTYPE_CMP_RECORD); //这是关联那个业务List<RelateProjValObj> mainProjs=Arrays.asList(cmpRdProj);DomainEvent de=null;//登记信息是无效的 则删除已存在的和这个件相关的if(cmdRecord==null||!cmdRecord.isValidEntity()) {//删除全文检索信息de=new FullTextSearchOperateEvent(recordId+"_FullTextSearch_Remove", null, operator, operateTime,mainProjs, null);DomainEventPublisherFactory.getRegisteredPublisher().publishEvent(de);return;}//全文检索 类型前缀 String contentTypepPefix=RelateProjConstants.PROJTYPE_CMP_RECORD;//在当前线程中执行,保证事务一致性ExecutePoint executePoint=ExecutePoint.CURR_THREAD;/***********************************************关键词检索-内容摘要***********************************************///全文检索的类型 区分内容摘要 附件内容List<String> contentTypes=Arrays.asList(contentTypepPefix+"_contentAbstract");String contentAbstract =cmdRecord.getBaseInfo().getContentAbstract();//内容摘要if(StringUtils.isBlank(contentAbstract)) contentAbstract="";if(StringUtils.isNotBlank(comment)) {if(StringUtils.isNotBlank(contentAbstract)) contentAbstract=contentAbstract + ",";contentAbstract=contentAbstract+comment;}de=new FullTextSearchOperateEvent(recordId+"_FullTextSearch_Update", executePoint, operator, operateTime,mainProjs, contentTypes, contentAbstract, null);DomainEventPublisherFactory.getRegisteredPublisher().publishEvent(de);/***********************************************关键词检索-信件内容***********************************************/contentTypes=Arrays.asList(contentTypepPefix+"_content");String content =cmdRecord.getBaseInfo().getContent();//信件内容de=new FullTextSearchOperateEvent(recordId+"_FullTextSearch_Update", executePoint, operator, operateTime,mainProjs, contentTypes, content, null);DomainEventPublisherFactory.getRegisteredPublisher().publishEvent(de);/***********************************************关键词检索-附件(原信等)***********************************************///如果附件也需要检索  设置attIds参数Map<String,List<String>> attCategoryToAttIds=(Map<String,List<String>>)otherData.get("attCategoryToAttIds");if(attCategoryToAttIds!=null && attCategoryToAttIds.size() > 0) {//按附件类型分开for (Map.Entry<String,List<String>> d : attCategoryToAttIds.entrySet()) {contentTypes=Arrays.asList(contentTypepPefix+"_att_"+d.getKey());List<String> attIds=d.getValue();//公文相关附件de=new FullTextSearchOperateEvent(recordId+"_att_"+d.getKey()+"_FullTextSearch_Update", executePoint,operator, operateTime, mainProjs, contentTypes, null, attIds);DomainEventPublisherFactory.getRegisteredPublisher().publishEvent(de);}}}@Overridepublic boolean listenOn(String eventType) {return "Handle_CmpRecord_FullTextSearch".equals(eventType);}
}

统一处理全文检索事件

@Service
@Transactional
public class FullTextSearchListener extends JpaHibernateRepository implements IDomainEventListener{@Autowiredprivate FullTextSearchRepository fullTextSearchRepository;@Autowiredprivate IFileSysService fileSysService;@Overridepublic void onEvent(DomainEvent event) {if("true".equals(BaseConstants.getProperty("prefetchingRecordNo", "false"))){return;}FullTextSearchOperateEvent de = null;if(event instanceof FullTextSearchOperateEvent) {de=(FullTextSearchOperateEvent)event;}if(de==null) {return;}if(FullTextSearchOperateEvent.EVENTTYPE_UPDATE.equals(de.getEventType())) {/**"mainProjs":List<RelateProjValObj> 必选"contentType":String 必选"content":String 可选"attIds":List<String> 可选  content与attIds都不存在 会删除对应关键词检索"relProjs":List<RelateProjValObj> 可选  指定的需要添加的关系"removeOtherRelProjs":false  可选  是否清除 指定relProjs以外的关联记录*/this.fullTextSearchUpdate(de);}else if(FullTextSearchOperateEvent.EVENTTYPE_REMOVE.equals(de.getEventType())) {/**"mainProjs":List<RelateProjValObj> 必选*/this.fullTextSearchRemoveByProjs(de);}}//关键词检索增加private void fullTextSearchUpdate(FullTextSearchOperateEvent de) {Date date=de.obtainEventTime();if(date==null) {date=new Date();}List<RelateProjValObj> mainProjs=de.getMainProjs();String contentType=null;if(de.getContentTypes()!=null&&de.getContentTypes().size()==1) {contentType=de.getContentTypes().get(0);}String content=de.getContent();List<String> attIds=de.getAttIds();if(mainProjs==null||mainProjs.size()==0||StringUtils.isBlank(contentType)) {throw new RuntimeException("数据指定错误");}Set<String> fullTextIds=new HashSet<String>();for (RelateProjValObj mainProj : mainProjs) {if(StringUtils.isBlank(mainProj.getProjId())||StringUtils.isBlank(mainProj.getProjType())) {continue;}fullTextIds.add(new FullTextSearch(mainProj,contentType,null,null).getId());}if(fullTextIds.size()==0) {throw new RuntimeException("数据指定错误");}//这是从附件中获取文本数据if(StringUtils.isBlank(content)&&attIds!=null) {content="";try {if(attIds.size()>0) {Map<String,String> attIdToContentMao=ThreadLocalCache.fetchAPIData(null,()->{return fileSysService.findFileContentByIds(attIds, true);});for (String attContent : attIdToContentMao.values()) {if(StringUtils.isBlank(attContent)) {continue;}if(StringUtils.isNotBlank(content)) {content+=",";}content+=RegExUtils.replaceAll(attContent, "\\u0000", "");//处理掉非法字符}}} catch (Exception e) {e.printStackTrace();}}//从数据库中获取已经存的List<FullTextSearch> oldFullTexts=this.fullTextSearchRepository.findFullTextSearchByIds(fullTextIds);Map<String,FullTextSearch> oldFullTextMap=oldFullTexts.stream().collect(Collectors.toMap(d->d.getId(),d->d));//遍历这次需要更新的记录for (RelateProjValObj mainProj : mainProjs) {if(StringUtils.isBlank(mainProj.getProjId())||StringUtils.isBlank(mainProj.getProjType())) {continue;}FullTextSearch fullText=new FullTextSearch(mainProj, contentType, content, date);FullTextSearch oldFullText=oldFullTextMap.get(fullText.getId());//旧的记录中已存在 则更新if(oldFullText!=null) {if(StringUtils.isBlank(content)) {//如果内容未空 则删除	this.fullTextSearchRepository.removeFullTextSearch(oldFullText);return;}//如果存在内容,则更新this.fullTextSearchRepository.updateFullTextSearchContent(fullText.getId(), content, date);}else {if(StringUtils.isBlank(content)) {return;}try {//否则 创建全文检索记录this.fullTextSearchRepository.createFullTextSearch(fullText);} catch (Exception e) {e.printStackTrace();return;}}}}//关键词检索删除  根据主相关件private void fullTextSearchRemoveByProjs(FullTextSearchOperateEvent de) {Date date=de.obtainEventTime();if(date==null) {date=new Date();}List<RelateProjValObj> mainProjs=de.getMainProjs();if(mainProjs==null||mainProjs.size()==0) {throw new RuntimeException("数据指定错误");}List<String> projKeys=new ArrayList<String>();for (RelateProjValObj mainProj : mainProjs) {projKeys.add(mainProj.getProjKey());}Map<String,Object> params=new HashMap<String,Object>();StringBuffer hql=new StringBuffer();hql.append("delete from ").append(FullTextSearch.class.getName()).append(" ");hql.append("where mainProj.projKey IN(:projKeys) ");params.put("projKeys", projKeys);if(de.getContentTypes()!=null&&de.getContentTypes().size()>0) {params.put("contentTypes", de.getContentTypes());}this.createHQLQueryByMapParams(hql.toString(), params).executeUpdate();}@Overridepublic boolean listenOn(String eventType) {return eventType.startsWith(FullTextSearchOperateEvent.class.getName());}
}

全文检索实体

@Entity
@Table(name="TV_FULLTEXT_SEARCH",indexes={@Index(name="idx_TV_FULLTEXT_SEARCH1",columnList="projKey"),@Index(name="idx_TV_FULLTEXT_SEARCH2",columnList="contentType")}
)
public class FullTextSearch extends IEntity {@Id@Column(length=200)private String id;private RelateProjValObj mainProj;//来源相关件@Lob@Type(type="org.hibernate.type.TextType")private String content;//检索内容@Column(length=100)private String contentType;//检索类型@Column(length=100)private Date lastUpdateDate;//最后更新时间public String getId() {return id;}public String getContent() {return content;}public String getContentType() {return contentType;}public RelateProjValObj getMainProj() {return mainProj;}public Date getLastUpdateDate() {return lastUpdateDate;}public FullTextSearch() {}public FullTextSearch(RelateProjValObj mainProj, String contentType,String content, Date lastUpdateDate) {this.id = mainProj.getProjKey()+"_"+contentType;this.mainProj = mainProj;this.content = content;this.contentType = contentType;this.lastUpdateDate = lastUpdateDate;if(this.lastUpdateDate==null){this.lastUpdateDate = new Date();}}}

存储数据格式

在这里插入图片描述
在这里插入图片描述

查询

sql大致就是这样的逻辑

select tv.id from tv_cmp_dw_query tv join tv_fulltext_search tvs on tv.id = tvs.proj_id where tvs.contet_type in () and conent like '%测试%'

事件处理机制请看另一篇文章
自定义事件处理机制

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.cpky.cn/p/10789.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

数字多空策略(实盘+回测+数据)

数量技术宅团队在CSDN学院推出了量化投资系列课程 欢迎有兴趣系统学习量化投资的同学&#xff0c;点击下方链接报名&#xff1a; 量化投资速成营&#xff08;入门课程&#xff09; Python股票量化投资 Python期货量化投资 Python数字货币量化投资 C语言CTP期货交易系统开…

Python之Web开发中级教程----ubuntu安装MySQL

Python之Web开发中级教程----ubuntu安装MySQL 进入/opt目录 cd /opt 更新软件源 sudo apt-get upgrade sudo apt-get update 3、安装Mysql server sudo apt-get install mysql-server 4、启动Mysql service mysql start 5、确认Mysql的状态 service mysql status 6、安全设…

使用Python分析网易云歌曲评论信息并可视化处理

目录 一、引言 二、数据获取与预处理 分析网页结构 编写爬虫代码 数据预处理 三、评论分析 情感分析 关键词提取 四、可视化处理 评论情感分布可视化 2. 关键词词云可视化 评论时间分布可视化 五、总结 一、引言 在数字化时代&#xff0c;音乐与我们的生活紧…

JJJ:改善ubuntu网速慢的方法

Ubuntu 系统默认的软件下载源由于服务器的原因&#xff0c; 在国内的下载速度往往比较慢&#xff0c;这时我 们可以将 Ubuntu 系统的软件下载源更改为国内软件源&#xff0c;譬如阿里源、中科大源、清华源等等&#xff0c; 下载速度相比 Ubuntu 官方软件源会快很多&#xff01;…

MySQL 搭建双主复制服务 并 通过 HAProxy 负载均衡

一、MySQL 搭建双主复制高可用服务 在数据库管理中&#xff0c;数据的备份和同步是至关重要的环节&#xff0c;而双主复制&#xff08;Dual Master Replication&#xff09;作为一种高可用性和数据同步的解决方案&#xff0c;通过让两个数据库实例同时充当主服务器和从服务器&…

C# 方法(函数)

文章目录 C# 方法&#xff08;函数&#xff09;简单示例程序代码运行效果 值传递和引用传递示例程序 运行效果按输出传递参数运行结果 C# 方法&#xff08;函数&#xff09; 简单示例 程序代码 访问的限制符 using System; using System.Collections.Generic; using Syste…