在lucene.net重新编制索引

时间:2012-12-13 07:16:53

标签: c# lucene.net

我正在使用lucene.net。我正在编写一个代码,它应该在一段时间后索引回相同的文件夹。如果已将该文件夹中的内容编入索引,如何重新编制索引?说我索引了4个文档。并且在5分钟之后,任何文档都没有变化,那么如何管理这种情况? 另外我想知道如果其中一个文件最近更新了,那么我如何通过替换或删除旧文件来仅返回该文件?

2 个答案:

答案 0 :(得分:1)

只需存储每个文件的时间戳,或某处的CRC(IE是数据库)。

然后,您抓取文件系统并仅更新使用IndexWriter.UpdateDocument()更改的文件,使用IndexWriter.AddDocument()添加新文件,并使用IndexWriter.DeleteDocument()删除不再存在的文件。

答案 1 :(得分:0)

在现代版本的 Lucene.Net 中,您可以将键作为文档的一部分进行索引,然后根据键修剪现有索引:

var document = new Document()
{
  new StringField("DocumentId", source.DocumentId, Field.Store.YES),
  new StringField("DocumentPath", source.DocumentPath, Field.Store.YES),
  new TextField("Content", source.Text, Field.Store.NO),
  new TextField("Tags", source.Tags, Field.Store.YES),
};

...

var writer = GetIndexWriter();

// Delete existing records
var query = new BooleanQuery
{
  {new TermQuery(new Term("DocumentId", source.DocumentId)), Occur.MUST},
  {new TermQuery(new Term("DocumentPath", source.DocumentPath)), Occur.MUST},
};
writer.DeleteDocuments(query);

// Add new document
writer.AddDocument(document);

例如,您还可以将上次更新时间戳存储为索引的一部分,并使用它来确定何时重新索引文件。

绝对不需要为此使用外部数据库。

注意:您应该为此使用StringField,而不是TextField,以便您可以匹配复杂的键; IE。 TextField 可能会将像 ABC-DEF 这样的 id 转换为标记 ABC 和 DEF,因此术语搜索查询将无法准确匹配 ABC-DEF