分布式 Lucene 中的索引数据
分布式 Lucene 通过对文档进行索引来实现高效搜索,其中需要创建索引并将其存储在目录中。 第一步是 初始化 存放索引的目录。 与 Lucene.NET 不同, NCacheDirectory
用于通过指定缓存名称和索引名称打开目录。
备注
此功能也可用于 NCache Professional.
备注
索引目录的默认路径是 C:\ ProgramData \ncache\lucene-index\{CACHE_NAME}\data 对于 Windows,以及 /用户/分享/ncache/lucene-index/{CACHE_NAME}/数据 对于 Linux。
目录初始化后, IndexWriter
通过提供的实例打开 NCacheDirectory
和 索引写入器配置. IndexWriter
使用与 Lucene.NET 中相同的机制在索引上添加和索引文档,使用 AddDocument
方法。
备注
对于缓存服务器之间的文档分布, NCache 自动添加一个 TextField
用 DocKey
字段和自动生成的 GUID 值到文档(如果用户未指定)。
对索引执行的所有写入操作都是同步的。 因此,它们仅在完成上述操作后才会返回给用户。 这增加了分布式 Lucene 的数据一致性和完整性。
重要
对于写入器的任何写操作,我们需要调用 Commit
将其保存到文档目录。 需要调用commit,否则不会保存写入操作,还可能影响添加文档的搜索操作。
与 Lucene.NET 不同,您可以在同一目录中打开多个编写器以进行并行索引。 写文件的时候, IndexWriter.Commit
被调用来持久化文档并使其可搜索。 一旦 IndexWriter
用于索引数据, IndexWriter.Dispose
需要调用以释放正在使用的资源。
Tips:
您可以使用 NCache 提供 Boolean
财产 IndexWriter.OperationsCompleted
.
先决条件
索引数据
下面的例子首先打开 NCacheDirectory
通过将缓存名称指定为 Lucene缓存 索引名称为 产品索引. 然后它打开一个 IndexWriter
在指定的目录上通过指定 空白分析器 用于分析数据。
警告
索引写操作是不允许的 部分簇.
// Specify the Distributed-Lucene cache name
string cache = "LuceneCache";
// Specify the index name to create the indexes
string indexName = "ProductIndex";
NCacheDirectory ncacheDirectory = null;
IndexWriter indexWriter = null;
//Initializing
// Create a directory and open it on the cache and the index path
ncacheDirectory = NCacheDirectory.Open(cache, indexName);
// Specify the analyzer used to analyze data
Analyzer analyzer = new WhitespaceAnalyzer(LuceneVersion.LUCENE_48);
// 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 = new IndexWriter(ncacheDirectory, new IndexWriterConfig
(LuceneVersion.LUCENE_48, _analyzer));
// Indexing
// Add the products information that is to be indexed
Product[] products = FetchProductsFromDB();
foreach (var prod in products)
{
// Create a document and add fields to it
Document doc = new Document();
doc.Add(new TextField("ProductID", prod.ProductID.ToString(),
Field.Store.YES));
doc.Add(new TextField("ProductName", prod.ProductName, Field.Store.NO));
doc.Add(new TextField("Category", prod.Category, Field.Store.YES));
doc.Add(new TextField("Description", prod.Description, Field.Store.YES));
// Writer is created previously
indexWriter.AddDocument(doc);
}
// Calling commit on the writer saves all the write operations
indexWriter.Commit();
if(indexWriter.OperationsCompleted)
{
// All writing operations are complete
// Can proceed with other operations such as querying
}
// Dispose the indexWriter after indexing
if (indexWriter != null) indexWriter.Dispose();
// Dispose the ncacheDirectory
if (ncacheDirectory != null) ncacheDirectory.Dispose();
备注
你应该打电话 Dispose
在每次结束时 writer
实例,否则,它存在于内存中并导致内存泄漏。
更多资讯
NCache 提供了分布式 Lucene 的示例应用程序 GitHub上.
参见
.NET: Lucene.Net.索引 命名空间。