How To Delete a Document using indexWriter in LuceneNet

…衆ロ難τιáo~ 提交于 2019-12-07 08:55:12

问题


I have this method that I invoke in my controller that have to delete a specific Document. I read in some articles that the best way to delete a Document is using a IndexWriter. But I can't make it work. This is my code

My Index:

    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();

The method delete:

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();
}

The method in the controller that invoke the "delete" void:

  public ActionResult Delete()
    {
        _carService.Delete("1");
        return RedirectToAction("Index", "Home");
    }

So I can't find my error,a little help please...


回答1:


When you build your IndexWriter for the delete method like that:

new IndexWriter(directory, analyzar, true, IndexWriter.MaxFieldLength.LIMITED);

You are specifying true for the create parameter, which overwrites the existing index with an empty one, deleting all your documents.




回答2:


That's because you're storing you id field as Field.Index.ANALYZED, you should always store id fields as Field.Index.NOT_ANALYZED, so that such fields won't be tokenized and will be stored in the index as is. Same for other fields that you don't want to be changed on indexing.



来源:https://stackoverflow.com/questions/10439505/how-to-delete-a-document-using-indexwriter-in-lucenenet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!