【问题标题】:Migrating from Hit/Hits to TopDocs/TopDocCollector从 Hit/Hits 迁移到 TopDocs/TopDocCollector
【发布时间】:2009-06-10 01:47:46
【问题描述】:

我有类似的现有代码:

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 重写代码以及如何迭代所有结果。

【问题讨论】:

    标签: java lucene


    【解决方案1】:

    基本上,您必须决定对预期结果数量的限制。然后在生成的TopDocs 中遍历所有ScoreDocs。

    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" ) );
        // ...
    }
    

    【讨论】:

    • 除了我想要所有结果。 (我希望它的功能更像 grep。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2012-12-04
    • 2011-04-26
    • 2015-07-23
    • 2020-05-31
    • 2010-10-26
    相关资源
    最近更新 更多