J'ai un forum comme application web écrit dans Asp.net MVC. J'essaie d'implémenter Lucene.net comme moteur de recherche. Quand je construis mon index, de temps en temps j'obtiens des exceptions liées au fait que Lucene ne puisse pas renommer le fichier deletable
. Je pense que c'est parce que je vide l'index chaque fois que je veux le reconstruire. Voici le code qui traite de l'indexation:Quelle est la bonne façon de reconstruire l'index de Lucene
public class SearchService : ISearchService
{
Directory IndexFileLocation;
IndexWriter Writer;
IndexReader Reader;
Analyzer Analyzer;
public SearchService(String indexLocation)
{
IndexFileLocation = FSDirectory.GetDirectory(indexLocation, System.IO.Directory.Exists(indexLocation) == false);
Reader = IndexReader.Open(IndexFileLocation);
Writer = new IndexWriter(IndexFileLocation, Analyzer, IndexFileLocation.List().Length == 0);
Analyzer = new StandardAnalyzer();
}
public void ClearIndex()
{
var DocumentCount = Writer.DocCount();
if (DocumentCount == 0)
return;
for (int i = 0; i < DocumentCount; i++)
Reader.DeleteDocument(i);
}
public void AddToSearchIndex(ISearchableData Data)
{
Document Doc = new Document();
foreach (var Entry in Data)
{
Field field = new Field(Entry.Key,
Entry.Value,
Lucene.Net.Documents.Field.Store.NO,
Lucene.Net.Documents.Field.Index.TOKENIZED,
Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS);
Doc.Add(field);
}
Field KeyField = new Field(
SearchField.Key.ToString(),
Data.Key,
Lucene.Net.Documents.Field.Store.YES,
Lucene.Net.Documents.Field.Index.NO);
Doc.Add(KeyField);
Writer.AddDocument(Doc);
}
public void Dispose()
{
Writer.Optimize();
Writer.Close();
Reader.Close();
}
}
Et voici le code qui exécute tout:
private void btnRebuildIndex_Click(object sender, EventArgs e)
{
using (var SearchService = new SearchService(Application.StartupPath + @"\indexs\"))
{
SearchService.ClearIndex();
}
using (var SearchService = new SearchService(Application.StartupPath + @"\indexs\"))
{
Int32 BatchSize = 50;
Int32 Current = 0;
var TotalQuestions = SubmissionService.GetQuestionsCount();
while (Current < TotalQuestions)
{
var Questions = SubmissionService.ListQuestions(Current, BatchSize, "Id", Qsparx.SortOrder.Asc);
foreach (var Question in Questions)
{
SearchService.AddToSearchIndex(Question.ToSearchableData());
}
Current += BatchSize;
}
}
}
Pourquoi Lucene se plaignent de renommer le fichier « effaçables »?
IndexFileLocation.List(). Length == 0 ne sera évalué que si aucun fichier d'index n'existe – Roman