/**
* 查詢
*
* @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);
}