代码 如下:
Searcher searcher = new IndexSearcher(indexDir);
// Query query = MultiFieldQueryParser.parse(keyVal, fields, analyzer);
QueryParser q=new QueryParser("title",new StandardAnalyzer());
Query query = q.parse("中国");
StandardAnalyzer analyzer=new StandardAnalyzer();
Hits hits = searcher.search(query);
Highlighter highlighter = new Highlighter(new QueryScorer(query));
//整数型的ID检索结果排序只要进行以下的简单操作:
// Sort sort = new Sort("id");
// Hits hits = searcher.search(query, sort);
System.out.println("len="+hits.length());
if(hits != null){
for(int i = 0;i < hits.length(); i++){
Document doc = hits.doc(i);
System.out.println("found in " + doc.get("title"));
System.out.println("summary = " + doc.get("summary"));
System.out.println(doc.get("url"));
TokenStream tokenStream = analyzer.tokenStream("title", new StringReader( doc.get("title")));
// Get 3 best fragments and seperate with a "..."
String result = highlighter.getBestFragments(tokenStream, doc.get("title"), 3, "...");
// System.out.println(result);
}
}
searcher.close();
注意: 该方法是是 利用 lunece 1.9api 其他版本 写法不同,请参考 api
在 创建索引时,需要记录索引位置
IndexWriter indexWriter = new IndexWriter(indexDir, new StandardAnalyzer(), true);
indexWriter.mergeFactor = 2; //修正lucene 1.4.2 bug,不添加则不合并原有索引
for( int i=0;i HashMap map=(HashMap)list.get(i);
Document doc = new Document();
doc.add(new Field("title",(String)map.get("title"), Field.Store.YES, Field.Index.TOKENIZED,Field.TermVector.WITH_POSITIONS_OFFSETS));
// Add the summary as a field that is stored and returned with
// hit documents for display.
doc.add(new Field("summary","summary", Field.Store.YES, Field.Index.NO));
// Add the title as a field that it can be searched and that is stored.
doc.add(new Field("url", (String)map.get("url"), Field.Store.YES, Field.Index.NO));
indexWriter.addDocument(doc);
// System.out.println("加入:"+(String)map.get("content"));
}
indexWriter.optimize(); //合并索引并优化
indexWriter.close();
阅读(2669) | 评论(0) | 转发(0) |