lucene 3.0.0源码分析:索引中的文档总数
文档数总的来说是指索引文件系统中总的文档数量,但细分起来有如下三类:
1、 缓存中的文档数量
2、已经写入段中的文档数量
3、已经删除的文档数量
在IndexWriter中对此有非常清楚的方法及描述与之对应,如下:
不包含索引中删除文档的总的文档数量:
public synchronized int maxDoc() {
//count记录缓存中的文档总数
int count;
if (docWriter != null)
count = docWriter.getNumDocsInRAM();
else
count = 0;
//再加入以下在文档中存在的文档总数
for (int i = 0; i < segmentInfos.size(); i++)
count += segmentInfos.info(i).docCount;
return count;
}
包含索引中删除文档的总的文档数量:
public synchronized int numDocs() throws IOException {
//count记录缓存中的文档总数
int count;
if (docWriter != null)
count = docWriter.getNumDocsInRAM();
else
count = 0;
// info.getDelCount()为删除的文档总数
for (int i = 0; i < segmentInfos.size(); i++) {
final SegmentInfo info = segmentInfos.info(i);
count += info.docCount - info.getDelCount();
}
return count;
}
在段的对象生成前,文档数量是记在缓存中的,只有当段对象(SegmentInfo)生成了,且进行了刷新(flush)才会将缓存中的文档数量赋给段对象的属性docCount,这样的一个过程如下所示:
1、 执行创建索引时的语句writer.addDocument(document);
2、进入到IndexWriter.java中的方法
public void addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException,在这个方法中,通过执行方法:
doFlush = docWriter.addDocument(doc, analyzer);
进入到DocumentsWriter.java中
3、进入到
boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm)
throws CorruptIndexException, IOException,在方法:
final DocumentsWriterThreadState state = getThreadState(doc, delTerm);
中,通过调用
numDocsInRAM++;
来记录缓存中文档的数量,每加入一次文档,也就是writer.addDocument(document);,那么numDocsInRAM就加1,此时段对象还并没生成。
4、生成段对象并将缓存中的文档数量赋给段对象的属性docCount
这步同样也是在
public void addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException方法中调用的,调用的是flush(true, false, false);最后是在IndexWriter中的方法
private synchronized final boolean doFlushInternal(boolean flushDocStores, boolean flushDeletes) throws CorruptIndexException, IOException
里完成的,具体代码为:
4.1、flushedDocCount = docWriter.flush(flushDocStores);返回缓存中的文档数量
4.2、 newSegment = new SegmentInfo(segment,flushedDocCount,directory, false, true,docStoreOffset, docStoreSegment,docStoreIsCompoundFile, docWriter.hasProx());
第二个参数就是文档数量,赋值代码为:
this.docCount = docCount;
执行完后,缓存中的文档数量清为0,至此文档总数已被完全计入到了段对象中了。
如无转载说明,则均为本站原创文章,转载请注明:来源:子猴博客
