Add the average rating of content to your Find index

If you are using Episerver Social on your site, you may want to add the average rating of a page to the find index. The code is based on the SocialAlloy sample.

This is the way how to make that work

First add an extension method that gets the average rating of your content item.

public static double GetRatingAverage(this IContent content)
    ISocialRatingRepository socialRatingRepository =

    return socialRatingRepository.GetRatingStatistics(content.ContentGuid.ToString())?.Average ?? 0;

Now you can index the rating average together with your content. Add the following to your/a initialization module

SearchClient.Instance.Conventions.ForInstancesOf().IncludeField(x => x.GetRatingAverage());

As the content itself is not changed, you will need to reindex your content item when a new rating is given. You can use an ActivityHandler, available in Episerver Social, for this.

public class ContentRatedActivityHandler : IActivityHandler
    public void Handle(Activity activity, SocialRatingActivity extension)
        IContentRepository contentRepository = ServiceLocator.Current.GetInstance();

        IContent content = contentRepository.Get(Guid.Parse(activity.Target.Id));


    private static void HandleFindIndexing(IContent content)
        bool shouldIndex;
        bool ok = ContentIndexer.Instance.TryShouldIndex(content, out shouldIndex);

        if (ok && shouldIndex)

The last thing you will need to do is to have the ActivityService watch the handler. You can do this in the initializable module you use for Social.

IActivityService activityService = context.Locate.Advanced.GetInstance();

activityService.Watch(new ContentRatedActivityHandler());

Now the average ratings are indexed together with your content. And updated.

You could use this to display your top 25 rated pages/products for example.

IContentResult contentResult = this.searchClient.Search()
        .Filter(c => c.GetRatingAverage().GreaterThan(0))
        .OrderByDescending(c => c.GetRatingAverage()).Take(25)

Full code sample can be found in a gist

2 thoughts on “Add the average rating of content to your Find index

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s