krisk / Fuse

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

How do I search for multiple results? #683

Closed ChrisMGeo closed 1 year ago

ChrisMGeo commented 1 year ago

I have an array of character names called characterList, which I want to search from. I sometimes have strings with multiple of these character names, and would like to return every single search result and their indices.

import Fuse from "fuse.js";
const options = {};
const characterList = ["John", "Chris", "Sarah", "Jun"];
const characterFuse = new Fuse(characterList, options);
console.log(characterFuse.search("John met Chris and Sarah at the park."));

How would I return John, Chris and Sarah with their approximate indices, and not just one or none of them?

modyabhi commented 1 year ago

I am unsure what you're trying to do here but if you use it the other way seems more logical, having your characterList search in the text. Also tokenise the string to create an array out of your string first.

so your input text should look like this

const inputArray = ["John" ,"met" ,"Chris" ,"and" ,"Sarah" ,"at" ,"the" ,"park."]

include this in the options useExtendedSearch:true

and the character list to be constructed with = in front of every single character as you'd like to make an exact search.

See the below code that worked for me:

const options = {useExtendedSearch: true};
const characterList = ["=John", "=Chris", "=Sarah", "=Jun"];
const query = characterList.join("|")
const inputArray = ["John" ,"met" ,"Chris" ,"and" ,"Sarah" ,"at" ,"the" ,"park."]
const fuse = new Fuse(inputArray, options);
const result = fuse.search(query);
console.log((result));

results:

[{"item":"John","refIndex":0},
{"item":"Chris","refIndex":2},
{"item":"Sarah","refIndex":4}]

For more info look at the extended search of their documentation : https://fusejs.io/examples.html#extended-search

github-actions[bot] commented 1 year ago

This issue is stale because it has been open 120 days with no activity. Remove stale label or comment or this will be closed in 30 days