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

这篇具有很好参考价值的文章主要介绍了基于数据库的全文检索实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

对于内容摘要,信件内容进行全文检索
基于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 {
    
    @Autowired
    private CmpRecordRepository cmpRecordRepository;
    @Autowired
    private DataChangeLogEventRepository dataChangeLogEventRepository;
    
    @Override
    public 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);
            }
        }
    }
    
    @Override
    public boolean listenOn(String eventType) {
        return "Handle_CmpRecord_FullTextSearch".equals(eventType);
    }
}

统一处理全文检索事件

@Service
@Transactional
public class FullTextSearchListener extends JpaHibernateRepository implements IDomainEventListener{
    
	@Autowired
	private FullTextSearchRepository fullTextSearchRepository;
	@Autowired
	private IFileSysService fileSysService;
	
    @Override
    public 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();
	}
	
	@Override
    public 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 '%测试%'

事件处理机制请看另一篇文章
自定义事件处理机制文章来源地址https://www.toymoban.com/news/detail-838720.html

到了这里,关于基于数据库的全文检索实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 实现全文检索的方法

    实现网站全文检索功能,可以采取多种方法,从简单的基于数据库的搜索到使用专门的全文检索系统。以下是一些常见的实现全文检索的方法: 1. **数据库全文索引**:    如果你的网站后端使用的是关系型数据库(如MySQL),大多数数据库管理系统都提供了全文索引的功能。

    2024年04月26日
    浏览(7)
  • Mysql 简单实现全文检索(FULLTEXT)

    版本支持 MySQL 5.6 以前的版本,只有 MyISAM 存储引擎支持全文索引; MySQL 5.6 及以后的版本,MyISAM 和 InnoDB 存储引擎均支持全文索引; 只有字段的数据类型为 char、varchar、text 及其系列才可以建全文索引。 按顺序操做: 1.修改数据库配置 etc/my.cnf 文件 [mysqld] 下面加入 ngram_token_s

    2024年02月09日
    浏览(7)
  • MySQL使用全文检索实现模糊搜索

    创建全文检索有两种方式 方式一: 方法二: in boolean mode(布尔模式): 可以为检索的字符串增加操作符,且不会像自然语言一样自动拆词查询并集(除非手动空格隔开) 全文检索模糊查询使用全文索引来提高搜索效率,可以快速查询大数据量中的模糊匹配结果。而LIKE模糊查

    2024年02月15日
    浏览(8)
  • ElasticSearch 实现分词全文检索 - SpringBoot 完整实现 Demo

    ElasticSearch 实现分词全文检索 - SpringBoot 完整实现 Demo

    需求 做一个类似百度的全文搜索功能 搜素自动补全(suggest) 分词全文搜索 所用的技术如下: ElasticSearch Kibana 管理界面 IK Analysis 分词器 SpringBoot 实现流程 可以通过 Canal 对 MySQL binlog 进行数据同步,或者 flink 或者 SpringBoot 直接往ES里添加数据 当前以 SpringBoot 直接代码同

    2024年02月03日
    浏览(6)
  • SpringBoot封装Elasticsearch搜索引擎实现全文检索

    注:本文实现了Java对Elasticseach的分页检索/不分页检索的封装 ES就不用过多介绍了,直接上代码: 创建Store类(与ES字段对应,用于接收ES数据) Elasticsearch全文检索接口:不分页检索 Elasticsearch全文检索接口:分页检索 本文实现了Java对Elasticsearch搜索引擎全文检索的封装 传入

    2024年02月04日
    浏览(18)
  • 【springboot微服务】Lucence实现Mysql全文检索

    目录 一、前言 1.1 常规调优手段 1.1.1 加索引 1.1.2 代码层优化 1.1.3 减少关联表查询

    2023年04月12日
    浏览(10)
  • MySQL全文检索临时代替ES实现快速搜索

    MySQL全文检索临时代替ES实现快速搜索

    引入 在MySQL 5.7.6之前,全文索引只支持英文全文索引,不支持中文全文索引,需要利用分词器把中文段落预处理拆分成单词,然后存入数据库。 从MySQL 5.7.6开始,MySQL内置了ngram全文解析器,用来支持中文、日文、韩文分词。 全文索引只支持InnoDB和MyISAM引擎,支持的类型为C

    2024年02月07日
    浏览(11)
  • Mysql 实现类似于 ElasticSearch 的全文检索功能

    ​ 一、前言 今天一个同事问我,如何使用 Mysql 实现类似于 ElasticSearch 的全文检索功能,并且对检索跑分?我当时脑子里立马产生了疑问?为啥不直接用es呢?简单好用还贼快。但是听他说,数据量不多,客户给的时间非常有限,根本没时间去搭建es,所以还是看一下

    2024年02月03日
    浏览(7)
  • SpringBoot整合Lucene实现全文检索【详细步骤】【附源码】

    SpringBoot整合Lucene实现全文检索【详细步骤】【附源码】

    同样,本文的出现,也是我的个人网站笑小枫搭建的过程中产生的,作为一个技术博客为主的网站,Mysql的搜索已经满足不了我的野心了,于是,我便瞄上了全文检索。最初,是打算直接使用比较熟悉的ES,但是考虑到部署ES额外的服务器资源开销,最后选择了Lucene,搭配IK分

    2024年02月04日
    浏览(6)
  • MySQL高级特性篇(3)-全文检索的实现与优化

    MySQL数据库全文检索是指对数据库中的文本字段进行高效地搜索和匹配。在MySQL数据库中,可以使用全文检索来实现快速的文本搜索功能,并且可以通过一些优化手段提高全文检索的性能。 全文检索是一种将搜索与自然语言处理技术结合起来的搜索方法。与传统的基于

    2024年02月19日
    浏览(10)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包