fuzzysort icon indicating copy to clipboard operation
fuzzysort copied to clipboard

Adding weights per object

Open ShinichiHezemansCortegs opened this issue 1 year ago • 3 comments

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.

ShinichiHezemansCortegs avatar Apr 04 '24 05:04 ShinichiHezemansCortegs

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 ]
// ]

farzher avatar Apr 04 '24 15:04 farzher

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?

ShinichiHezemansCortegs avatar Apr 08 '24 05:04 ShinichiHezemansCortegs

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

farzher avatar Apr 08 '24 16:04 farzher

https://github.com/farzher/fuzzysort/issues/125#issuecomment-2113069011

farzher avatar May 15 '24 17:05 farzher