您的位置:首页 > 其它

开发搜索引擎初步(二)搜索(Lucene实现)

2011-09-24 17:14 441 查看
经过上一篇的经验,想必大家对建立索引应该没有什么问题了,下面我们就开始最简单的搜索,也就是对我们已经建立好的索引进行检索,废话不多说,下面看代码


package com.dreamers.search;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexSearch {
private String INDEX_STORE_PATH = "d:\\LuceneDemo";//注意,此处的PATH为你的索引在磁盘中的存放位置
public void search(){
try{
Directory directory = FSDirectory.open(new File(INDEX_STORE_PATH));//建立库,导入索引
System.out.println("使用索引搜索");
IndexSearcher searcher = new IndexSearcher(directory);//初始化搜索的类,在Lucene中
Term t = new Term("publisher","历城二中");//构建搜索初始化元
Query q = new TermQuery(t);
Date begin = new Date();//建立时间,以便显示搜索用时
ScoreDoc[] hits = searcher.search(q,null,1000).scoreDocs;//将搜索到的资源放入数组
System.out.println("共找到 " + hits.length + " 个文档符合条件");
for (int i = 0; i < hits.length; i++){
Document doc = new Document();//遍历资源
doc = searcher.doc(hits[i].doc);
System.out.print("文件名为: ");
System.out.print(doc.get("title"));
System.out.print(".");
System.out.println(doc.get("kind"));
System.out.print("地址为 : ");
System.out.println(doc.get("url"));
System.out.print("描述: ");
System.out.println(doc.get("describe"));
System.out.print("scores is :");
System.out.println(hits[i].score);
System.out.print("作者为:");
System.out.println(doc.get("author"));
System.out.println("---------------------------------------------------");
}
Date end = new Date();
long time = end.getTime()-begin.getTime();
System.out.print("搜索用时 " + time + "ms");
}catch(IOException x){
x.printStackTrace();
}
}

public static void main(String [] args){
IndexSearch search = new IndexSearch();
search.search();//测试
}

}


通过这个程序,我们可以很简单的实现对自己的在磁盘上面建立的索引文件进行按照自己的想法进行索引,呵呵,下面的工作就是自己去实现了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: