2016-08-10 4 views
0

Я абсолютный новичок в Lucene и получил проблему с обновлением индекса.Обновление индекса Lucene на лету

В настоящее время я могу перестроить весь индекс ежедневно, но индекс обновляется только до момента создания, но как я могу обновить индекс, добавив его так, чтобы он обновлялся? В настоящее время существует код, пытающийся обновить индекс, но он только обновляет файлы сегментов, а не другие файлы.

Каждый раз, когда запись добавляется с моего сайта, она запускает метод RefreshFromDatabase и пытается добавить последний индекс, однако в индексной папке поиска он обновит два файла segment.gen и segment_t, однако все остальные файлы (.fdt .fdx .fnm .frq .nrm .prx .tii .tis .del .cfs) не обновляются. Вот скриншот: folder screenshot

код:

using (ISiteScope scope = _scopeFactory.GetSiteScope(site)){ 
     scope.Get<ISearchIndexUpdater>().RefreshFromDatabase(primaryId, secondaryId); 
     scope.Commit(); 
} 

public void RefreshFromDatabase(long primaryId, int? secondaryId){ 
    Process process = _processRepo.GetById(primaryId); 
    IList<Decision> allDecisions = _decisionRepo.GetByProcess(process); 
    IList<Link> allLinks = _linkRepo.GetActiveByProcess(process); 
    Decision current = allDecisions.OrderByDescending(x => x.DTG).FirstOrDefault(); 
    _luceneRepository.Add(process, allDecisions, allLinks); 
} 

public void Add(Process process, IList<Decision> decisions, IList<Link> links){ 
    if (null == decisions) 
    decisions = new List<Decision>(); 

    using (LuceneWriter writer = BeginWriter(false)) { 
     Add(writer.Writer, 
      new SearchIndexProcess { 
       // properties 
      }, 
      decisions.Select(x => new SearchIndexDecision { 
       // params 
      }).ToArray(), 
      (links ?? new List<Link>()).Select(x => new SearchIndexLink { 
       // properties 
      }).ToArray() 
     ); 
     writer.Commit(); 
    } 
} 

и LuceneWriter класс:

public class LuceneWriter : IDisposable 
     { 
       Directory _directory; 
       Analyzer _analyzer; 
       IndexWriter _indexWriter; 

       bool _commit; 
       bool _optimise; 

       /// <summary> 
       /// Constructor for LuceneWriter. 
       /// </summary> 
       /// <param name="fileSystem">An IFileSystem.</param> 
       /// <param name="luceneDir">The directory that contains the Lucene index. Need not exist.</param> 
       public LuceneWriter(IFileSystem fileSystem, string luceneDir) 
        : this(fileSystem, luceneDir, false) 
       { 
       } 

       /// <summary> 
       /// Constructor for LuceneWriter. 
       /// </summary> 
       /// <param name="fileSystem">An IFileSystem.</param> 
       /// <param name="luceneDir">The directory that contains the Lucene index. Need not exist.</param> 
       /// <param name="optimiseWhenDone">Optimse the index on Dispose(). This is an expensive operation.</param> 
       public LuceneWriter(IFileSystem fileSystem, string luceneDir, bool optimiseWhenDone) 
       { 
        Init(fileSystem, luceneDir, optimiseWhenDone); 
       } 

       //init has its own single use method for mocking reasons. 
       /// <summary> 
       /// Initialise the LuceneWriter. 
       /// </summary> 
       /// <param name="fileSystem">An IFileSystem.</param> 
       /// <param name="luceneDir">The directory containing the Lucene index.</param> 
       /// <param name="optimiseWhenDone">Whether or not to optimise the Lucene index upon Dispose().</param> 
       protected virtual void Init(IFileSystem fileSystem, string luceneDir, bool optimiseWhenDone) 
       { 
        _optimise = optimiseWhenDone; 

        bool exists = true; 
        if (!fileSystem.DirectoryExists(luceneDir)) { 
          fileSystem.CreateDirectory(luceneDir); 
          exists = false; 
        } 

        _directory = FSDirectory.Open(new DirectoryInfo(luceneDir)); 
        _analyzer = new StandardAnalyzer(Version.LUCENE_30); 
        _indexWriter = new IndexWriter(_directory, _analyzer, !exists, IndexWriter.MaxFieldLength.UNLIMITED); 
       } 

       /// <summary> 
       /// Flags writer to commit and optimise. Does not commit until Dispose() is called. 
       /// </summary> 
       public void Commit() 
       { 
        _commit = true; 
       } 

       /// <summary> 
       /// The IndexWriter. 
       /// </summary> 
       public IndexWriter Writer { get { return _indexWriter; } } 

       /// <summary> 
       /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 
       /// </summary> 
       /// <filterpriority>2</filterpriority> 
       public void Dispose() 
       { 
        if ((null != _indexWriter) && (_commit)) { 
          if (_optimise) 
            _indexWriter.Optimize(true); 
          _indexWriter.Commit(); 
          _indexWriter.Close(true); 
        } 

        if (null != _indexWriter) 
          _indexWriter.Dispose(); 
        if (null != _analyzer) 
          _analyzer.Dispose(); 
        if (null != _directory) { 
          _directory.Close(); 
          _directory.Dispose(); 
        } 
       } 
     } 

ответ

0

В Lucene нет обновления документов. Фактически удалять и добавлять. при обновлении документов. В старых сегментах он будет помечен как удаленный, и будет создан новый сегмент, и к нему добавится документ.

+0

да Я на самом деле добавляю к нему, но только два сегмента файлов segment.gen и segment_t и .cfs-файл изменены, а остальные не изменены – Xstaci

+0

Да, отдых не будет изменен до тех пор, пока вы не выполните слияние – aravinth

+0

Простите мое невежество, пожалуйста, сообщите мне, как это сделать, спасибо. Или нет необходимости сливаться и все еще выполнять как «слитый»? В чем моя ситуация, я изменил индекс на 2/8/2016, поэтому все файлы .prx .frq и т. Д. Не изменены, и есть способ записи индекса каждый раз, когда запись добавляется в базу данных , поэтому файл .cfs постоянно изменяется. Мой вопрос: обновлен ли индекс? – Xstaci

Смежные вопросы