using Lucene.Net.Index; using Portoa.Logging; using Portoa.Persistence; using VideoGameQuotes.Api.Persistence; namespace VideoGameQuotes.Api.Search.Lucene { public class LuceneEntityIndexBuilder : ISearchIndexBuilder where T : Entity { private readonly ILogger logger; private readonly IndexWriter indexWriter; private readonly ISearchService searchService; private readonly ILuceneDocumentHandler documentHandler; public LuceneEntityIndexBuilder(IndexWriter indexWriter, ISearchService searchService, ILuceneDocumentHandler documentHandler, ILogger logger) { this.indexWriter = indexWriter; this.searchService = searchService; this.documentHandler = documentHandler; this.logger = logger; } public void BuildIndex() { logger.Info("Building lucene index"); foreach (var quote in searchService.GetAllIndexableRecords()) { indexWriter.AddDocument(documentHandler.BuildDocument(quote)); } indexWriter.Optimize(); indexWriter.Commit(); logger.Info("Finished building lucene index"); } public void UpdateIndex(T entity) { if (entity.IsTransient()) { throw new SearchIndexException(string.Format("Cannot add a transient entity to the index ({0})", entity)); } logger.Info(string.Format("Updating index for {0}", entity)); //delete current document, if it exists indexWriter.DeleteDocuments(documentHandler.GetIdTerm(entity)); indexWriter.AddDocument(documentHandler.BuildDocument(entity)); indexWriter.Commit(); logger.Info(string.Format("Finished updating index for {0}", entity)); } } }