3

Using Fuse.js, I need to weight individual item for a better ranking in search results. For instance, how do I make sure "Paris France" has the biggest score for a "Paris" query with the data below?

places = [{
  name: 'Paris, France'
  weigth: 10
},{
  name: 'Paris, Ontario'
  weigth: 2
},
{
  name: 'Paris, Texas'
  weigth: 1
}]
Félix Ménard
  • 453
  • 4
  • 10

1 Answers1

1

As far as I am aware, there are no methods built into Fuse.js to do this. The weight property is meant to be applied to properties which are being searched (in the options object), rather than to the object that is being searched (as seen in the example here.

What I might suggest is writing a function to sort this yourself. So once you get your results array back, after the search, perform an Array.sort() on it yourself (documentation here).

For example...

//Your places object
var places = [
  {
    name: 'Paris, Texas',
    weight: 2
  },
  {
    name: 'Paris, France',
    weight: 10
  },
  {
    name: 'Paris, Texas',
    weight: 1
  }
];

//Your search options
var options = {
  keys: [
    "name"
  ]
};
var fuse = new Fuse(places, options); // "list" is the item array
var result = fuse.search("Paris");

//Once you have got this result, perform your own sort on it:

result.sort(function(a, b) {
    return b.weight - a.weight;
});

console.log('Your sorted results:');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.1.0/fuse.min.js"></script>
Sam Conran
  • 156
  • 1
  • 7
  • 2
    Doing a second sort is a good patch. I also experimented with the quality score returned by Fuse and using the weights as multipliers. Otherwise, the second sort might end up surfacing otherwise poor matches. – Félix Ménard Oct 13 '17 at 17:05