krisk / Fuse

Lightweight fuzzy-search, in JavaScript
https://fusejs.io/
Apache License 2.0
18.05k stars 766 forks source link

Mixing logical and fuzzy search #448

Closed jlismore closed 4 years ago

jlismore commented 4 years ago

From the docs it seems there are two ways of searching a list

However it doesn't look like it's possible to combine the two methods simply. Imagine I want to search my list for every item where color === 'blue' AND any field contains 'new'. I could do this by combining $and and $or operators, but the $or becomes really verbose once there are more than a few keys.

const result = fuse.search({
  $and: [
    { color: "'blue" }, // Exact match for blue
    {
      $or: [
        { title: 'new' }, 
        { type: 'new' },
        { family: 'new' },
        { group: 'new' },
        ...
      ]
    }
  ]
})

Is there a better way to accomplish this?

belvederef commented 4 years ago

Maybe there is a better solution but if you need to search a word in any field of the object obj, and given you have already defined a set of keys keys to index, then I can recommend using:

$or: keys.map((k) => ({ [k]: 'new' }))
krisk commented 4 years ago

Maybe there is a better solution but if you need to search a word in any field of the object obj, and given you have already defined a set of keys keys to index, then I can recommend using:

$or: keys.map((k) => ({ [k]: 'new' }))

That's a pretty good solution.