Reputation: 313
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
Upvotes: 5
Views: 2774
Reputation: 12032
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.
Upvotes: 4