对数据源进行分析,是为建立索引服务的;为指定的文件建立索引,是为检索服务的。

对数据源分析,使用Lucene的分析器(Analyzer),根据分析器所得到的词条,构造一个索引器IndexWriter。索引器IndexWriter的功能主要就是创建索引,是建立索引工作中最核心的。

当构造完一个索引器IndexWriter之后,就可以向其中添加Document了。

在前面Lucene-2.2.0 源代码阅读学习(1)中,根据Lucene提供的一个Demo,详细分析研究一下索引器org.apache.lucene.index.IndexWriter类,看看它是如果定义的,掌握它建立索引的机制。

通过IndexWriter类的实现源代码可知,它包含的内容相当丰富了。乍一看无从入手,不知道从何处去分析。可以通过Lucene提供的Demo的,根据它的实现过程l来一点点地解析。

在Demo中,实例化一个索引器:

IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true);

它使用的IndexWriter的一个构造函数,定义如下所示:

public IndexWriter(String path, Analyzer a, boolean create)
       throws CorruptIndexException, LockObtainFailedException, IOException {
    init(FSDirectory.getDirectory(path), a, create, true, null, true);
}

这个构造函数具有三个参数:

path   :根据一个字符串描述的路径,为建立的索引文件指定存放目录。

a        :一个分析器。

create:它是一个boolean型变量,如果为true,表示要重写指定的存放索引目录下的索引文件;如果为false,表示在指定存放索引目录下已经存在的索引文件的基础上,向其中继续追加新的索引文件。

简单做个测试吧:

package org.shirdrn.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.LockObtainFailedException;

public class MyIndexWriterTest {
public static void main(String[] args) throws Exception {
   String path = "E:\\index";
   Analyzer a = new StandardAnalyzer();
   IndexWriter myWriter = new IndexWriter(path,a,true);
}
}

这里没有指定要进行建立索引的文件,因此,应该是“建立空索引”。这里,指定了create的值为true,是新建索引文件。

这里,只是实例化了一个IndexWriter索引器,并没有建立索引。建立索引的过程是在一个IndexWriter索引器实例存在的前提下,通过为其添加Document,这样才能真正就爱你里索引。

运行程序,可以在指定的索引文件的存放目录E:\\index下看到生成的三个与索引有关的文件:

segments.gen     (大小为1K)
segments_1        (大小为1K)
write.lock             (大小为0K)

如果再次运行程序,会发现文件segments_1变成了segments_2,再次运行还会变成segments_3……,这就说明参数create为true表示重写现存的索引文件。

如果第一次执行上述程序,指定create为false,由于指定的索引目录下面缺少被追加索引的索引文件,将会抛出异常:

Exception in thread "main" java.io.FileNotFoundException: no segments* file found in org.apache.lucene.store.FSDirectory@E:\index: files:
at org.apache.lucene.index.SegmentInfos$FindSegmentsFile.run(SegmentInfos.java:516)
at org.apache.lucene.index.SegmentInfos.read(SegmentInfos.java:249)
at org.apache.lucene.index.IndexWriter.init(IndexWriter.java:616)
at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:360)
at org.shirdrn.lucene.MyIndexWriterTest.main(MyIndexWriterTest.java:22)

从异常来看,追加索引在现存的索引文件的基础上追加。

如果指定的索引目录下已经存在一些索引文件,并且指定create的值为false,则执行向已存在的索引文件中追加索引,就可以看到索引目录下面的文件不会发生变化,程序执行会因为write.lock文件而抛出异常:

Exception in thread "main" org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out: SimpleFSLock@E:\index\write.lock
at org.apache.lucene.store.Lock.obtain(Lock.java:70)
at org.apache.lucene.index.IndexWriter.init(IndexWriter.java:598)
at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:360)
at org.shirdrn.lucene.MyIndexWriterTest.main(MyIndexWriterTest.java:22)

继续看上面IndexWriter的构造函数的函数体内容:

