---
title: "cannot make any changes to the index (it was opened with readOnly = true)"
author: "m2000hsf"
date: "2011-09-10T13:13:57Z"
tags: []
categories: ["编程语言"]
slug: "cannot-make-any-changes-to-the-index-it-was-opened-with-readonly-true"
draft: false
lastmod: "2011-09-10T13:19:13Z"
id: 1169773
url: "https://develop.iteye.com/blog/1169773"
---

在调用IndexReader.open(final Directory directory)时候，在lucene3.0以上的版本中新增加属性中的readOnly默认为true（readOnly true if no changes (deletions, norms) will be made with this IndexReader），导致在删除索引的时候抛出UnsupportedOperationException。
解决方法为：
1、IndexReader源码中添加方法：
 
```java
public static IndexReader open(final String path, Boolean readOnly) throws
 CorruptIndexException, IOException {
	    return open(FSDirectory.open(new File(path)), null, null, 
readOnly, DEFAULT_TERMS_INDEX_DIVISOR);
	  }
```

2、应用代码中传递一参数：

```java
IndexReader indexReader = IndexReader.open(indexDir,false);
```


源码解释如下:

```java
/** Expert: returns an IndexReader reading the index in
   *  the given Directory, using a specific commit and with
   *  a custom {@link IndexDeletionPolicy}.  You should pass
   *  readOnly=true, since it gives much better concurrent
   *  performance, unless you intend to do write operations
   *  (delete documents or change norms) with the reader.
   * @param commit the specific {@link IndexCommit} to open;
   * see {@link IndexReader#listCommits} to list all commits
   * in a directory
   * @param deletionPolicy a custom deletion policy (only used
   *  if you use this reader to perform deletes or to set
   *  norms); see {@link IndexWriter} for details.
   * @param readOnly true if no changes (deletions, norms) will be made with this IndexReader
   * @param termInfosIndexDivisor Subsamples which indexed
   *  terms are loaded into RAM. This has the same effect as {@link
   *  IndexWriter#setTermIndexInterval} except that setting
   *  must be done at indexing time while this setting can be
   *  set per reader.  When set to N, then one in every
   *  N*termIndexInterval terms in the index is loaded into
   *  memory.  By setting this to a value > 1 you can reduce
   *  memory usage, at the expense of higher latency when
   *  loading a TermInfo.  The default value is 1.  Set this
   *  to -1 to skip loading the terms index entirely. This is only useful in 
   *  advanced situations when you will only .next() through all terms; 
   *  attempts to seek will hit an exception.
   *  
   * @throws CorruptIndexException if the index is corrupt
   * @throws IOException if there is a low-level IO error
   */
  public static IndexReader open(final IndexCommit commit, IndexDeletionPolicy deletionPolicy, boolean readOnly, int termInfosIndexDivisor) throws CorruptIndexException, IOException {
    return open(commit.getDirectory(), deletionPolicy, commit, readOnly, termInfosIndexDivisor);
  }
```