2013-02-25 140 views
1

我跟隨這篇文章http://leoncullens.nl/post/2012/11/18/Full-Text-Search-on-Azure-with-LuceneNET.aspx來設置Lucene索引。Lucene更新文檔索引

它在大多數情況下可以平穩運行,所以如果有一個綁定到id的現有文檔將其刪除,然後重新插入它?

編輯以下方法:

public void CreateIndex() { 


IndexWriter indexWriter = new IndexWriter(_directory, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED); // Create the IndexWriter 

    foreach (Book book in _bookService.List()) // Use whatever data source you like 
    { 
     // NEED TO INSERT A CHECK HERE TO SEE IF A DOC EXISTS 
     Document document = CreateBookDocument(book); // Create a 'Document' for each row of your data 

     indexWriter.AddDocument(document); 
    } 

    try 
    { 
     indexWriter.Optimize(); // Call optimize once to improve performance 
     indexWriter.Dispose(); // Commit and dispose the object 

     Thread.Sleep(60 * 10 * 1000); // Sleep 10 minutes when the index is created successfully, otherwise immediately restart the process 
    } 
    catch (Exception) 
    { 
     indexWriter.Rollback(); 
     indexWriter.Dispose(); 
    } 
} 

private Document CreateBookDocument(Book book) 
{ 
    Document document = new Document(); 
    document.Add(new Field("Id", book.Id.ToString(), Field.Store.YES, Field.Index.NO, Field.TermVector.NO)); // We want to store the ID so we can retrieve data for the ID, but we don't want to index it because it is useless searching through the IDs 
    document.Add(new Field("Title", book.Title, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO)); 
    document.Add(new Field("Publisher", book.Publisher, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO)); 
    document.Add(new Field("Isbn10", book.Isbn10, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO)); 

    return document; 
} 

回答

1

據我所知,沒有這樣的事情實際上不更新內部Lucene的文檔實例。它總是以刪除/插入的方式完成。

+0

疑難雜症我怎麼能檢查是否存在文檔然後將其刪除? – Joe 2013-02-26 14:42:16

1

我們使用Lucene.Net 2.0.0.4,對於3.0我認爲它們是相同的。

首先您需要添加ID爲Field.Index.TOKENIZED,然後您可以修改(刪除,然後插入)索引。

document.Add(new Field("Id", book.Id.ToString(), Field.Store.YES, Field.Index.TOKENIZED)); 

然後打開索引而不是創造新的

IndexWriter indexWriter = new IndexWriter(_directory, new StandardAnalyzer(Version.LUCENE_30), false, IndexWriter.MaxFieldLength.UNLIMITED); 

有刪除示例代碼:

IndexReader reader = IndexReader.Open(_directory); 
reader.DeleteDocuments(new Term("Id", book_id_delete)); 
reader.Close();