init(FSDirectory.getDirectory(path), a, create, true, null, true);

IndexWriter的构造函数初始化,调用了一个init方法,init方法在IndexWriter类中有具体实现,它还有一个重载的init方法。先看这里用到的这个,它的实现代码如下所示:

/**
* 该方法中的参数列表中。各个参数的含义如下:
* d :指定的存放建立索引文件的索引目录
* a :一个传递进来分析器
* create :是否要重新写入索引文件,如果为true,则重写索引文件;如果为false,则追加写入索引文件
* closeDir :一个boolean型变量,表示是否关闭索引目录Directory d,与IndexWriter的一个成员变量相关
* deletionPolicy :指定删除索引文件使用的策略
* autoCommit :建立索引文件后,自动提交。
*/

private void init(Directory d, Analyzer a, final boolean create, boolean closeDir, IndexDeletionPolicy deletionPolicy, boolean autoCommit)
    throws CorruptIndexException, LockObtainFailedException, IOException {
    this.closeDir = closeDir;
    directory = d;
    analyzer = a;
    this.infoStream = defaultInfoStream;    // infoStream是一个PrintStream输出流对象,在这里指定它为defaultInfoStream=null。PrintStream类继承自FilterOutputStream,主要是对建立索引文件过程中的输出流进行管理

    if (create) {
     
// 如果是残留索引文件,则清除写锁文件write.lock
      directory.clearLock(IndexWriter.WRITE_LOCK_NAME);
    }

    Lock writeLock = directory.makeLock(IndexWriter.WRITE_LOCK_NAME);
    if (!writeLock.obtain(writeLockTimeout))    // 获取写锁文件
      throw new LockObtainFailedException("Index locked for write: " + writeLock);
    this.writeLock = writeLock;                   // 重新保存写锁文件

    try {
      if (create) {    // 如果create为true,表示重写索引文件。重写索引文件之前,要先读取已经存在的索引文件,并且要清除掉历史写入的segment信息
        try {
          segmentInfos.read(directory);
          segmentInfos.clear();
        } catch (IOException e) {
        }
        segmentInfos.write(directory);    // 向指定的索引存放目录中写入segment信息
      } else {    // 如果create为false,只是读取,并不予以清除,因为是追加写入索引文件
        segmentInfos.read(directory);
      }

      this.autoCommit = autoCommit;    //   执行提交写入索引的标志
      if (!autoCommit) {   
// 如果如果提交写入索引失败,要回滚到原来的状态
        rollbackSegmentInfos = (SegmentInfos) segmentInfos.clone();    // 克隆
      }

      //   默认的删除策略实现类为KeepOnlyLastCommitDeletionPolicy,它只是保证将最近提交删除的索引文件,提交删除动作

     // IndexFileDeleter deleter是IndexWriter类的一个私有的成员变量,它在org.apache.lucene.index包里面,主要对删除索引文件进行实现和管理
      deleter = new IndexFileDeleter(directory,
                                     deletionPolicy == null ? new KeepOnlyLastCommitDeletionPolicy() : deletionPolicy,segmentInfos, infoStream);

    } catch (IOException e) {
      this.writeLock.release();   
// 索引写入完成之后,要释放写锁
      this.writeLock = null;
      throw e;
    }
}

通过IndexWriter索引器的构造函数,以及它初始化时调用的一个init方法,可以了解一个IndexWriter索引器的构造最重要的是在init方法中的初始化工作。它主要实现了根据指定的建立索引的方式(重写、追加写入),通过create标志位来判断,从而指定一种在操作索引文件的过程中删除索引文件的策略。

必须深入地理解IndexWriter索引器初始化的过程,以及在构造一个IndexWriter索引器过程中涉及到的一些其他的类,应该深入研究这些相关的类的定义。这样才能有助于深化IndexWriter索引器构造的原理机制。

可见,IndexWriter索引器的构造相当复杂,但是却非常重要。

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