![](/img/trans.png)
[英]Most efficient way to retrieve all element of a Dictionary from a list of keys?
[英]What's the most efficient way to retrieve all matching documents from a query in Lucene, unsorted?
我希望執行查詢以保持內部完整性; 例如,從索引中刪除特定字段/值的所有跟蹤。 因此,重要的是我找到所有匹配的文檔(不僅僅是前n個文檔),但它們返回的順序是無關緊要的。
根據文檔,看起來我需要使用Searcher.Search( Query, Collector )
方法,但是沒有內置的Collector類可以滿足我的需要。
我應該為此目的派生自己的收藏家嗎? 這樣做時我需要記住什么?
事實證明,這比我預期的要容易得多。 我剛剛在http://lucene.apache.org/java/2_9_0/api/core/org/apache/lucene/search/Collector.html上使用了示例實現,並記錄了傳遞給Collect()
方法的文檔編號。列表,將其公開為公共Docs
屬性。
然后我簡單地迭代這個屬性,將數字傳遞給Searcher
以獲取正確的Document
:
var searcher = new IndexSearcher( reader );
var collector = new IntegralCollector(); // my custom Collector
searcher.Search( query, collector );
var result = new Document[ collector.Docs.Count ];
for ( int i = 0; i < collector.Docs.Count; i++ )
result[ i ] = searcher.Doc( collector.Docs[ i ] );
searcher.Close(); // this is probably not needed
reader.Close();
到目前為止,它似乎在初步測試中運行良好。
更新:這是IntegralCollector
的代碼:
internal class IntegralCollector: Lucene.Net.Search.Collector {
private int _docBase;
private List<int> _docs = new List<int>();
public List<int> Docs {
get { return _docs; }
}
public override bool AcceptsDocsOutOfOrder() {
return true;
}
public override void Collect( int doc ) {
_docs.Add( _docBase + doc );
}
public override void SetNextReader( Lucene.Net.Index.IndexReader reader, int docBase ) {
_docBase = docBase;
}
public override void SetScorer( Lucene.Net.Search.Scorer scorer ) {
}
}
如果您只是想要獲取索引中的所有Document對象,則無需編寫命中收集器。 只需從0循環到maxDoc()並在每個doc id上調用reader.document(),確保跳過已刪除的文檔:
for (int i=0; i<reader.maxDoc(); i++) {
if (reader.isDeleted(i))
continue;
results[i] = reader.document(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.