45 lines
1.6 KiB
C#
45 lines
1.6 KiB
C#
using Lucene.Net.Index;
|
|
using Portoa.Logging;
|
|
using Portoa.Persistence;
|
|
using VideoGameQuotes.Api.Persistence;
|
|
|
|
namespace VideoGameQuotes.Api.Search.Lucene {
|
|
public class LuceneEntityIndexBuilder<T> : ISearchIndexBuilder<T> where T : Entity<T, int> {
|
|
private readonly ILogger logger;
|
|
private readonly IndexWriter indexWriter;
|
|
private readonly ISearchService<T> searchService;
|
|
private readonly ILuceneDocumentHandler<T> documentHandler;
|
|
|
|
public LuceneEntityIndexBuilder(IndexWriter indexWriter, ISearchService<T> searchService, ILuceneDocumentHandler<T> 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));
|
|
}
|
|
}
|
|
} |