Lucene中IndexSearcher的构造函数有以下几个:
/** */
/** Creates a searcher searching the index in the named directory. */
public IndexSearcher(String path) throws IOException ... {
this(IndexReader.open(path), true);
}
/** */ /** Creates a searcher searching the index in the provided directory. */
public IndexSearcher(Directory directory) throws IOException ... {
this(IndexReader.open(directory), true);
}
/** */ /** Creates a searcher searching the provided index. */
public IndexSearcher(IndexReader r) ... {
this(r, false);
}
private IndexSearcher(IndexReader r, boolean closeReader) ... {
reader = r;
this.closeReader = closeReader;
}
public IndexSearcher(String path) throws IOException ... {
this(IndexReader.open(path), true);
}
/** */ /** Creates a searcher searching the index in the provided directory. */
public IndexSearcher(Directory directory) throws IOException ... {
this(IndexReader.open(directory), true);
}
/** */ /** Creates a searcher searching the provided index. */
public IndexSearcher(IndexReader r) ... {
this(r, false);
}
private IndexSearcher(IndexReader r, boolean closeReader) ... {
reader = r;
this.closeReader = closeReader;
}
由此可知,可以用索引文件的存储路径path、文件对象file、索引对象(即IndexReader对象)reader初始化IndexSearcher对象,从上边的代码可以看到前两个构造函数的参数(path或directory)都转换为索引对象,同时多了一个boolean类型的参数closeReader,那么这个增加的参数的作用是什么呢?那么我们可以在IndexSearcher类中搜索,可以看到:
/** */
/**
* Note that the underlying IndexReader is not closed, if
* IndexSearcher was constructed with IndexSearcher(IndexReader r).
* If the IndexReader was supplied implicitly by specifying a directory, then
* the IndexReader gets closed.
*/
public void close() throws IOException ... {
if(closeReader)
reader.close();
}
* Note that the underlying IndexReader is not closed, if
* IndexSearcher was constructed with IndexSearcher(IndexReader r).
* If the IndexReader was supplied implicitly by specifying a directory, then
* the IndexReader gets closed.
*/
public void close() throws IOException ... {
if(closeReader)
reader.close();
}
可以看到注释中写到:注意,如果
IndexSearcher
对象由
IndexSearcher(IndexReader
r)
初始化,下边的索引(
IndexReader
)对象不关闭。若如果索引(
IndexReader
)对象由一个指定的路径暗中生成,那么
IndexReader
对象将关闭。
索引(
IndexReader
)对象在搜索之前就已定义,这个索引对象不属于
IndexSearcher
对象,索引(
IndexReader
)对象就不能关闭。
在
lucene
应用中也许很多人都遇到这种情况。当索引太大(大于
10G
),搜索时用前两种构造方法声明
IndexSearcher
对象,这样每构造一个
IndexSearcher
对象,都要声明一个索引对象(实际上是一个索引的多次连接),而每个索引对象都要占用一定量的系统资源(主要是内存)。当大量用户访问系统时,就会看到系统内容直线增长,致使产生“
java heap space
”内存耗尽。这个问题可以通过以下方法解决:
每个索引都声明一个
static
的索引对象
(
即
IndexReader
对象
)
,以后每个针对这个索引的索引都通过这个
static
对象声明
IndexSearcher
对象,也就是
IndexSearcher
的第三个构造函数的应用。