我有一个文件夹 (MY_FILES),其中包含大约 500 个文件,每天都有一个新文件到达并放置在那里。每个文件的大小约为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);
}
首先,您应该使用 IndexWriter.updateDocument(Term, Document) 而不是 IndexWriter.addDocument
来更新文档,这将防止索引包含重复的条目。
若要执行增量索引,应将上次修改的
时间戳添加到索引的文档,并且仅为较新的文档添加索引。
编辑:有关增量索引的更多详细信息
您的文档至少应有两个字段:
在开始索引之前,只需在索引中搜索最新的时间戳,然后抓取目录以查找时间戳比索引的最新时间戳更新的所有文件。
这样,您的索引将在每次文件更改时更新。
如果您想检查您的文档是否已经存在于索引中,一种方法可能是生成关联的Lucene查询,您将使用该查询与IndexSearcher
一起搜索Lucene索引。
例如,在这里,您可以使用字段文件名
、路径
和内容
构建查询,以检查文档是否已存在于索引中。
除了< code>IndexWriter之外,您还需要一个< code>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调用该方法。