lucene.net索引文件存储简析

在lucene.net中,典型的索引文件操作代码如下:
IndexWriter writer = new IndexWriter("c:/index", new StandardAnalyzer(), true);
try
{
   Document doc = new Document();
   doc.Add(Field.Keyword("name", "name name");
   doc.Add(Field.Text("title", "title title");
   doc.Add(Field.Text("content", "content content");
   writer.AddDocument();
}
finally{    
   writer.Optimize();
   writer.Close();
}

在上面的代码中:
IndexWriter专门用于索引文件的写入操作;
StandardAnalyzer是一个分析器,用于对要索引的内容进行切分处理;
Document表示一条被索引的记录;

下面简单分析一下索引文件的创建过程

01. 创建IndexWriter

IndexWriter有几个重载的构造函数,它们都调用私有构造函数
private IndexWriter(Directory d, Analyzer a, bool create, bool closeDir) {
// 初始化及锁定处理略...
   lock (directory) {
   // in- & inter-process sync
      new AnonymousClassWith(create, this, directory.MakeLock(IndexWriter.COMMIT_LOCK_NAME), COMMIT_LOCK_TIMEOUT).Run();
   }
}
参数Directory是Lucene.net内实现的一个存储结构,它有基于文件系统的FSDirectory和基于内存的RAMDirectory两个版本;
Analyzer为分析器,用于索引内容的切分,StandardAnalyzer是Lucene.net内的一个标准的分析器实现,支持中英文,不过中文是按单字切分的;
create指定是否创建索引目录,如果要在同一文件夹内进行增量索引,create应设置为false;

AnonymousClassWith是一个辅助类,用于完成索引目录的初始化操作,
// class Lock.With (lock.cs)
public virtual Object Run() {
bool locked = false;
try {
   locked = lock_Renamed.Obtain(lockWaitTimeout);
   return DoBody();
}
finally {
   if (locked)
    lock_Renamed.Release();
}
}
先取得一个操作锁对象,然后进行具体的操作,避免多个线程同时进行一项操作。
关于lucene的锁操作在后续文章中介绍,

// class IndexWriter.AnonymousClassWith
public override Object DoBody() {
if (create)
   Enclosing_Instance.segmentInfos.Write(Enclosing_Instance.directory);
else
   Enclosing_Instance.segmentInfos.Read(Enclosing_Instance.directory);
return null;
}
根据create的值决定是新索引目录(Write)还是使用现有索引目录(Read);
segmentInfos用于记录索引目录下的索引文件信息.

// class SegmentInfos
public void Write(Directory directory) {
OutputStream output = directory.CreateFile("segments.new");
try {
   output.WriteInt(FORMAT); // write FORMAT
   output.WriteLong(++version); // ever

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值