Sitecore Content Search API - Random Search Results using Solr

More often than you think you may get a requirement to show random related content on a page, whether it's related news articles for news website or related sale items for an eCommerce website or friend suggestions for a social networking website. This is a common requirement in eCommerce where we want to cross sell items from the same category as the current item. Most of the RDBMS databases have this feature built-in to return a random results for a select query, however Sitecore uses search providers to get its results which makes this little tricky to achieve.

In this article I will show how to achieve this using the Sitecore's default search provider Solr. Solr comes with a RandomSortField out of the box which you can use to sort results randomly. You will need to pass random_{RandomValue} or {RandomValue}_random as value for sort parameter to get your search results sorted randomly. However, for the same sort value the results are always sorted in the same order. So to get random results each time you need to pass different random values. Your Solr queries will look like below


The below code snippet shows how to get two random items under current item's parent excluding the current item using content search api.

From the code you can see we are passing a randomly generated value for the sort parameter which will randomize your search results. You can return either item ids or paths from search results and use it to fetch the full details of the individual related item using content search api.


Popular posts from this blog

SXA Scriban extension to get link field target URL

Using Sitecore FXM to update and track contacts