全文检索compass

来源:互联网 发布:linux 删除php扩展 编辑:程序博客网 时间:2024/04/29 01:56
文章出处:我的博客 我的生活

compass
compass是开源的java搜索引擎框架,建立在Lucene搜索引擎的基础之上的。是对Lucene搜索引擎在企业应用(数据库应用)中的增强。

在全文检索(lucene)开发和关于jforum2.1.6的检索问题(采用lucene实现)两篇文章中都是讨论关于全文检索的。这里想描述一下如何利用compass框架来实现这一功能。

在实际的项目中,一般都会涉及到数据库,如何保证数据库的增删改变实时的映射到索引文件中去,compass就是最佳的选择。
如果你采用了Hibernate等ORM方案,你只须在POJO中进行annotation注释,或者采用AOP的方式,自动变更索引。
如果你采用了JDBC,也可以在XML文件中加以配置,Compasss定时进行更新。Compasss还支持事务处理。
没有Compasss的话,一般会采用比如深夜重建一次索引,或是采用一个线程类来定时建立或重建索引,在关于jforum2.1.6的检索问题(采用lucene实现)中就是这样实现的,可以去参考一下。
当然从效率、实时性、安全性来说,Compasss是一个好的选择,而且开发起来也比较方便。
Compasss和Spring很好的结合了起来,在Compasss的包内专门设置了Spring的相关操作,比如和Spring MVC的操作:org.compass.spring.web.mvc.CompassIndexController来建立索引,如果换成Struts 来开发的话,需要作些调整,当然动作不会很大,模仿CompassIndexController就可以了。

这里给出一个小例子,以作参考,是采用了Hibernate-ORM方案实现,同时采用了Spring、Struts:
首先是POJO类:
@Searchable(alias = "customer")
public class Customer {
@SearchableId
private String guid;

@SearchableProperty(name = "customerName")
private String customerName;
......
}

然后是Compass的具体实现,由于采用了Struts,所以改造相应的建立索引和检索的类。
/**
* 仿照 {@link org.compass.spring.web.mvc.CompassIndexController}
* 中的代码,构建了一个Service(建立索引),方便不使用Spring MVC的实现
*
* @author Schweigen
* @see org.compass.spring.web.mvc.CompassIndexController
* @see org.compass.spring.web.mvc.AbstractCompassGpsCommandController
*/
public class CompassIndexService implements InitializingBean {
private CompassGps compassGps;

public void afterPropertiesSet() throws Exception {
if (compassGps == null) {
throw new IllegalArgumentException("Must set the compassGpd property");
}
}

/**
* 建立索引的接口
*
* @param command 里面doIndex 为"true",则执行构建索引,并将构建时间封装入{@link org.compass.spring.web.mvc.CompassIndexResults}
* 中<br>
* 否则,不做任何操作,返回null
* @return
* @see org.compass.spring.web.mvc.CompassIndexResults
*/
public CompassIndexResults index(CompassIndexCommand command) {
if (StringUtils.isBlank(command.getDoIndex()) || !command.getDoIndex().equalsIgnoreCase("true")) {
return null;
}

long time = System.currentTimeMillis();

// 建立索引
getCompassGps().index();

time = System.currentTimeMillis() - time;
CompassIndexResults indexResults = new CompassIndexResults(time);

return indexResults;
}

public CompassGps getCompassGps() {
return compassGps;
}

public void setCompassGps(CompassGps compassGps) {
this.compassGps = compassGps;
}
}

然后建立一个检索的类CompassSearchService,这里比较长,就不列出来了,可以去提供下载的地方一并下载

最后是有关Spring的配置,这个很重要,相关的服务都在这里进行配置,这里就不列出了,可提供下载,具体的有一些注释描述,需要Spring的相关知识,可以自行阅读,这里采用了springside的相关实现,以在实际项目中使用。

可去提供下载