Adding weights per object
Can I add weights per object?
I have a bunch of objects I want to search through that have this structure.
{ "Term:"Apple pie", "Weight": 1.0 }
I have tried to use this for the options
{ key: ['Term'], scoreFn: a => a[0].score * a.obj.Weight }
But that sadly doesn't work.
Is this use case supported? Otherwise, I would just do a post-processing step and multiply the score by the weight. But then I would have to increase the threshold and limit in case an object gets boosted by its weight.
this is possible but admittedly a bit weird. weighted scores was intended for combining multiple scores when using multiple keys, and so only works when using multiple keys. and when using keys fuzzysort.go returns a KeysResults instead of the normal Results, which can be a bit awkward to work with. (also you'll want to divide the weight instead of multiply since scores are negative). here's an example
const objects = [
{ Term:"Apple pie", Weight: 1.0 },
{ Term:"cream pie", Weight: 2.0 },
{ Term:"pizza pie", Weight: 0.5 },
]
const results = fuzzysort.go('pie', objects, {
keys: ['Term'],
scoreFn: scores => scores[0]==null ? null : scores[0].score / scores.obj.Weight
}).map(fuzzysortKeysResultsToResults)
function fuzzysortKeysResultsToResults(result) {
result[0].obj = result.obj
result[0].score = result.score
return result[0]
}
console.log(results.map(r => [r.target, r.score]))
// [
// [ 'cream pie', -3.036 ],
// [ 'Apple pie', -6.072 ],
// [ 'pizza pie', -12.144 ]
// ]
Hi, thanks for your reply!
Your suggested code works with your test data, but when there is something really different in there i get
<a class='gotoLine' href='#51:22] TypeError: scores[0'>51:22] TypeError: scores[0</a> is null
I hope this link works https://jsfiddle.net/zd23rqvy/1/ Just uncomment the line with the extra entry.
Do you know how to fix this?
Do you know how to fix this?
yeah... this is something that should probably be changed but it's a breaking change that maybe some people rely on. scoreFn is called even when there isn't a match. so in that case scores[0] is null. you have to check if scores[0] == null then return null
scoreFn: scores => scores[0]==null ? null : scores[0].score / scores.obj.Weight
https://github.com/farzher/fuzzysort/issues/125#issuecomment-2113069011