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(); 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)); 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(); 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) .GetContentResult();
Full code sample can be found in a gist
This (and your previous post on personalized find with Episerver Social) are really cool integrations! Thanks so much for sharing. Great stuff.
LikeLiked by 1 person
Glad you liked it 🙂
LikeLike