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 =
        ServiceLocator.Current.GetInstance<ISocialRatingRepository>();

    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<IContent>().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<SocialRatingActivity>
{
    public void Handle(Activity activity, SocialRatingActivity extension)
    {
        IContentRepository contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();

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

        HandleFindIndexing(content);
    }

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

        if (ok && shouldIndex)
        {
            ContentIndexer.Instance.Index(content);
        }
}

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<IActivityService>();

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<SitePageData> contentResult = this.searchClient.Search<SitePageData>()
        .Filter(c => c.GetRatingAverage().GreaterThan(0))
        .OrderByDescending(c => c.GetRatingAverage()).Take(25)
        .GetContentResult();

Full code sample can be found in a gist

Advertisements

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:

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s