java - 从命中/命中迁移到 TopDocs/TopDocCollector

标签 java lucene

我有这样的现有代码:

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

最佳答案

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

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

关于java - 从命中/命中迁移到 TopDocs/TopDocCollector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/973354/

相关文章:

java - sleep 线程有时 sleep 时间超过所需时间

java - 如何将jcompilo作为gradle依赖项添加到android studio项目

java - 使用 FTPClient 检查目录是否存在

java.lang.NullPointerException : println needs a message soap 异常

hadoop - Lucene在Hadoop文件系统(HDFS)上建立索引

search - Solr分布式搜索与联合搜索相同吗?

java - 如何删除或更新 apache Lucene 中的文档

search - 使用 Solr 的 log4j 日志索引

java - 为什么 lucene 单字符通配符查询找到的文档比完全指定通配符时少?

java - 在 Android 应用程序开发中的一个文本字段和一项 Activity 中打印所有提取的电子邮件