Limit fuzzy search within FuseJS to a specific category

607 views Asked by At

Let's say I have data that looks like the following:

[ 
  {"categories": ["North"], "title": "Welcome home", "content": "It was the best of times..."},  
  {"categories": ["South"], "title": "Welcome back", "content": "It was the worst of times..."}
]

I've got fuse configured as follows:

const fuse = new Fuse(articles, {
      keys: ['categories', 'content', 'title'],
    });

If I want to search within a category, but across all the fields, what is the best way to do that? Let's say I want to find all articles in the "North" category with "times" in either title or content, is there a way to do that with $and like as follows? (which I've tried and doesn't work):

fuse.search({$and: [{categories: "North"}, "times"]})

I've gotten it to work by manually setting "times" into the other fields with an $or flag, like the following:

fuse.search({
  $and: [ 
    {categories: "North"},
    {$or: [
      {title: "times"},
      {content: "times"}
      ]
    }
   }]);

At any rate, I'm curious if I can do it in a more simple way like above.

1

There are 1 answers

0
jloosli On

For what it's worth, it seems like the nested $and and $or is the best way to do it (at least that I could find).