我有这个方法,我在我的控制器中调用,必须删除一个特定的文档。我在一些文章中读到删除文档的最佳方法是使用IndexWriter。但我不能让它发挥作用。这是我的代码
我的索引:
var article1 = new Document();
article1.Add(new Field("Id", "1", Field.Store.YES, Field.Index.ANALYZED));
article1.Add(new Field("Author", "Author", Field.Store.YES, Field.Index.ANALYZED));
article1.Add(new Field("Title", "Title", Field.Store.YES, Field.Index.ANALYZED));
var directory = FSDirectory.Open(new DirectoryInfo(IndexRoute));
var analyzar = new StandardAnalyzer(Version.LUCENE_29);
var writer = new IndexWriter(directory, analyzar, true, IndexWriter.MaxFieldLength.LIMITED);
writer.AddDocument(article1);
writer.Optimize();
writer.Commit();
writer.Close();
方法删除:
public void Delete(string id)
{
var directory = FSDirectory.Open(new DirectoryInfo(IndexRoute));
var analyzar = new StandardAnalyzer(Version.LUCENE_29);
var writer = new IndexWriter(directory, analyzar, true, IndexWriter.MaxFieldLength.LIMITED);
var term = new Term("Id", id);
writer.DeleteDocuments(term);
writer.Optimize();
writer.Commit();
writer.Close();
}
控制器中调用“delete”void的方法:
public ActionResult Delete()
{
_carService.Delete("1");
return RedirectToAction("Index", "Home");
}
所以我找不到我的错误,请一点帮助......
答案 0 :(得分:11)
为删除方法构建IndexWriter时:
new IndexWriter(directory, analyzar, true, IndexWriter.MaxFieldLength.LIMITED);
您为create参数指定true,该参数用空的索引覆盖现有索引,删除所有文档。
答案 1 :(得分:4)
那是因为你将id字段存储为Field.Index.ANALYZED
,你应该始终将id字段存储为Field.Index.NOT_ANALYZED
,这样这些字段就不会被标记化,而是会被存储在索引中。 。对于您不希望在索引编制时更改的其他字段也是如此。