Epinova / Epinova.Elasticsearch

A search-plugin for Episerver CMS and Commerce
MIT License
29 stars 20 forks source link

Indexing job overwrites best bets for content that has multiple best bets #173

Open jonatanjii opened 2 years ago

jonatanjii commented 2 years ago

If there are multiple best bets for a specific content the indexing job iterates them all and ovewrites the current value in each iteration resulting in that only the latest best bet is saved for each specific content item.

This only occurs if there are multiple separate best bets created for specific content item (multiple lines in the best bet admin ui that points to the same content).

image

image

For the case above the scheduled job will first update the index and write banana best bet and then do the same thing and overwrite it with apple.

Solution: Already existing code found in BestBetsRepository can be used in the indexing job´s method RestoreBestBets to only update each content item once with all its best bets. Something like this:

private void RestoreBestBetsCustom(IEnumerable<LanguageBranch> languages)
{
    foreach (var language in languages.Select(l => l.LanguageID))
    {
        try
        {
            var indexName = GetIndexName(language);
            _logger.Debug("Index: " + indexName);
            OnStatusChanged("Restoring best bets for index " + indexName);
            var bestBets = _bestBetsRepository.GetBestBets(language, indexName);

            var termsById = bestBets.GroupBy(b => b.Id)
                .Select(x => new {
                    Id = x.Key,
                    Terms = x.SelectMany(z => z.GetTerms()).ToArray()
                });

            foreach (var bestBet in termsById)
            {
                try
                {
                    _coreIndexer.UpdateBestBets(indexName, typeof(IndexItem), bestBet.Id, bestBet.Terms);
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("Failed to update best bets for content: {0}", bestBet.Id), ex);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Warning("Failed to update best bets mappings", ex);
        }
    }
}