在分布式 Lucene 中搜索
对数据建立索引后执行搜索。 要搜索数据, NCacheDirectory
传递给 IndexReader
. 可以通过一个索引打开多个索引阅读器 IndexWriter
或 NCacheDirectory
. 的实例 IndexReader
传递给 IndexSearcher
。 该 IndexSearcher
负责根据给定的查询搜索数据。 Lucene 提供了广泛的查询,分布式 Lucene 支持所有的 Lucene 查询。
备注
此功能也可用于 NCache Professional.
Lucene.Net.Search.TopDocs.TotalHits
表示执行搜索后获得的最佳结果的数量。 对于分布式 Lucene,该值是从 integer
至 long
. 同样, Lucene.Net.Search.ScoreDocs.Doc
, Lucene.Net.Index.IndexReader.NumDoc
及 Lucene.Net.Index.IndexReader.MaxDocs
也都是从 integer
至 long
.
在分布式 Lucene 中,如果删除一个 Document
并打电话 commit
,您仍然可以阅读已删除的内容 Document
通过一个实例 IndexReader
, 前提是这个 IndexReader
在您制作之前已打开 commit
调用(删除后)。 如果您处理掉这个 IndexReader
在你之后 commit
调用然后重新打开它,你将无法阅读已删除的内容 Document
.
即使集群处于运行状态,您也可以检索结果 部分的. NCache 分布式 Lucene 提供了 AllowPartialResults
可以设置为的标志 TRUE
用于检索部分数据。 默认情况下,它的值为 FALSE
.
先决条件
搜索数据
下面的代码示例演示了如何使用分布式 Lucene 搜索索引文档。
IndexReader reader = null;
IndexSearcher indexSearcher = null;
// Create a directory and open it on the cache and the index path
NCacheDirectory ncacheDirectory = NCacheDirectory.Open("demoCache",
"luceneIndex");
// Specify lucene version and analyzer type
LuceneVersion version = LuceneVersion.LUCENE_48;
Analyzer analyzer = new WhitespaceAnalyzer(version);
// Create an indexWriterConfig which holds all the configurations to create an instance of the writer
IndexWriterConfig config = new IndexWriterConfig(LuceneVersion.
LUCENE_48, analyzer);
// Create an instance of the writer
IndexWriter indexWriter = new IndexWriter(ncacheDirectory, new
IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer));
// Open a new reader instance
// The 'applyAllDeletes' is set to true which means all enqueued deletes will be applied on the writer
reader = indexWriter.GetReader(true);
// OR
// reader = DirectoryReader.Open(indexWriter, true);
// OR
// reader = DirectoryReader.Open(ncacheDirectory, 1);
// Allow partial results in case of partial connectivity with cluster
reader.AllowPartialResults = true;
// A searcher is opened to perform searching
indexSearcher = new IndexSearcher(reader);
// Specify the searchTerm and the fieldName
string searchTerm = "Beverages";
string fieldName = "Category";
// Specify lucene version and analyzer type
LuceneVersion version = LuceneVersion.LUCENE_48;
Analyzer analyzer = new WhitespaceAnalyzer(version);
// Create a query parser and parse the query with the parser
QueryParser parser = new QueryParser(version, fieldName,
analyzer);
Query query = parser.Parse(searchTerm);
// Returns the top 10000 hits from the result set
ScoreDoc[] docsFound = indexSearcher.Search(query, 10000).
ScoreDocs;
// Please make sure that no operations should be performed after calling this
if (indexSearcher != null) indexSearcher.Dispose();
if (reader != null) reader.Dispose();
备注
你应该打电话 Dispose
在每次结束时 reader
实例,否则,它存在于内存中并导致内存泄漏。
更多资讯
NCache 提供了一个示例应用程序,用于在 Distributed Lucene 上搜索文档 GitHub上.
参见
.NET: Lucene.Net.搜索 命名空间。