Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algolia instantsearch.js : how to display the results with a random order?

I am using Algolia instantsearch.js to display candidates to an election (here: https://laprimaire.org/candidats/). I would like the initial display of candidates to be random so that every candidate gets more or less the same visibility.

I read in this answer that it is not a feature of Algolia but that it should be possible to do it anyway with a little js trick : Is it possible to sort randomly, and to query on field if it exists?

Problem is I am using instantsearch.js and I cannot find how to implement the above searchFunction in the case of instantsearch.js.

I see from the documentation that instantsearch can be initialized with a searchFunction which receives a helper as a parameter: https://community.algolia.com/instantsearch.js/documentation/#initialization

However it did not find documentation about this helper and how to manipulate it, so that I can apply the random function to the search results.

Any help would be greatly appreciated ! Thanks a lot

Thibauld

like image 1000
Thibauld Avatar asked Apr 20 '16 15:04

Thibauld


1 Answers

The hits widget has a way for you to get more control on how to display the list of hits through the transformData.allItems and templates.allItems parameters.

Using the shuffle method of this question How can I shuffle an array? :

function shuffle (o){
  for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
}

You can simply do:

search.addWidget(
  instantsearch.widgets.hits({
    // Your other options
    transformData: {
      allItems: function (content) {
        return { hits: shuffle(content.hits) };
      }
    },
    templates: {
      empty: 'No results',
      allItems: '{{#hits}}<your previous templates.hit value>{{/hits}}'
    }
  })
);

The {{#hits}}{{/hits}} template is simply some Hogan.js logic to loop on each of your hits.

like image 105
Jerska Avatar answered Oct 14 '22 14:10

Jerska