FileDocCategorySizeDatePackage
IndexWriter.javaAPI DocApache Lucene 2.2.079249Sat Jun 16 22:20:36 BST 2007org.apache.lucene.index

IndexWriter

public class IndexWriter extends Object
An IndexWriter creates and maintains an index.

The create argument to the constructor determines whether a new index is created, or whether an existing index is opened. Note that you can open an index with create=true even while readers are using the index. The old readers will continue to search the "point in time" snapshot they had opened, and won't see the newly created index until they re-open. There are also constructors with no create argument which will create a new index if there is not already an index at the provided path and otherwise open the existing index.

In either case, documents are added with addDocument and removed with deleteDocuments. A document can be updated with updateDocument (which just deletes and then adds the entire document). When finished adding, deleting and updating documents, close should be called.

These changes are buffered in memory and periodically flushed to the {@link Directory} (during the above method calls). A flush is triggered when there are enough buffered deletes (see {@link #setMaxBufferedDeleteTerms}) or enough added documents (see {@link #setMaxBufferedDocs}) since the last flush, whichever is sooner. You can also force a flush by calling {@link #flush}. When a flush occurs, both pending deletes and added documents are flushed to the index. A flush may also trigger one or more segment merges.

The optional autoCommit argument to the constructors controls visibility of the changes to {@link IndexReader} instances reading the same index. When this is false, changes are not visible until {@link #close()} is called. Note that changes will still be flushed to the {@link org.apache.lucene.store.Directory} as new files, but are not committed (no new segments_N file is written referencing the new files) until {@link #close} is called. If something goes terribly wrong (for example the JVM crashes) before {@link #close()}, then the index will reflect none of the changes made (it will remain in its starting state). You can also call {@link #abort()}, which closes the writer without committing any changes, and removes any index files that had been flushed but are now unreferenced. This mode is useful for preventing readers from refreshing at a bad time (for example after you've done all your deletes but before you've done your adds). It can also be used to implement simple single-writer transactional semantics ("all or none").

When autoCommit is true then every flush is also a commit ({@link IndexReader} instances will see each flush as changes to the index). This is the default, to match the behavior before 2.2. When running in this mode, be careful not to refresh your readers while optimize or segment merges are taking place as this can tie up substantial disk space.

Regardless of autoCommit, an {@link IndexReader} or {@link org.apache.lucene.search.IndexSearcher} will only see the index as of the "point in time" that it was opened. Any changes committed to the index after the reader was opened are not visible until the reader is re-opened.

If an index will not have more documents added for a while and optimal search performance is desired, then the optimize method should be called before the index is closed.

Opening an IndexWriter creates a lock file for the directory in use. Trying to open another IndexWriter on the same directory will lead to a {@link LockObtainFailedException}. The {@link LockObtainFailedException} is also thrown if an IndexReader on the same directory is used to delete documents from the index.

Expert: IndexWriter allows an optional {@link IndexDeletionPolicy} implementation to be specified. You can use this to control when prior commits are deleted from the index. The default policy is {@link KeepOnlyLastCommitDeletionPolicy} which removes all prior commits as soon as a new commit is done (this matches behavior before 2.2). Creating your own policy can allow you to explicitly keep previous "point in time" commits alive in the index for some time, to allow readers to refresh to the new commit without having the old commit deleted out from under them. This is necessary on filesystems like NFS that do not support "delete on last close" semantics, which Lucene's "point in time" search normally relies on.

Fields Summary
public static long
WRITE_LOCK_TIMEOUT
Default value for the write lock timeout (1,000).
private long
writeLockTimeout
public static final String
WRITE_LOCK_NAME
Name of the write lock in the index.
public static final int
DEFAULT_MERGE_FACTOR
Default value is 10. Change using {@link #setMergeFactor(int)}.
public static final int
DEFAULT_MAX_BUFFERED_DOCS
Default value is 10. Change using {@link #setMaxBufferedDocs(int)}.
public static final int
DEFAULT_MAX_BUFFERED_DELETE_TERMS
Default value is 1000. Change using {@link #setMaxBufferedDeleteTerms(int)}.
public static final int
DEFAULT_MAX_MERGE_DOCS
Default value is {@link Integer#MAX_VALUE}. Change using {@link #setMaxMergeDocs(int)}.
public static final int
DEFAULT_MAX_FIELD_LENGTH
Default value is 10,000. Change using {@link #setMaxFieldLength(int)}.
public static final int
DEFAULT_TERM_INDEX_INTERVAL
Default value is 128. Change using {@link #setTermIndexInterval(int)}.
private static final int
MERGE_READ_BUFFER_SIZE
private Directory
directory
private Analyzer
analyzer
private Similarity
similarity
private boolean
commitPending
private SegmentInfos
rollbackSegmentInfos
private SegmentInfos
localRollbackSegmentInfos
private boolean
localAutoCommit
private boolean
autoCommit
SegmentInfos
segmentInfos
SegmentInfos
ramSegmentInfos
private final RAMDirectory
ramDirectory
private IndexFileDeleter
deleter
private Lock
writeLock
private int
termIndexInterval
private int
maxBufferedDeleteTerms
private HashMap
bufferedDeleteTerms
private int
numBufferedDeleteTerms
private boolean
useCompoundFile
Use compound file setting. Defaults to true, minimizing the number of files used. Setting this to false may improve indexing performance, but may also cause file handle problems.
private boolean
closeDir
private boolean
closed
private int
maxFieldLength
The maximum number of terms that will be indexed for a single field in a document. This limits the amount of memory required for indexing, so that collections with very large files will not crash the indexing process by running out of memory.

Note that this effectively truncates large documents, excluding from the index terms that occur further in the document. If you know your source documents are large, be sure to set this value high enough to accomodate the expected size. If you set it to Integer.MAX_VALUE, then the only limit is your memory, but you should anticipate an OutOfMemoryError.

By default, no more than 10,000 terms will be indexed for a field.

private int
mergeFactor
Determines how often segment indices are merged by addDocument(). With smaller values, less RAM is used while indexing, and searches on unoptimized indices are faster, but indexing speed is slower. With larger values, more RAM is used during indexing, and while searches on unoptimized indices are slower, indexing is faster. Thus larger values (> 10) are best for batch index creation, and smaller values (< 10) for indices that are interactively maintained.

This must never be less than 2. The default value is {@link #DEFAULT_MERGE_FACTOR}.

private int
minMergeDocs
Determines the minimal number of documents required before the buffered in-memory documents are merging and a new Segment is created. Since Documents are merged in a {@link org.apache.lucene.store.RAMDirectory}, large value gives faster indexing. At the same time, mergeFactor limits the number of files open in a FSDirectory.

The default value is {@link #DEFAULT_MAX_BUFFERED_DOCS}.

private int
maxMergeDocs
Determines the largest number of documents ever merged by addDocument(). Small values (e.g., less than 10,000) are best for interactive indexing, as this limits the length of pauses while indexing to a few seconds. Larger values are best for batched indexing and speedier searches.

The default value is {@link #DEFAULT_MAX_MERGE_DOCS}.

private PrintStream
infoStream
If non-null, information about merges will be printed to this.
private static PrintStream
defaultInfoStream
Constructors Summary
public IndexWriter(Directory d, Analyzer a, boolean create)
Constructs an IndexWriter for the index in d. Text will be analyzed with a. If create is true, then a new, empty index will be created in d, replacing the index already there, if any.

param
d the index directory
param
a the analyzer to use
param
create true to create the index or overwrite the existing one; false to append to the existing index
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to, or if it does not exist and create is false or if there is any other low-level IO error

    init(d, a, create, false, null, true);
  
public IndexWriter(String path, Analyzer a)
Constructs an IndexWriter for the index in path, first creating it if it does not already exist. Text will be analyzed with a.

param
path the path to the index directory
param
a the analyzer to use
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to or if there is any other low-level IO error

    init(FSDirectory.getDirectory(path), a, true, null, true);
  
public IndexWriter(File path, Analyzer a)
Constructs an IndexWriter for the index in path, first creating it if it does not already exist. Text will be analyzed with a.

param
path the path to the index directory
param
a the analyzer to use
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to or if there is any other low-level IO error

    init(FSDirectory.getDirectory(path), a, true, null, true);
  
public IndexWriter(Directory d, Analyzer a)
Constructs an IndexWriter for the index in d, first creating it if it does not already exist. Text will be analyzed with a.

param
d the index directory
param
a the analyzer to use
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to or if there is any other low-level IO error

    init(d, a, false, null, true);
  
public IndexWriter(Directory d, boolean autoCommit, Analyzer a)
Constructs an IndexWriter for the index in d, first creating it if it does not already exist. Text will be analyzed with a.

param
d the index directory
param
autoCommit see above
param
a the analyzer to use
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to or if there is any other low-level IO error

    init(d, a, false, null, autoCommit);
  
public IndexWriter(Directory d, boolean autoCommit, Analyzer a, boolean create)
Constructs an IndexWriter for the index in d. Text will be analyzed with a. If create is true, then a new, empty index will be created in d, replacing the index already there, if any.

param
d the index directory
param
autoCommit see above
param
a the analyzer to use
param
create true to create the index or overwrite the existing one; false to append to the existing index
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to, or if it does not exist and create is false or if there is any other low-level IO error

    init(d, a, create, false, null, autoCommit);
  
public IndexWriter(Directory d, boolean autoCommit, Analyzer a, IndexDeletionPolicy deletionPolicy)
Expert: constructs an IndexWriter with a custom {@link IndexDeletionPolicy}, for the index in d, first creating it if it does not already exist. Text will be analyzed with a.

param
d the index directory
param
autoCommit see above
param
a the analyzer to use
param
deletionPolicy see above
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to or if there is any other low-level IO error

    init(d, a, false, deletionPolicy, autoCommit);
  
public IndexWriter(Directory d, boolean autoCommit, Analyzer a, boolean create, IndexDeletionPolicy deletionPolicy)
Expert: constructs an IndexWriter with a custom {@link IndexDeletionPolicy}, for the index in d. Text will be analyzed with a. If create is true, then a new, empty index will be created in d, replacing the index already there, if any.

param
d the index directory
param
autoCommit see above
param
a the analyzer to use
param
create true to create the index or overwrite the existing one; false to append to the existing index
param
deletionPolicy see above
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to, or if it does not exist and create is false or if there is any other low-level IO error

    init(d, a, create, false, deletionPolicy, autoCommit);
  
public IndexWriter(String path, Analyzer a, boolean create)
Constructs an IndexWriter for the index in path. Text will be analyzed with a. If create is true, then a new, empty index will be created in path, replacing the index already there, if any.

param
path the path to the index directory
param
a the analyzer to use
param
create true to create the index or overwrite the existing one; false to append to the existing index
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to, or if it does not exist and create is false or if there is any other low-level IO error

    init(FSDirectory.getDirectory(path), a, create, true, null, true);
  
public IndexWriter(File path, Analyzer a, boolean create)
Constructs an IndexWriter for the index in path. Text will be analyzed with a. If create is true, then a new, empty index will be created in path, replacing the index already there, if any.

param
path the path to the index directory
param
a the analyzer to use
param
create true to create the index or overwrite the existing one; false to append to the existing index
throws
CorruptIndexException if the index is corrupt
throws
LockObtainFailedException if another writer has this index open (write.lock could not be obtained)
throws
IOException if the directory cannot be read/written to, or if it does not exist and create is false or if there is any other low-level IO error

    init(FSDirectory.getDirectory(path), a, create, true, null, true);
  
Methods Summary
public synchronized voidabort()
Close the IndexWriter without committing any of the changes that have occurred since it was opened. This removes any temporary files that had been created, after which the state of the index will be the same as it was when this writer was first opened. This can only be called when this IndexWriter was opened with autoCommit=false.

throws
IllegalStateException if this is called when the writer was opened with autoCommit=true.
throws
IOException if there is a low-level IO error

    ensureOpen();
    if (!autoCommit) {

      // Keep the same segmentInfos instance but replace all
      // of its SegmentInfo instances.  This is so the next
      // attempt to commit using this instance of IndexWriter
      // will always write to a new generation ("write once").
      segmentInfos.clear();
      segmentInfos.addAll(rollbackSegmentInfos);

      // Ask deleter to locate unreferenced files & remove
      // them:
      deleter.checkpoint(segmentInfos, false);
      deleter.refresh();

      ramSegmentInfos = new SegmentInfos();
      bufferedDeleteTerms.clear();
      numBufferedDeleteTerms = 0;

      commitPending = false;
      close();

    } else {
      throw new IllegalStateException("abort() can only be called when IndexWriter was opened with autoCommit=false");
    }
  
public voidaddDocument(org.apache.lucene.document.Document doc)
Adds a document to this index. If the document contains more than {@link #setMaxFieldLength(int)} terms for a given field, the remainder are discarded.

Note that if an Exception is hit (for example disk full) then the index will be consistent, but this document may not have been added. Furthermore, it's possible the index will have one segment in non-compound format even when using compound files (when a merge has partially succeeded).

This method periodically flushes pending documents to the Directory (every {@link #setMaxBufferedDocs}), and also periodically merges segments in the index (every {@link #setMergeFactor} flushes). When this occurs, the method will take more time to run (possibly a long time if the index is large), and will require free temporary space in the Directory to do the merging.

The amount of free space required when a merge is triggered is up to 1X the size of all segments being merged, when no readers/searchers are open against the index, and up to 2X the size of all segments being merged when readers/searchers are open against the index (see {@link #optimize()} for details). Most merges are small (merging the smallest segments together), but whenever a full merge occurs (all segments in the index, which is the worst case for temporary space usage) then the maximum free disk space required is the same as {@link #optimize}.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error


                                                                                                                                                                                                                                                          
         
    addDocument(doc, analyzer);
  
public voidaddDocument(org.apache.lucene.document.Document doc, org.apache.lucene.analysis.Analyzer analyzer)
Adds a document to this index, using the provided analyzer instead of the value of {@link #getAnalyzer()}. If the document contains more than {@link #setMaxFieldLength(int)} terms for a given field, the remainder are discarded.

See {@link #addDocument(Document)} for details on index and IndexWriter state after an Exception, and flushing/merging temporary free space requirements.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    ensureOpen();
    SegmentInfo newSegmentInfo = buildSingleDocSegment(doc, analyzer);
    synchronized (this) {
      ramSegmentInfos.addElement(newSegmentInfo);
      maybeFlushRamSegments();
    }
  
public synchronized voidaddIndexes(org.apache.lucene.store.Directory[] dirs)
Merges all segments from an array of indexes into this index.

This may be used to parallelize batch indexing. A large document collection can be broken into sub-collections. Each sub-collection can be indexed in parallel, on a different thread, process or machine. The complete index can then be created by merging sub-collection indexes with this method.

After this completes, the index is optimized.

This method is transactional in how Exceptions are handled: it does not commit a new segments_N file until all indexes are added. This means if an Exception occurs (for example disk full), then either no indexes will have been added or they all will have been.

If an Exception is hit, it's still possible that all indexes were successfully added. This happens when the Exception is hit when trying to build a CFS file. In this case, one segment in the index will be in non-CFS format, even when using compound file format.

Also note that on an Exception, the index may still have been partially or fully optimized even though none of the input indexes were added.

Note that this requires temporary free space in the Directory up to 2X the sum of all input indexes (including the starting index). If readers/searchers are open against the starting index, then temporary free space required will be higher by the size of the starting index (see {@link #optimize()} for details).

Once this completes, the final size of the index will be less than the sum of all input index sizes (including the starting index). It could be quite a bit smaller (if there were many pending deletes) or just slightly smaller.

See LUCENE-702 for details.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error


    ensureOpen();
    optimize();					  // start with zero or 1 seg

    int start = segmentInfos.size();

    boolean success = false;

    startTransaction();

    try {
      for (int i = 0; i < dirs.length; i++) {
        SegmentInfos sis = new SegmentInfos();	  // read infos from dir
        sis.read(dirs[i]);
        for (int j = 0; j < sis.size(); j++) {
          segmentInfos.addElement(sis.info(j));	  // add each info
        }
      }

      // merge newly added segments in log(n) passes
      while (segmentInfos.size() > start+mergeFactor) {
        for (int base = start; base < segmentInfos.size(); base++) {
          int end = Math.min(segmentInfos.size(), base+mergeFactor);
          if (end-base > 1) {
            mergeSegments(segmentInfos, base, end);
          }
        }
      }
      success = true;
    } finally {
      if (success) {
        commitTransaction();
      } else {
        rollbackTransaction();
      }
    }

    optimize();					  // final cleanup
  
public synchronized voidaddIndexes(org.apache.lucene.index.IndexReader[] readers)
Merges the provided indexes into this index.

After this completes, the index is optimized.

The provided IndexReaders are not closed.

See {@link #addIndexes(Directory[])} for details on transactional semantics, temporary free space required in the Directory, and non-CFS segments on an Exception.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error


    ensureOpen();
    optimize();					  // start with zero or 1 seg

    final String mergedName = newSegmentName();
    SegmentMerger merger = new SegmentMerger(this, mergedName);

    SegmentInfo info;

    IndexReader sReader = null;
    try {
      if (segmentInfos.size() == 1){ // add existing index, if any
        sReader = SegmentReader.get(segmentInfos.info(0));
        merger.add(sReader);
      }

      for (int i = 0; i < readers.length; i++)      // add new indexes
        merger.add(readers[i]);

      boolean success = false;

      startTransaction();

      try {
        int docCount = merger.merge();                // merge 'em

        if(sReader != null) {
          sReader.close();
          sReader = null;
        }

        segmentInfos.setSize(0);                      // pop old infos & add new
        info = new SegmentInfo(mergedName, docCount, directory, false, true);
        segmentInfos.addElement(info);

        success = true;

      } finally {
        if (!success) {
          rollbackTransaction();
        } else {
          commitTransaction();
        }
      }
    } finally {
      if (sReader != null) {
        sReader.close();
      }
    }
    
    if (useCompoundFile) {

      boolean success = false;

      startTransaction();

      try {
        merger.createCompoundFile(mergedName + ".cfs");
        info.setUseCompoundFile(true);
      } finally {
        if (!success) {
          rollbackTransaction();
        } else {
          commitTransaction();
        }
      }
    }
  
public synchronized voidaddIndexesNoOptimize(org.apache.lucene.store.Directory[] dirs)
Merges all segments from an array of indexes into this index.

This is similar to addIndexes(Directory[]). However, no optimize() is called either at the beginning or at the end. Instead, merges are carried out as necessary.

This requires this index not be among those to be added, and the upper bound* of those segment doc counts not exceed maxMergeDocs.

See {@link #addIndexes(Directory[])} for details on transactional semantics, temporary free space required in the Directory, and non-CFS segments on an Exception.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    // Adding indexes can be viewed as adding a sequence of segments S to
    // a sequence of segments T. Segments in T follow the invariants but
    // segments in S may not since they could come from multiple indexes.
    // Here is the merge algorithm for addIndexesNoOptimize():
    //
    // 1 Flush ram segments.
    // 2 Consider a combined sequence with segments from T followed
    //   by segments from S (same as current addIndexes(Directory[])).
    // 3 Assume the highest level for segments in S is h. Call
    //   maybeMergeSegments(), but instead of starting w/ lowerBound = -1
    //   and upperBound = maxBufferedDocs, start w/ lowerBound = -1 and
    //   upperBound = upperBound of level h. After this, the invariants
    //   are guaranteed except for the last < M segments whose levels <= h.
    // 4 If the invariants hold for the last < M segments whose levels <= h,
    //   if some of those < M segments are from S (not merged in step 3),
    //   properly copy them over*, otherwise done.
    //   Otherwise, simply merge those segments. If the merge results in
    //   a segment of level <= h, done. Otherwise, it's of level h+1 and call
    //   maybeMergeSegments() starting w/ upperBound = upperBound of level h+1.
    //
    // * Ideally, we want to simply copy a segment. However, directory does
    // not support copy yet. In addition, source may use compound file or not
    // and target may use compound file or not. So we use mergeSegments() to
    // copy a segment, which may cause doc count to change because deleted
    // docs are garbage collected.

    // 1 flush ram segments

    ensureOpen();
    flushRamSegments();

    // 2 copy segment infos and find the highest level from dirs
    int startUpperBound = minMergeDocs;

    boolean success = false;

    startTransaction();

    try {

      for (int i = 0; i < dirs.length; i++) {
        if (directory == dirs[i]) {
          // cannot add this index: segments may be deleted in merge before added
          throw new IllegalArgumentException("Cannot add this index to itself");
        }

        SegmentInfos sis = new SegmentInfos(); // read infos from dir
        sis.read(dirs[i]);
        for (int j = 0; j < sis.size(); j++) {
          SegmentInfo info = sis.info(j);
          segmentInfos.addElement(info); // add each info
          
          while (startUpperBound < info.docCount) {
            startUpperBound *= mergeFactor; // find the highest level from dirs
            if (startUpperBound > maxMergeDocs) {
              // upper bound cannot exceed maxMergeDocs
              throw new IllegalArgumentException("Upper bound cannot exceed maxMergeDocs");
            }
          }
        }
      }

      // 3 maybe merge segments starting from the highest level from dirs
      maybeMergeSegments(startUpperBound);

      // get the tail segments whose levels <= h
      int segmentCount = segmentInfos.size();
      int numTailSegments = 0;
      while (numTailSegments < segmentCount
             && startUpperBound >= segmentInfos.info(segmentCount - 1 - numTailSegments).docCount) {
        numTailSegments++;
      }
      if (numTailSegments == 0) {
        success = true;
        return;
      }

      // 4 make sure invariants hold for the tail segments whose levels <= h
      if (checkNonDecreasingLevels(segmentCount - numTailSegments)) {
        // identify the segments from S to be copied (not merged in 3)
        int numSegmentsToCopy = 0;
        while (numSegmentsToCopy < segmentCount
               && directory != segmentInfos.info(segmentCount - 1 - numSegmentsToCopy).dir) {
          numSegmentsToCopy++;
        }
        if (numSegmentsToCopy == 0) {
          success = true;
          return;
        }

        // copy those segments from S
        for (int i = segmentCount - numSegmentsToCopy; i < segmentCount; i++) {
          mergeSegments(segmentInfos, i, i + 1);
        }
        if (checkNonDecreasingLevels(segmentCount - numSegmentsToCopy)) {
          success = true;
          return;
        }
      }

      // invariants do not hold, simply merge those segments
      mergeSegments(segmentInfos, segmentCount - numTailSegments, segmentCount);

      // maybe merge segments again if necessary
      if (segmentInfos.info(segmentInfos.size() - 1).docCount > startUpperBound) {
        maybeMergeSegments(startUpperBound * mergeFactor);
      }

      success = true;
    } finally {
      if (success) {
        commitTransaction();
      } else {
        rollbackTransaction();
      }
    }
  
private final voidapplyDeletes(java.util.HashMap deleteTerms, org.apache.lucene.index.IndexReader reader)

    Iterator iter = deleteTerms.entrySet().iterator();
    while (iter.hasNext()) {
      Entry entry = (Entry) iter.next();
      reader.deleteDocuments((Term) entry.getKey());
    }
  
private final voidapplyDeletesSelectively(java.util.HashMap deleteTerms, org.apache.lucene.index.IndexReader reader)

    Iterator iter = deleteTerms.entrySet().iterator();
    while (iter.hasNext()) {
      Entry entry = (Entry) iter.next();
      Term term = (Term) entry.getKey();

      TermDocs docs = reader.termDocs(term);
      if (docs != null) {
        int num = ((Num) entry.getValue()).getNum();
        try {
          while (docs.next()) {
            int doc = docs.doc();
            if (doc >= num) {
              break;
            }
            reader.deleteDocument(doc);
          }
        } finally {
          docs.close();
        }
      }
    }
  
private voidbufferDeleteTerm(org.apache.lucene.index.Term term)

    Num num = (Num) bufferedDeleteTerms.get(term);
    if (num == null) {
      bufferedDeleteTerms.put(term, new Num(ramSegmentInfos.size()));
    } else {
      num.setNum(ramSegmentInfos.size());
    }
    numBufferedDeleteTerms++;
  
org.apache.lucene.index.SegmentInfobuildSingleDocSegment(org.apache.lucene.document.Document doc, org.apache.lucene.analysis.Analyzer analyzer)

    DocumentWriter dw = new DocumentWriter(ramDirectory, analyzer, this);
    dw.setInfoStream(infoStream);
    String segmentName = newRamSegmentName();
    dw.addDocument(segmentName, doc);
    SegmentInfo si = new SegmentInfo(segmentName, 1, ramDirectory, false, false);
    si.setNumFields(dw.getNumFields());
    return si;
  
private final booleancheckNonDecreasingLevels(int start)

    int lowerBound = -1;
    int upperBound = minMergeDocs;

    for (int i = segmentInfos.size() - 1; i >= start; i--) {
      int docCount = segmentInfos.info(i).docCount;
      if (docCount <= lowerBound) {
        return false;
      }

      while (docCount > upperBound) {
        lowerBound = upperBound;
        upperBound *= mergeFactor;
      }
    }
    return true;
  
private voidcheckpoint()

    if (autoCommit) {
      segmentInfos.write(directory);
    } else {
      commitPending = true;
    }
  
public synchronized voidclose()
Flushes all changes to an index and closes all associated files.

If an Exception is hit during close, eg due to disk full or some other reason, then both the on-disk index and the internal state of the IndexWriter instance will be consistent. However, the close will not be complete even though part of it (flushing buffered documents) may have succeeded, so the write lock will still be held.

If you can correct the underlying cause (eg free up some disk space) then you can call close() again. Failing that, if you want to force the write lock to be released (dangerous, because you may then lose buffered docs in the IndexWriter instance) then you can do something like this:

try {
writer.close();
} finally {
if (IndexReader.isLocked(directory)) {
IndexReader.unlock(directory);
}
}
after which, you must be certain not to use the writer instance anymore.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    if (!closed) {
      flushRamSegments();

      if (commitPending) {
        segmentInfos.write(directory);         // now commit changes
        deleter.checkpoint(segmentInfos, true);
        commitPending = false;
        rollbackSegmentInfos = null;
      }

      ramDirectory.close();
      if (writeLock != null) {
        writeLock.release();                          // release write lock
        writeLock = null;
      }
      closed = true;

      if(closeDir)
        directory.close();
    }
  
private voidcommitTransaction()


    // First restore autoCommit in case we hit an exception below:
    autoCommit = localAutoCommit;

    boolean success = false;
    try {
      checkpoint();
      success = true;
    } finally {
      if (!success) {
        rollbackTransaction();
      }
    }

    if (!autoCommit)
      // Remove the incRef we did in startTransaction.
      deleter.decRef(localRollbackSegmentInfos);

    localRollbackSegmentInfos = null;

    // Give deleter a chance to remove files now:
    deleter.checkpoint(segmentInfos, autoCommit);
  
public synchronized voiddeleteDocuments(org.apache.lucene.index.Term term)
Deletes the document(s) containing term.

param
term the term to identify the documents to be deleted
throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    ensureOpen();
    bufferDeleteTerm(term);
    maybeFlushRamSegments();
  
public synchronized voiddeleteDocuments(org.apache.lucene.index.Term[] terms)
Deletes the document(s) containing any of the terms. All deletes are flushed at the same time.

param
terms array of terms to identify the documents to be deleted
throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    ensureOpen();
    for (int i = 0; i < terms.length; i++) {
      bufferDeleteTerm(terms[i]);
    }
    maybeFlushRamSegments();
  
voiddoAfterFlush()

  
public synchronized intdocCount()
Returns the number of documents currently in this index.

    ensureOpen();
    int count = ramSegmentInfos.size();
    for (int i = 0; i < segmentInfos.size(); i++) {
      SegmentInfo si = segmentInfos.info(i);
      count += si.docCount;
    }
    return count;
  
protected final voidensureOpen()
Used internally to throw an {@link AlreadyClosedException} if this IndexWriter has been closed.

throws
AlreadyClosedException if this IndexWriter is


                        
        
    if (closed) {
      throw new AlreadyClosedException("this IndexWriter is closed");
    }
  
protected voidfinalize()
Release the write lock, if needed.

    try {
      if (writeLock != null) {
        writeLock.release();                        // release write lock
        writeLock = null;
      }
    } finally {
      super.finalize();
    }
  
public final synchronized voidflush()
Flush all in-memory buffered updates (adds and deletes) to the Directory.

Note: if autoCommit=false, flushed data would still not be visible to readers, until {@link #close} is called.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    ensureOpen();
    flushRamSegments();
  
private final synchronized voidflushRamSegments()
Expert: Flushes all RAM-resident segments (buffered documents), then may merge segments.

    flushRamSegments(true);
  
protected final synchronized voidflushRamSegments(boolean triggerMerge)
Expert: Flushes all RAM-resident segments (buffered documents), then may merge segments if triggerMerge==true.

    if (ramSegmentInfos.size() > 0 || bufferedDeleteTerms.size() > 0) {
      mergeSegments(ramSegmentInfos, 0, ramSegmentInfos.size());
      if (triggerMerge) maybeMergeSegments(minMergeDocs);
    }
  
public org.apache.lucene.analysis.AnalyzergetAnalyzer()
Returns the analyzer used by this index.

    ensureOpen();
    return analyzer;
  
final synchronized intgetBufferedDeleteTermsSize()

    return bufferedDeleteTerms.size();
  
public static java.io.PrintStreamgetDefaultInfoStream()
Returns the current default infoStream for newly instantiated IndexWriters.

see
#setDefaultInfoStream

    return IndexWriter.defaultInfoStream;
  
public static longgetDefaultWriteLockTimeout()
Returns default write lock timeout for newly instantiated IndexWriters.

see
#setDefaultWriteLockTimeout

    return IndexWriter.WRITE_LOCK_TIMEOUT;
  
public org.apache.lucene.store.DirectorygetDirectory()
Returns the Directory used by this index.

    ensureOpen();
    return directory;
  
final synchronized intgetDocCount(int i)

    if (i >= 0 && i < segmentInfos.size()) {
      return segmentInfos.info(i).docCount;
    } else {
      return -1;
    }
  
public java.io.PrintStreamgetInfoStream()
Returns the current infoStream in use by this writer.

see
#setInfoStream

    ensureOpen();
    return infoStream;
  
public intgetMaxBufferedDeleteTerms()
Returns the number of buffered deleted terms that will trigger a flush.

see
#setMaxBufferedDeleteTerms

    ensureOpen();
    return maxBufferedDeleteTerms;
  
public intgetMaxBufferedDocs()
Returns the number of buffered added documents that will trigger a flush.

see
#setMaxBufferedDocs

    ensureOpen();
    return minMergeDocs;
  
public intgetMaxFieldLength()
Returns the maximum number of terms that will be indexed for a single field in a document.

see
#setMaxFieldLength

    ensureOpen();
    return maxFieldLength;
  
public intgetMaxMergeDocs()
Returns the largest number of documents allowed in a single segment.

see
#setMaxMergeDocs

    ensureOpen();
    return maxMergeDocs;
  
public intgetMergeFactor()
Returns the number of segments that are merged at once and also controls the total number of segments allowed to accumulate in the index.

see
#setMergeFactor

    ensureOpen();
    return mergeFactor;
  
final synchronized intgetNumBufferedDeleteTerms()

    return numBufferedDeleteTerms;
  
final synchronized intgetRamSegmentCount()

    return ramSegmentInfos.size();
  
final synchronized intgetSegmentCount()

    return segmentInfos.size();
  
public org.apache.lucene.search.SimilaritygetSimilarity()
Expert: Return the Similarity implementation used by this IndexWriter.

This defaults to the current value of {@link Similarity#getDefault()}.

    ensureOpen();
    return this.similarity;
  
public intgetTermIndexInterval()
Expert: Return the interval between indexed terms.

see
#setTermIndexInterval(int)

    ensureOpen();
    return termIndexInterval;
  
public booleangetUseCompoundFile()
Get the current setting of whether to use the compound file format. Note that this just returns the value you set with setUseCompoundFile(boolean) or the default. You cannot use this to query the status of an existing index.

see
#setUseCompoundFile(boolean)

    ensureOpen();
    return useCompoundFile;
  
public longgetWriteLockTimeout()
Returns allowed timeout when acquiring the write lock.

see
#setWriteLockTimeout

    ensureOpen();
    return writeLockTimeout;
  
private voidinit(org.apache.lucene.store.Directory d, org.apache.lucene.analysis.Analyzer a, boolean closeDir, org.apache.lucene.index.IndexDeletionPolicy deletionPolicy, boolean autoCommit)

    if (IndexReader.indexExists(d)) {
      init(d, a, false, closeDir, deletionPolicy, autoCommit);
    } else {
      init(d, a, true, closeDir, deletionPolicy, autoCommit);
    }
  
private voidinit(org.apache.lucene.store.Directory d, org.apache.lucene.analysis.Analyzer a, boolean create, boolean closeDir, org.apache.lucene.index.IndexDeletionPolicy deletionPolicy, boolean autoCommit)

    this.closeDir = closeDir;
    directory = d;
    analyzer = a;
    this.infoStream = defaultInfoStream;

    if (create) {
      // Clear the write lock in case it's leftover:
      directory.clearLock(IndexWriter.WRITE_LOCK_NAME);
    }

    Lock writeLock = directory.makeLock(IndexWriter.WRITE_LOCK_NAME);
    if (!writeLock.obtain(writeLockTimeout)) // obtain write lock
      throw new LockObtainFailedException("Index locked for write: " + writeLock);
    this.writeLock = writeLock;                   // save it

    try {
      if (create) {
        // Try to read first.  This is to allow create
        // against an index that's currently open for
        // searching.  In this case we write the next
        // segments_N file with no segments:
        try {
          segmentInfos.read(directory);
          segmentInfos.clear();
        } catch (IOException e) {
          // Likely this means it's a fresh directory
        }
        segmentInfos.write(directory);
      } else {
        segmentInfos.read(directory);
      }

      this.autoCommit = autoCommit;
      if (!autoCommit) {
        rollbackSegmentInfos = (SegmentInfos) segmentInfos.clone();
      }

      // Default deleter (for backwards compatibility) is
      // KeepOnlyLastCommitDeleter:
      deleter = new IndexFileDeleter(directory,
                                     deletionPolicy == null ? new KeepOnlyLastCommitDeletionPolicy() : deletionPolicy,
                                     segmentInfos, infoStream);

    } catch (IOException e) {
      this.writeLock.release();
      this.writeLock = null;
      throw e;
    }
  
private final voidmaybeApplyDeletes(boolean doMerge)


    if (bufferedDeleteTerms.size() > 0) {
      if (infoStream != null)
        infoStream.println("flush " + numBufferedDeleteTerms + " buffered deleted terms on "
                           + segmentInfos.size() + " segments.");

      if (doMerge) {
        IndexReader reader = null;
        try {
          reader = SegmentReader.get(segmentInfos.info(segmentInfos.size() - 1));

          // Apply delete terms to the segment just flushed from ram
          // apply appropriately so that a delete term is only applied to
          // the documents buffered before it, not those buffered after it.
          applyDeletesSelectively(bufferedDeleteTerms, reader);
        } finally {
          if (reader != null) {
            try {
              reader.doCommit();
            } finally {
              reader.doClose();
            }
          }
        }
      }

      int infosEnd = segmentInfos.size();
      if (doMerge) {
        infosEnd--;
      }

      for (int i = 0; i < infosEnd; i++) {
        IndexReader reader = null;
        try {
          reader = SegmentReader.get(segmentInfos.info(i));

          // Apply delete terms to disk segments
          // except the one just flushed from ram.
          applyDeletes(bufferedDeleteTerms, reader);
        } finally {
          if (reader != null) {
            try {
              reader.doCommit();
            } finally {
              reader.doClose();
            }
          }
        }
      }

      // Clean up bufferedDeleteTerms.
      bufferedDeleteTerms.clear();
      numBufferedDeleteTerms = 0;
    }
  
protected final voidmaybeFlushRamSegments()
Used internally to trigger a flush if the number of buffered added documents or buffered deleted terms are large enough.

    // A flush is triggered if enough new documents are buffered or
    // if enough delete terms are buffered
    if (ramSegmentInfos.size() >= minMergeDocs || numBufferedDeleteTerms >= maxBufferedDeleteTerms) {
      flushRamSegments();
    }
  
private final voidmaybeMergeSegments(int startUpperBound)
Incremental segment merger.

    long lowerBound = -1;
    long upperBound = startUpperBound;

    while (upperBound < maxMergeDocs) {
      int minSegment = segmentInfos.size();
      int maxSegment = -1;

      // find merge-worthy segments
      while (--minSegment >= 0) {
        SegmentInfo si = segmentInfos.info(minSegment);

        if (maxSegment == -1 && si.docCount > lowerBound && si.docCount <= upperBound) {
          // start from the rightmost* segment whose doc count is in bounds
          maxSegment = minSegment;
        } else if (si.docCount > upperBound) {
          // until the segment whose doc count exceeds upperBound
          break;
        }
      }

      minSegment++;
      maxSegment++;
      int numSegments = maxSegment - minSegment;

      if (numSegments < mergeFactor) {
        break;
      } else {
        boolean exceedsUpperLimit = false;

        // number of merge-worthy segments may exceed mergeFactor when
        // mergeFactor and/or maxBufferedDocs change(s)
        while (numSegments >= mergeFactor) {
          // merge the leftmost* mergeFactor segments

          int docCount = mergeSegments(segmentInfos, minSegment, minSegment + mergeFactor);
          numSegments -= mergeFactor;

          if (docCount > upperBound) {
            // continue to merge the rest of the worthy segments on this level
            minSegment++;
            exceedsUpperLimit = true;
          } else {
            // if the merged segment does not exceed upperBound, consider
            // this segment for further merges on this same level
            numSegments++;
          }
        }

        if (!exceedsUpperLimit) {
          // if none of the merged segments exceed upperBound, done
          break;
        }
      }

      lowerBound = upperBound;
      upperBound *= mergeFactor;
    }
  
private final intmergeSegments(org.apache.lucene.index.SegmentInfos sourceSegments, int minSegment, int end)
Merges the named range of segments, replacing them in the stack with a single segment.


    // We may be called solely because there are deletes
    // pending, in which case doMerge is false:
    boolean doMerge = end > 0;
    final String mergedName = newSegmentName();
    SegmentMerger merger = null;

    final List ramSegmentsToDelete = new ArrayList();

    SegmentInfo newSegment = null;

    int mergedDocCount = 0;
    boolean anyDeletes = (bufferedDeleteTerms.size() != 0);

    // This is try/finally to make sure merger's readers are closed:
    try {

      if (doMerge) {
        if (infoStream != null) infoStream.print("merging segments");
        merger = new SegmentMerger(this, mergedName);

        for (int i = minSegment; i < end; i++) {
          SegmentInfo si = sourceSegments.info(i);
          if (infoStream != null)
            infoStream.print(" " + si.name + " (" + si.docCount + " docs)");
          IndexReader reader = SegmentReader.get(si, MERGE_READ_BUFFER_SIZE); // no need to set deleter (yet)
          merger.add(reader);
          if (reader.directory() == this.ramDirectory) {
            ramSegmentsToDelete.add(si);
          }
        }
      }

      SegmentInfos rollback = null;
      boolean success = false;

      // This is try/finally to rollback our internal state
      // if we hit exception when doing the merge:
      try {

        if (doMerge) {
          mergedDocCount = merger.merge();

          if (infoStream != null) {
            infoStream.println(" into "+mergedName+" ("+mergedDocCount+" docs)");
          }

          newSegment = new SegmentInfo(mergedName, mergedDocCount,
                                       directory, false, true);
        }
        
        if (sourceSegments != ramSegmentInfos || anyDeletes) {
          // Now save the SegmentInfo instances that
          // we are replacing:
          rollback = (SegmentInfos) segmentInfos.clone();
        }

        if (doMerge) {
          if (sourceSegments == ramSegmentInfos) {
            segmentInfos.addElement(newSegment);
          } else {
            for (int i = end-1; i > minSegment; i--)     // remove old infos & add new
              sourceSegments.remove(i);

            segmentInfos.set(minSegment, newSegment);
          }
        }

        if (sourceSegments == ramSegmentInfos) {
          maybeApplyDeletes(doMerge);
          doAfterFlush();
        }
        
        checkpoint();

        success = true;

      } finally {

        if (success) {
          // The non-ram-segments case is already committed
          // (above), so all the remains for ram segments case
          // is to clear the ram segments:
          if (sourceSegments == ramSegmentInfos) {
            ramSegmentInfos.removeAllElements();
          }
        } else {

          // Must rollback so our state matches index:
          if (sourceSegments == ramSegmentInfos && !anyDeletes) {
            // Simple case: newSegment may or may not have
            // been added to the end of our segment infos,
            // so just check & remove if so:
            if (newSegment != null && 
                segmentInfos.size() > 0 && 
                segmentInfos.info(segmentInfos.size()-1) == newSegment) {
              segmentInfos.remove(segmentInfos.size()-1);
            }
          } else if (rollback != null) {
            // Rollback the individual SegmentInfo
            // instances, but keep original SegmentInfos
            // instance (so we don't try to write again the
            // same segments_N file -- write once):
            segmentInfos.clear();
            segmentInfos.addAll(rollback);
          }

          // Delete any partially created and now unreferenced files:
          deleter.refresh();
        }
      }
    } finally {
      // close readers before we attempt to delete now-obsolete segments
      if (doMerge) merger.closeReaders();
    }

    // Delete the RAM segments
    deleter.deleteDirect(ramDirectory, ramSegmentsToDelete);

    // Give deleter a chance to remove files now.
    deleter.checkpoint(segmentInfos, autoCommit);

    if (useCompoundFile && doMerge) {

      boolean success = false;

      try {

        merger.createCompoundFile(mergedName + ".cfs");
        newSegment.setUseCompoundFile(true);
        checkpoint();
        success = true;

      } finally {
        if (!success) {  
          // Must rollback:
          newSegment.setUseCompoundFile(false);
          deleter.refresh();
        }
      }
      
      // Give deleter a chance to remove files now.
      deleter.checkpoint(segmentInfos, autoCommit);
    }

    return mergedDocCount;
  
final synchronized java.lang.StringnewRamSegmentName()

    return "_ram_" + Integer.toString(ramSegmentInfos.counter++, Character.MAX_RADIX);
  
final synchronized java.lang.StringnewSegmentName()

    return "_" + Integer.toString(segmentInfos.counter++, Character.MAX_RADIX);
  
public final synchronized intnumRamDocs()
Expert: Return the number of documents whose segments are currently cached in memory. Useful when calling flushRamSegments()

    ensureOpen();
    return ramSegmentInfos.size();
  
public synchronized voidoptimize()
Merges all segments together into a single segment, optimizing an index for search.

It is recommended that this method be called upon completion of indexing. In environments with frequent updates, optimize is best done during low volume times, if at all.

See http://www.gossamer-threads.com/lists/lucene/java-dev/47895 for more discussion.

Note that this requires substantial temporary free space in the Directory (see LUCENE-764 for details):

  • If no readers/searchers are open against the index, then free space required is up to 1X the total size of the starting index. For example, if the starting index is 10 GB, then you must have up to 10 GB of free space before calling optimize.

  • If readers/searchers are using the index, then free space required is up to 2X the size of the starting index. This is because in addition to the 1X used by optimize, the original 1X of the starting index is still consuming space in the Directory as the readers are holding the segments files open. Even on Unix, where it will appear as if the files are gone ("ls" won't list them), they still consume storage due to "delete on last close" semantics.

    Furthermore, if some but not all readers re-open while the optimize is underway, this will cause > 2X temporary space to be consumed as those new readers will then hold open the partially optimized segments at that time. It is best not to re-open readers while optimize is running.

The actual temporary usage could be much less than these figures (it depends on many factors).

Once the optimize completes, the total size of the index will be less than the size of the starting index. It could be quite a bit smaller (if there were many pending deletes) or just slightly smaller.

If an Exception is hit during optimize(), for example due to disk full, the index will not be corrupt and no documents will have been lost. However, it may have been partially optimized (some segments were merged but not all), and it's possible that one of the segments in the index will be in non-compound format even when using compound file format. This will occur when the Exception is hit during conversion of the segment into compound format.

throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error


                                                                                                                                                                                                                                                                                                                                                                                                                         
         
    ensureOpen();
    flushRamSegments();
    while (segmentInfos.size() > 1 ||
           (segmentInfos.size() == 1 &&
            (SegmentReader.hasDeletions(segmentInfos.info(0)) ||
             SegmentReader.hasSeparateNorms(segmentInfos.info(0)) ||
             segmentInfos.info(0).dir != directory ||
             (useCompoundFile &&
              (!SegmentReader.usesCompoundFile(segmentInfos.info(0))))))) {
      int minSegment = segmentInfos.size() - mergeFactor;
      mergeSegments(segmentInfos, minSegment < 0 ? 0 : minSegment, segmentInfos.size());
    }
  
public final longramSizeInBytes()
Expert: Return the total size of all index files currently cached in memory. Useful for size management with flushRamDocs()

    ensureOpen();
    return ramDirectory.sizeInBytes();
  
private voidrollbackTransaction()


    // First restore autoCommit in case we hit an exception below:
    autoCommit = localAutoCommit;

    // Keep the same segmentInfos instance but replace all
    // of its SegmentInfo instances.  This is so the next
    // attempt to commit using this instance of IndexWriter
    // will always write to a new generation ("write once").
    segmentInfos.clear();
    segmentInfos.addAll(localRollbackSegmentInfos);
    localRollbackSegmentInfos = null;

    // Ask deleter to locate unreferenced files we had
    // created & remove them:
    deleter.checkpoint(segmentInfos, false);

    if (!autoCommit)
      // Remove the incRef we did in startTransaction:
      deleter.decRef(segmentInfos);

    deleter.refresh();
  
public static voidsetDefaultInfoStream(java.io.PrintStream infoStream)
If non-null, this will be the default infoStream used by a newly instantiated IndexWriter.

see
#setInfoStream

    IndexWriter.defaultInfoStream = infoStream;
  
public static voidsetDefaultWriteLockTimeout(long writeLockTimeout)
Sets the default (for any instance of IndexWriter) maximum time to wait for a write lock (in milliseconds).

    IndexWriter.WRITE_LOCK_TIMEOUT = writeLockTimeout;
  
public voidsetInfoStream(java.io.PrintStream infoStream)
If non-null, information about merges, deletes and a message when maxFieldLength is reached will be printed to this.

    ensureOpen();
    this.infoStream = infoStream;
    deleter.setInfoStream(infoStream);
  
public voidsetMaxBufferedDeleteTerms(int maxBufferedDeleteTerms)

Determines the minimal number of delete terms required before the buffered in-memory delete terms are applied and flushed. If there are documents buffered in memory at the time, they are merged and a new segment is created.

The default value is {@link #DEFAULT_MAX_BUFFERED_DELETE_TERMS}.

throws
IllegalArgumentException if maxBufferedDeleteTerms is smaller than 1

    ensureOpen();
    if (maxBufferedDeleteTerms < 1)
      throw new IllegalArgumentException("maxBufferedDeleteTerms must at least be 1");
    this.maxBufferedDeleteTerms = maxBufferedDeleteTerms;
  
public voidsetMaxBufferedDocs(int maxBufferedDocs)
Determines the minimal number of documents required before the buffered in-memory documents are merged and a new Segment is created. Since Documents are merged in a {@link org.apache.lucene.store.RAMDirectory}, large value gives faster indexing. At the same time, mergeFactor limits the number of files open in a FSDirectory.

The default value is 10.

throws
IllegalArgumentException if maxBufferedDocs is smaller than 2

    ensureOpen();
    if (maxBufferedDocs < 2)
      throw new IllegalArgumentException("maxBufferedDocs must at least be 2");
    this.minMergeDocs = maxBufferedDocs;
  
public voidsetMaxFieldLength(int maxFieldLength)
The maximum number of terms that will be indexed for a single field in a document. This limits the amount of memory required for indexing, so that collections with very large files will not crash the indexing process by running out of memory.

Note that this effectively truncates large documents, excluding from the index terms that occur further in the document. If you know your source documents are large, be sure to set this value high enough to accomodate the expected size. If you set it to Integer.MAX_VALUE, then the only limit is your memory, but you should anticipate an OutOfMemoryError.

By default, no more than 10,000 terms will be indexed for a field.

    ensureOpen();
    this.maxFieldLength = maxFieldLength;
  
public voidsetMaxMergeDocs(int maxMergeDocs)
Determines the largest number of documents ever merged by addDocument(). Small values (e.g., less than 10,000) are best for interactive indexing, as this limits the length of pauses while indexing to a few seconds. Larger values are best for batched indexing and speedier searches.

The default value is {@link Integer#MAX_VALUE}.

    ensureOpen();
    this.maxMergeDocs = maxMergeDocs;
  
public voidsetMergeFactor(int mergeFactor)
Determines how often segment indices are merged by addDocument(). With smaller values, less RAM is used while indexing, and searches on unoptimized indices are faster, but indexing speed is slower. With larger values, more RAM is used during indexing, and while searches on unoptimized indices are slower, indexing is faster. Thus larger values (> 10) are best for batch index creation, and smaller values (< 10) for indices that are interactively maintained.

This must never be less than 2. The default value is 10.

    ensureOpen();
    if (mergeFactor < 2)
      throw new IllegalArgumentException("mergeFactor cannot be less than 2");
    this.mergeFactor = mergeFactor;
  
public voidsetSimilarity(org.apache.lucene.search.Similarity similarity)
Expert: Set the Similarity implementation used by this IndexWriter.

see
Similarity#setDefault(Similarity)

    ensureOpen();
    this.similarity = similarity;
  
public voidsetTermIndexInterval(int interval)
Expert: Set the interval between indexed terms. Large values cause less memory to be used by IndexReader, but slow random-access to terms. Small values cause more memory to be used by an IndexReader, and speed random-access to terms. This parameter determines the amount of computation required per query term, regardless of the number of documents that contain that term. In particular, it is the maximum number of other terms that must be scanned before a term is located and its frequency and position information may be processed. In a large index with user-entered query terms, query processing time is likely to be dominated not by term lookup but rather by the processing of frequency and positional data. In a small index or when many uncommon query terms are generated (e.g., by wildcard queries) term lookup may become a dominant cost. In particular, numUniqueTerms/interval terms are read into memory by an IndexReader, and, on average, interval/2 terms must be scanned for each random term access.

see
#DEFAULT_TERM_INDEX_INTERVAL

    ensureOpen();
    this.termIndexInterval = interval;
  
public voidsetUseCompoundFile(boolean value)
Setting to turn on usage of a compound file. When on, multiple files for each segment are merged into a single file once the segment creation is finished. This is done regardless of what directory is in use.

    ensureOpen();
    useCompoundFile = value;
  
public voidsetWriteLockTimeout(long writeLockTimeout)
Sets the maximum time to wait for a write lock (in milliseconds) for this instance of IndexWriter. @see

see
#setDefaultWriteLockTimeout to change the default value for all instances of IndexWriter.

    ensureOpen();
    this.writeLockTimeout = writeLockTimeout;
  
private voidstartTransaction()

    localRollbackSegmentInfos = (SegmentInfos) segmentInfos.clone();
    localAutoCommit = autoCommit;
    if (localAutoCommit) {
      flushRamSegments();
      // Turn off auto-commit during our local transaction:
      autoCommit = false;
    } else
      // We must "protect" our files at this point from
      // deletion in case we need to rollback:
      deleter.incRef(segmentInfos, false);
  
public voidupdateDocument(org.apache.lucene.index.Term term, org.apache.lucene.document.Document doc)
Updates a document by first deleting the document(s) containing term and then adding the new document. The delete and then add are atomic as seen by a reader on the same index (flush may happen only after the add).

param
term the term to identify the document(s) to be deleted
param
doc the document to be added
throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    ensureOpen();
    updateDocument(term, doc, getAnalyzer());
  
public voidupdateDocument(org.apache.lucene.index.Term term, org.apache.lucene.document.Document doc, org.apache.lucene.analysis.Analyzer analyzer)
Updates a document by first deleting the document(s) containing term and then adding the new document. The delete and then add are atomic as seen by a reader on the same index (flush may happen only after the add).

param
term the term to identify the document(s) to be deleted
param
doc the document to be added
param
analyzer the analyzer to use when analyzing the document
throws
CorruptIndexException if the index is corrupt
throws
IOException if there is a low-level IO error

    ensureOpen();
    SegmentInfo newSegmentInfo = buildSingleDocSegment(doc, analyzer);
    synchronized (this) {
      bufferDeleteTerm(term);
      ramSegmentInfos.addElement(newSegmentInfo);
      maybeFlushRamSegments();
    }