Java code
/**
* 查询
*
* @param String word 关键词
* @param String filedName 域字段
* @param String indexDir 索引位置
* @throws CorruptIndexException
* @throws IOException
* @throws ParseException
* @auther Gao XuGuo Nov 30, 2009
* 2:56:42 PM
*/
public List < Map < String, String >> search(String indexDir)
throws CorruptIndexException, IOException, ParseException {
File file = new File(indexDir);
IndexSearcher is = new IndexSearcher(FSDirectory.open(file), true );
String field = " content " ;
BooleanQuery bq = new BooleanQuery();
QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field,
new StandardAnalyzer(Version.LUCENE_CURRENT));
Query query = parser.parse( " content:王熙凤 " );
Query q = new TermQuery( new Term( " id " , " 100 " ));
bq.add(q,Occur.SHOULD);
bq.add(query,Occur.SHOULD);
// 100表示取前100条数据
TopScoreDocCollector collector = TopScoreDocCollector.create( 100 , true );
long start = new Date().getTime(); // start time
/**
* Lucene内置了三个Filter子类:
* 1)DateFilter使搜索只限于指定的日期域的值在某一时间范围内的文档空间里
* 2)QueryFilter把查询结果做为另一个新查询可搜索的文档空间
* 3)CachingWrappperFilter是其他过滤器的装饰器,将结果缓存起来以便再次使用,从而提高性能。
*
*/
String[] dirs = {indexDir};
MultiSearcher ms = this .getMultiSearcher(dirs);
ms.search(bq, collector);
// is.search(bq, collector);
ScoreDoc[] docs = collector.topDocs().scoreDocs;
Document doc;
for (ScoreDoc sd : docs) {
doc = is.doc(sd.doc);
// 取得doc里面的Field并从doc里面读取值
for (Fieldable fa : doc.getFields()) {
System.out.print(fa.name() + " = " + doc.get(fa.name()) + " " );
}
System.out.println();
}
long end = new Date().getTime();
if (is != null ) is.close();
System.out.println( " 找到 " + collector.getTotalHits()
+ " 条数据,花费时间 " + (end - start)
+ " 秒 " );
return null ;
}
/**
* 得到MultiSearcher多目录查询实例
*
* @param String[] dirs 要查询的索引目录。
*
* @return MultiSearcher
* @throws IOException
* @auther Gao XuGuo
* Jan 22, 2010 3:44:16 PM
*/
private MultiSearcher getMultiSearcher(String[] dirs) throws IOException {
// 多目录
IndexSearcher [] searchers = new IndexSearcher[dirs.length];
int i = 0 ;
for (String dir : dirs) {
searchers[i] = new IndexSearcher(FSDirectory.open( new File(dir)), true );
i ++ ;
}
// 多目录查询
return new MultiSearcher(searchers);
}