【问题标题】:Should I keep Lucene IndexWriter open for entire indexing or close after each document addition?我应该保持 Lucene IndexWriter 为整个索引打开还是在每个文档添加后关闭?
【发布时间】:2016-09-26 11:06:44
【问题描述】:

每次添加文档后关闭 Lucene IndexWriter 会减慢我的索引过程吗?

我想,关闭和打开索引编写器会减慢我的索引过程,还是 Lucene 不是这样?

基本上,我在 Spring Batch 作业中有一个 Lucene 索引器步骤,并且我在 ItemProcessor 中创建索引。 Indexer Step 是一个分区步骤,我在创建 ItemProcessor 时创建 IndexWriter 并保持打开状态直到步骤完成。

@Bean
    @StepScope
    public ItemProcessor<InputVO,OutputVO> luceneIndexProcessor(@Value("#{stepExecutionContext[field1]}") String str) throws Exception{
        boolean exists = IndexUtils.checkIndexDir(str);
        String indexDir = IndexUtils.createAndGetIndexPath(str, exists);
        IndexWriterUtils indexWriterUtils = new IndexWriterUtils(indexDir, exists);
        IndexWriter indexWriter = indexWriterUtils.createIndexWriter();
        return new LuceneIndexProcessor(indexWriter);
    }

有没有办法在步骤完成后关闭这个IndexWriter

另外,我遇​​到了问题,因为我也在这一步中搜索以查找重复的文档,但我通过在打开阅读器和搜索之前添加 writer.commit(); 解决了这个问题。

请建议我是否需要在每次添加文档后关闭并打开或可以一直保持打开?以及如何关闭StepExecutionListenerSupportafterStep

最初,我为每个文档关闭并重新打开,但索引过程非常缓慢,所以我认为这可能是原因。

【问题讨论】:

  • 您应该绝对在整个索引过程中保持一个IndexWriter 打开。正如您已经看到的,为每个文档打开一个新文档会大大减慢它的速度。

标签: java lucene spring-batch


【解决方案1】:

由于在开发中,索引目录很小,所以我们可能看不到太多收益,但是对于较大的索引目录大小,我们不需要对IndexWriterIndexReader 进行不必要的创建和关闭。

在 Spring Batch 中,我通过这些步骤完成了它

1.正如my other question所指出的,首先我们需要解决序列化问题,将对象放入ExecutionContext

2.我们在分区器的ExecutionContext中创建并放入复合可序列化对象的实例。

3.将值从ExecutionContext 传递给配置中的步进读取器、处理器或写入器,

    @Bean
    @StepScope
    public ItemProcessor<InputVO,OutputVO> luceneIndexProcessor(@Value("#{stepExecutionContext[field1]}") String field1,@Value("#{stepExecutionContext[luceneObjects]}") SerializableLuceneObjects luceneObjects) throws Exception{
        LuceneIndexProcessor indexProcessor =new LuceneIndexProcessor(luceneObjects);
        return indexProcessor;
    }

4.在需要的地方使用处理器中传递的这个实例,并使用getter方法获取索引读取器或写入器,public IndexWriter getLuceneIndexWriter() {return luceneIndexWriter;}

5.最后在StepExecutionListenerSupportafterStep(StepExecution stepExecution) 中通过从ExecutionContext 获取来关闭此作者或读者。

ExecutionContext executionContext = stepExecution.getExecutionContext();
SerializableLuceneObjects slObjects = (SerializableLuceneObjects)executionContext.get("luceneObjects");
IndexWriter luceneIndexWriter = slObjects.getLuceneIndexWriter();
IndexReader luceneIndexReader = slObjects.getLuceneIndexReader();
if(luceneIndexWriter !=null ) luceneIndexWriter.close();
if(luceneIndexReader != null) luceneIndexReader.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2011-05-25
    相关资源
    最近更新 更多