`
pandong8183
  • 浏览: 56081 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

研究Lucence(Java全文搜索引擎工具包)有感

    博客分类:
  • J2EE
 
阅读更多

Lucence是Java全文搜索引擎工具包,可以提供站内全文搜索,当前是否能做成像百度一样的搜索引擎,我就不知道了

首先来看看示例,先找个感觉

http://www.cdfast.cn/

这是本人近期完成的一个购物商城的项目,顶上的搜索就是用的Lucence实现全文搜索,当前这个网站暂时还未完全启用,处于测试阶段,所有商品信息都是胡编乱造的,如有雷同,不胜荣幸

例如:输入“CCD” 或者 “CCD 彩色 防水” 试试 ^_^

 

我认为,Lucence其实就是在系统中创建了一个查询索引,你可以理解为一个磁盘文件,然后将查询时需要的信息以某种方式保存的里面,然后当用户执行查询时,直接在这个磁盘文件中查找,并将结果显示出来。

当然这是我的理解,不对之处,请批评

接下来就是实际代码

1.首先导入jar包(自己想办法下载,百度一下即可)

lucene-core-3.0.2.jar
IKAnalyzer3.2.3Stable.jar

 

2.创建索引,以下代码是在struts2 + spring中使用的查询,只看我的思路,光看代码无意义

IndexWriter indexWriter = null;
ServletContext context = (ServletContext) ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
String indexUrl = context.getRealPath("/lucence/index");
File lucenceDir = new File(indexUrl);
// 如果存在直接读取,如果没有就创建
if (lucenceDir.exists()) {
	indexWriter = new IndexWriter(FSDirectory.open(lucenceDir), new IKAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED);
} else {
	indexWriter = new IndexWriter(FSDirectory.open(lucenceDir),new IKAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
}

 

 

3.将数据库中的信息按我需要的形式添加到索引中去

Document doc = new Document();
String brandName = "";//取得品牌信息
String typeName = "";//取得类别信息

//拼接总介绍信息,将商品描述的前200个字截取出来
String summary = brandName
				+ " "
				+ typeName
				+ " "
				+ WebUtil.splitAndFilterString(product.getProductDescription(),200);
// 拼接检索内容,包含商品名称,类别名称,品牌名称,关键字,简单描述,详细描述
StringBuffer content = new StringBuffer();
content.append(product.getProductProName());
content.append(" " + brandName);
content.append(" " + typeName);
content.append(" " + product.getProductKeywords());
content.append(" " + product.getProductSimpleDescription());
content.append(" " + WebUtil.filterString(product.getProductDescription()));
doc.add(new Field("uid", product.getProductId().toString(),Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("title", product.getProductProName(),Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("summary", summary, Field.Store.YES,Field.Index.NOT_ANALYZED));
doc.add(new Field("contents", content.toString(), Field.Store.YES,Field.Index.ANALYZED));
doc.add(new Field("modifyTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), Field.Store.YES,
Field.Index.NOT_ANALYZED));

 

4.最后添加到索引中

indexWriter.addDocument(doc);//将文档添加到索引中
indexWriter.optimize();//优化索引

 

5.查询索引中的信息

ServletContext context = (ServletContext) ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
IndexReader reader = IndexReader.open(FSDirectory.open(new File(context.getRealPath("/lucence/index"))), true);
IndexSearcher searcher = new IndexSearcher(reader);
// 在索引器中使用IKSimilarity相似度评估器
searcher.setSimilarity(new IKSimilarity());
// 使用IKQueryParser查询分析器构造Query对象
queryString = new String(queryString.getBytes("ISO-8859-1"),"UTF-8");
Query query = IKQueryParser.parse("contents", queryString);
TopDocs hits = searcher.search(query, curPage * 20);
if (hits.totalHits > 0) {
	int offset = (curPage - 1) * 20;
	int maxLength = 0;
	if (hits.totalHits - offset > 20) {
		maxLength = 20;
		maxPage = 0;
	} else {
		maxLength = hits.totalHits - offset;
		maxPage = 1;// 设置最后一页标志
	}

	for (int i = offset; i < offset + maxLength; i++) {
		SearchBean bean = new SearchBean();
		Document doc = searcher.doc(hits.scoreDocs[i].doc);
		bean.setUid(doc.get("uid"));
		bean.setTitle(doc.get("title"));
		bean.setSummary(doc.get("summary"));
		bean.setModifyTime(doc.get("modifyTime"));
		// 为title添加链接
		bean.setTitle("<a href='/product_show.do?productId=" + bean.getUid() + "'>" + bean.getTitle().trim() + "</a>");
		// 将关键字进行着色
		queryString = queryString.trim();
		String[] keys = queryString.split(" ");
		if (keys != null && keys.length > 0) {
			for (String curKey : keys) {
				bean.setTitle(bean.getTitle().replaceAll(curKey,"<span style='color:#d90a00;font-weight: bold;'>" + curKey + "</span>"));
				bean.setSummary(bean.getSummary().replace(curKey,"<span style='color:#d90a00;font-weight: bold;'>" + curKey + "</span>"));
			}
		} else {
			bean.setTitle(bean.getTitle().replaceAll(queryString,"<span style='color:#d90a00;font-weight: bold;'>" + queryString + "</span>"));
			bean.setSummary(bean.getSummary().replace(queryString, "<span style='color:#d90a00;font-weight: bold;'>" + queryString + "</span>"));
		}
		searchList.add(bean);
	}
} else {
	searchList = null;
}

 

分享到:
评论
2 楼 pandong8183 2011-10-20  
呵呵,这里只是提供了一个思路,具体还是要你自己写哈
1 楼 tancai0118 2011-10-20  
好东西····太感谢了···

相关推荐

Global site tag (gtag.js) - Google Analytics