我现有的代码如下:
final Term t = /* ... */;
final Iterator i = searcher.search( new TermQuery( t ) ).iterator();
while ( i.hasNext() ) {
Hit hit = (Hit)i.next();
// "FILE" is the field that recorded the original file indexed
File f = new File( hit.get( "FILE" ) );
// ...
}
我不清楚如何使用TopDocs
/ TopDocCollector
重写代码以及如何迭代所有结果。
答案 0 :(得分:24)
基本上,您必须决定对预期结果数量的限制。然后,迭代生成的ScoreDoc
中的所有TopDocs
。
final MAX_RESULTS = 10000;
final Term t = /* ... */;
final TopDocs topDocs = searcher.search( new TermQuery( t ), MAX_RESULTS );
for ( ScoreDoc scoreDoc : topDocs.scoreDocs ) {
Document doc = searcher.doc( scoreDoc.doc )
// "FILE" is the field that recorded the original file indexed
File f = new File( doc.get( "FILE" ) );
// ...
}
这基本上是Hits
类所做的,只是它设置 50 结果的限制,如果你迭代过去,那么重复搜索,这通常是浪费。这就是它被弃用的原因。
已添加:如果没有限制,您可以使用HitCollector:
final Term t = /* ... */;
final ArrayList<Integer> docs = new ArrayList<Integer>();
searcher.search( new TermQuery( t ), new HitCollector() {
public void collect(int doc, float score) {
docs.add(doc);
}
});
for(Integer docid : docs) {
Document doc = searcher.doc(docid);
// "FILE" is the field that recorded the original file indexed
File f = new File( doc.get( "FILE" ) );
// ...
}