Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fuse.js : How to return an exact match when there are two words to search for?

Here's what I'm trying to accomplish.

Old War shouldn't match, but it does. -> It's not what I'm looking for, there must be an exact match, even though there are two words. Old Man is a yes, but Old War is a no.

Man's War should match. It does at this moment.

Silmarillion should match. It does at this moment.

The Silmarillion should also match. It does at this moment.

var express = require('express');
var router = express.Router();
var path = require("path");
var async1 = require("async");
var Fuse = require("fuse.js");

var options = {
  shouldSort: true,
  tokenize: true,
  matchAllTokens: true,
  findAllMatches: true,
  threshold: 0,
  location: 0,
  distance: 0,
  maxPatternLength: 32,
  minMatchCharLength: 2,
  keys: ["title"]
};


var arr = [
  {
    title: "Old Man's War",
    author: {
      firstName: "John",
      lastName: "Scalzi"
    }
  }, 
  {
    title: "The SilmarillionADDITIONALTEXT",
    author: {
      firstName: "J.R.R",
      lastName: "Tolkien"
    }
  }
];

var keywords = ["Old War", "random title"];

router.get('/search', function (req, res, next) {

  async1.waterfall([
    function (callback) {
      var fuse = new Fuse(r, options);

      async1.map(keywords, function (keyword, asyncCallback) {
        var results = fuse.search(keyword);

        if (results.length !== 0) {
          async1.map(results, function (result, async2Callback) {
            console.log(result.title + " " + keyword);
          });
        }
      });
      callback(null, 'done!');
    }
  ], function (err, result) {
    res.sendStatus(200);
  });

});
like image 850
salep Avatar asked Oct 18 '22 03:10

salep


1 Answers

You set tokenize to true. This means that your search "Old War" gets tokenized into ["Old","War"]. Both those tokens match perfectly so it is working correctly. To achieve the output you want, set tokenize to false. Also, setting tokenize to true ignores the settings for threshold, location and distance.

like image 182
Konrad Höffner Avatar answered Oct 31 '22 10:10

Konrad Höffner