【问题标题】:lucene: how to perform an incremental indexing and avoid 'delete and redo'lucene:如何执行增量索引并避免“删除和重做”
【发布时间】:2012-09-17 15:39:20
【问题描述】:

我有一个包含大约 500 个文件的文件夹 (MY_FILES),每天都有一个新文件到达并放置在那里。每个文件的大小约为 4Mb。

我刚刚开发了一个简单的“void main”来测试我是否可以在这些文件中搜索特定的通配符。它工作得很好。

问题是我正在删除旧的 indexed_folder 并再次重新索引。这需要很多时间,而且显然效率低下。我正在寻找的是“增量索引”。意思是,如果索引已经存在 - 只需将新文件添加到索引中。

我想知道 Lucene 是否有某种机制来检查“doc”是否在尝试索引之前被索引。像 writer.isDocExists 这样的东西?

谢谢!

我的代码如下所示:

       // build the writer
       IndexWriter writer;
       IndexWriterConfig indexWriter = new IndexWriterConfig(Version.LUCENE_36, analyzer);
       writer = new IndexWriter(fsDir, indexWriter);
       writer.deleteAll();  //must - otherwise it will return duplicated result 
       //build the docs and add to writer
       File dir = new File(MY_FILES);
       File[] files = dir.listFiles();
       int counter = 0;
       for (File file : files) 
       { 
           String path = file.getCanonicalPath();
           FileReader reader = new FileReader(file);
           Document doc = new Document();  
           doc.add(new Field("filename", file.getName(), Field.Store.YES, Field.Index.ANALYZED));
           doc.add(new Field("path", path, Field.Store.YES, Field.Index.ANALYZED));
           doc.add(new Field("content", reader));  

           writer.addDocument(doc);
           System.out.println("indexing "+file.getName()+" "+ ++counter+"/"+files.length);
       }

【问题讨论】:

标签: java lucene


【解决方案1】:

首先,您应该使用IndexWriter.updateDocument(Term, Document) 而不是IndexWriter.addDocument 来更新文档,这将防止您的索引包含重复的条目。

要执行增量索引,您应该将last-modified 时间戳添加到索引的文档中,并且只索引较新的文档。

编辑:有关增量索引的更多详细信息

您的文档应至少包含两个字段:

  • 文件的路径
  • 文件最后一次修改的时间戳。

在开始编制索引之前,只需在您的索引中搜索最新的时间戳,然后爬取您的目录以查找时间戳比索引的最新时间戳更新的所有文件。

这样,您的索引将在每次文件更改时更新。

【讨论】:

  • 感谢@jpountz,您能否详细说明您的第二段。我使用了 Alexandre Dupriez 的方法并且效果很好(对于我目前需要的)。谢谢
【解决方案2】:

如果您想检查您的文档是否已存在于索引中,一种方法可能是生成关联的 Lucene 查询,您将使用该查询与 IndexSearcher 一起搜索 Lucene 索引。

例如,在这里,您可以使用字段filenamepathcontent 构建查询,以检查文档是否已存在于索引中。

除了IndexWriter 之外,您还需要一个IndexSearcher 并遵循Lucene 查询语法来生成您将提供给Lucene 的全文查询(例如

 filename:myfile path:mypath content:mycontent

)。

IndexSearcher indexSearcher = new IndexSearcher(directory);

String query = // generate your query

indexSearcher.search(query, collector);

在上面的代码中,collector 包含一个回调方法 collect,如果索引中的某些数据与查询匹配,则会使用文档 ID 调用该方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2018-01-01
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多