How to Randomly Display Hits on the Searches Initial Load

Hi,

I’m using Laravel & InstantSearch js for my search.

I want to display my hits randomly for the searches initial load/state.

Currently, my hits display (before being filtered) initially in the order of when they were created/added to the search.

I want my hits to be random on the searches initial load in order to give each result equal exposure.

I’d appreciate any help, thanks in advance.

This idea appears to be in the right area but I haven’t managed to get it to work https://stackoverflow.com/questions/36748131/algolia-instantsearch-js-how-to-display-the-results-with-a-random-order

Hey Alex! Algolia returns results by relevance, but nothing keeps you from reshuffling them before displaying them on your search UI.

The solution you linked form SatckOverflow is a good start, but it’s using the API of an older version of InstantSearch.js, which is why it’s probably not working.

Instead of transformData, you can use the transformItems method when passing options to the hits widget:

search.addWidget(
  instantsearch.widgets.hits({
    // your other options
    transformItems: shuffle,
  })
);

This should work starting from InstantSearch.js v2, up to the current v4 version. You can find out more about transformItems on our documentation: https://www.algolia.com/doc/api-reference/widgets/hits/js/#widget-param-transformitems

Best.

1 Like

Thanks for your reply.

This has worked really well.

Is there a way to isolate this to just the initial load of the search and not to be affected by using the pagination/filters?

Hello Alex,

For this you’ll need to use the connector https://www.algolia.com/doc/api-reference/widgets/hits/js/#connector .

From here you’ll have access to renderOptions with the complete results object. In this object you have access to the query, pagination or filters applied, so you can use it to only apply your transformation in some particular cases.

1 Like

Thanks for your reply, much appreciated.