1.异常:Lock obtain timed out: NativeFSLock
原因:没有及时关闭indexWriter或者indexReader,lucene进行读写的时候会在文件夹里面创建lock ,不关闭的话,lock一直存在,下次进行读写,就会出现该问题
解决方法:3.0以及3.0版本之前的,写入document之后,关闭indexWriter ,查询用到indexSearcher,查询结束之后需要关闭indexSearcher
3.0之后的,写入document之后,关闭indexWriter ,查询用到indexReader ,查询结束之后需要关闭indexReader
例:
private void closeIndexWriter(IndexWriter writer) { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (IndexWriter.isLocked(writer.getDirectory())) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } IndexWriter.unlock(writer.getDirectory()); } writer = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } 该方法需要放在外面,不然有可能在别的方法体内执行不了而没有关闭indexWriter
2.异常情况:
org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1024
at org.apache.lucene.search.BooleanQuery.add(BooleanQuery.java:165)
at org.apache.lucene.search.BooleanQuery.add(BooleanQuery.java:156)
at org.apache.lucene.search.RangeQuery.rewrite(RangeQuery.java:106)
原因:BooleanQuery用一个变量存储搜索字句 clauses 是一个List类型,同时使用另外一个变量限制其长度为1024 ,超过该数量,就会出现该异常。
比如,如果索引文档中包括条件 car 和 cars,那么使用 ca* 搜索之前,将被扩展成 car or cars。(查询字句的数目增大了,尤其是数据量较大,数据相似度较高,搜索条件较短的情况下这个出现的概率更高),这个条件列表的长度默认被限制在1024。当超出了1024的时候,就从上面的代码中抛出了异常。
解决方法:(1)、使用RangeFilter替换部分查询RangeQuery,但是效率会有影响;
(2)、设置默认长度值,BooleanQuery.setMaxClauseCount(),设置成10000,或者取消这个限制,BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE).
如果设置过大,有可能会出现out of memory 错误。
(3)、针对个别特殊的字段进行一些优化,比如时间字段保留到yyyyMMdd位,以避免后面时分位带来的搜索条件的扩大。
3.异常:java.lang.IllegalArgumentException: A SPI class of type org.apache.lucene.codecs
.Codec with name 'Lucene41' does not exist. You need to add the corresponding JA
R file supporting this SPI to your classpath.The current classpath supports the
following names: [Lucene40, Lucene3x, SimpleText, Appending]
原因:索引文件版本为lucene4.1 而打开索引的代码版本只支持lucene4.0以及以下的
4.索引删除不掉
可能原因:(1)删除之后没有提交indexWriter或者是关闭indexWriter.(2)用term指定的域删除,而那个域没有被索引,比如说id,把该域索引进去或者换索引过的域进行删除即可。
5.按照某些域排序,排序结果不正常
可能原因:(1)该域被分词了,导致排序出现不科学的结果。可以将该域不分词,查询的时候将关键字按空格切割,然后循环建立query
注意:可以按照评分,然后再按照自己选择的域排序。sort数组元素顺序表示排序选项优先级从高到低
6.异常:EOF错误
原因:用特殊字符查询会导致错误,比如() [] {} ^ : /
解决方法:传入参数查询之前进行替换。
name.replaceAll("\/", " ").replaceAll("\(", " ").replaceAll("\)", " ").replaceAll("\:", " ").replaceAll("\^", " ").replaceAll("\[", " ").replaceAll("\]", " ").replaceAll("\{", " ").replaceAll("\}", " ")