krisk / Fuse

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

Expose the searcher #15

Closed chaoaretasty closed 10 years ago

chaoaretasty commented 10 years ago

I'm liking the fuzzy search but would love to be able to integrate it into my current search function.

I was wondering if it's possible to expose the Searcher as well as Fuse so that it's possible to just get the score for any given match without the list handling and sorting it already does.

This would make it much easier to integrate into more complex algorithms.

krisk commented 10 years ago

Could please elaborate? Thanks!

chaoaretasty commented 10 years ago

Sure.

Currently only Fuse itself is added to the globals but there are cases where the Searcher is useful in and of itself but there's no access to it. There are also occasions you might want to expose the actual score which currently gets eaten.

For example custom I've got a search function I think this could be a good fit with. It generates a score currently by a full text match on several fields with separate weightings (ie an item's relevance is 2x match(header) + 1x match(shortdescription) + 0.5x match(long description)). If Fuse's searcher was made public match could return the score rather than just 1 or 0.

krisk commented 10 years ago

Sounds good.

This should all be available with the latest release, as new options have been added. What you may be especially interested in is the ability to set the searchFn. Right now it defaults to BitapSearcher.

Additional options

// Fuse default options:
// Whether the score should be included in the result set.
// When <true>, each result in the list will be of the form: 
// `{ item: ..., score: ... }`
includeScore: false,

// Whether to sort the result list, by score
shouldSort: true,

// The search function to use
// Note that the default search function ([[Function]]) must 
// conform the following API:
//
//  @param pattern The pattern string to search
//  @param options The search option
//  [[Function]].constructor = function(pattern, options)
//
//  @param text: the string to search in for the pattern
//  @return Object in the form of:
//    - isMatch: boolean
//    - score: Int
//  [[Function]].prototype.search = function(text)
searchFn: BitapSearcher,

// The sort function to use
sortFn: function(a, b) {
  return a.score - b.score;
}
chaoaretasty commented 10 years ago

As long as it exposes the BitapSearcher without needing to use the other parts of Fuse that sounds great. (I love what Fuse does but for some of my use cases that bit gets in the way).

chaoaretasty commented 10 years ago

Thanks, done a quick test and I can get the searcher via var bitap = new Fuse.defaultOptions.searchFn(pattern, options)

Noticed a small bug though that prevents you doing this with null or undefined options. I'll send a pull request.