jacobdubail
jacobdubail

Reputation: 194

Algolia Facet sorting numerically

I'm using the algoliasearch and algoliasearchHelper libraries to build an instant search interface using the hogan template example on the algolia site.

I'm having an issue with sorting a numerical facet. I'm populating the index using the algoliasearch-client-php installed via composer. I'm passing an integer into the index object like so:

"cost_to_build"  => (int) $project->data['approximate_cost'],

But in the index, I'm getting something like:

cost_to_build: "15.00"

which then results in a facet order like:

15, 25, 3, 5, 6.

Even thoguh {sortBy: ['name:asc']}. If I manually change all of my index values to integers from strings (too many to really do manually, plus we update it regularly), the sorting works as desired.

Anyone have any tips?

Thanks!

Upvotes: 2

Views: 935

Answers (1)

Jerska
Jerska

Reputation: 12032

The fact that the value gets transformed from integer to strings is really surprising in itself and I don't have a clue on why this would happen.

However, there is still an easy solution without fixing the root cause. The sortBy parameter is also able to accept a comparison function, so you can cast those values to integers in your front-end instead of your back-end.

Something along those lines should work :

helper.on('results', function(content){
  //get values  ordered only by count ascending using a function
  content.getFacetValues('cost_to_build', {
    sortBy: function(a, b) {
      return parseInt(a.name, 10) - parseInt(b.name, 10);
    }
  });
});

Upvotes: 2

Related Questions