fuse.js vs fuzzy vs fuzzy-search vs fuzzyset
Implementing Fuzzy Search in Frontend Applications
fuse.jsfuzzyfuzzy-searchfuzzyset类似的npm包:

Implementing Fuzzy Search in Frontend Applications

These libraries provide approximate string matching capabilities, allowing users to find relevant results even with typos or partial matches. fuse.js is a modern, lightweight search engine that supports weighted scoring and nested object keys. fuzzy offers basic string matching utilities for simple use cases. fuzzy-search wraps matching logic to handle lists of objects efficiently. fuzzyset focuses on set-based lookups using Levenshtein distance, often serving as a legacy solution for unique item retrieval.

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
fuse.js19,296,03020,520417 kB214 个月前Apache-2.0
fuzzy7,768,643834-2910 年前-
fuzzy-search306,07522713 kB01 个月前ISC
fuzzyset24,4591,37735.6 kB15 年前see LICENSE.md

fuse.js vs fuzzy vs fuzzy-search vs fuzzyset: Architecture and Usage Compared

These four libraries solve the same core problem — finding strings that approximately match a query — but they differ significantly in algorithm design, API structure, and maintenance status. Understanding these differences helps you avoid performance bottlenecks and technical debt in your frontend architecture. Let's break down how they handle common search scenarios.

⚙️ Core Algorithm and Performance

fuse.js uses a bitwise algorithm optimized for speed and relevance scoring.

  • It calculates a score based on location, distance, and threshold settings.
  • Suitable for large lists because it avoids heavy string manipulation.
// fuse.js: Bitwise optimized search
import Fuse from 'fuse.js';

const options = { keys: ['title', 'author'], threshold: 0.3 };
const fuse = new Fuse(books, options);
const results = fuse.search('react guide');
// Returns scored results with metadata

fuzzy relies on basic Levenshtein distance calculations.

  • It compares every character to determine match quality.
  • Slower on large datasets but simple to understand.
// fuzzy: Basic Levenshtein match
import fuzzy from 'fuzzy';

const results = fuzzy.filter('react', ['reactjs', 'vue', 'angular']);
// Returns array of matched strings with original index

fuzzy-search wraps matching logic to handle object lists.

  • It iterates over defined keys and applies fuzzy matching internally.
  • Performance depends on the number of keys and list size.
// fuzzy-search: Object list searcher
import FuzzySearch from 'fuzzy-search';

const searcher = new FuzzySearch(books, ['title', 'author'], { sort: true });
const results = searcher.search('react guide');
// Returns filtered array of original objects

fuzzyset uses set-based logic with Levenshtein distance.

  • It builds a set of unique items and finds the best match.
  • Best for unique lookups rather than filtering large lists.
// fuzzyset: Set-based lookup
import FuzzySet from 'fuzzyset';

const set = FuzzySet(['reactjs', 'vuejs', 'angular']);
const result = set.get('react');
// Returns array of [score, item] tuples

🗂️ Data Structure and Configuration

The shape of your data dictates which tool fits best.

  • Use fuse.js when you have nested objects and need weighted keys.
  • Use fuzzy when you have plain string arrays and need simple filtering.
  • Use fuzzy-search when you have flat object arrays and want built-in sorting.
  • Use fuzzyset when you need unique item resolution from a fixed set.

💡 Tip: If you try to use fuzzy for nested objects, you will need to flatten data manually. That is a sign you actually need fuse.js or fuzzy-search.

⚠️ Maintenance and Deprecation Status

All four packages exist on npm, but their maintenance levels vary significantly.

  • fuse.js is actively maintained with regular updates and TypeScript support.
  • fuzzy is stable but receives infrequent updates; it is considered legacy.
  • fuzzy-search is maintained but has a smaller community than fuse.js.
  • fuzzyset is older and sees minimal activity; treat it as a legacy option.
// fuse.js: Modern ES module support
import Fuse from 'fuse.js'; // Works with bundlers out of the box

// fuzzyset: Older CommonJS style
const FuzzySet = require('fuzzyset'); // May require transpilation

🌐 Real-World Scenarios

Scenario 1: Documentation Search Bar

You need to search through hundreds of pages with titles, tags, and content.

  • ✅ Best choice: fuse.js
  • Why? Weighted keys allow you to prioritize titles over content.
const fuse = new Fuse(docs, {
  keys: [
    { name: 'title', weight: 0.8 },
    { name: 'content', weight: 0.2 }
  ]
});

Scenario 2: Command Palette Filter

You have a short list of command names and need instant filtering.

  • ✅ Best choice: fuzzy
  • Why? Low overhead and simple string matching is sufficient.
const commands = ['Open File', 'Save', 'Exit'];
const matches = fuzzy.filter('sav', commands);

Scenario 3: User Directory Table

You need to search a table of users by name, email, and role.

  • ✅ Best choice: fuzzy-search
  • Why? Built-in support for multiple keys and sorting results.
const searcher = new FuzzySearch(users, ['name', 'email', 'role']);
const results = searcher.search('john');

Scenario 4: Tag Normalization

You want to map user input to a fixed set of known tags.

  • ✅ Best choice: fuzzyset
  • Why? Designed to find the single best match from a unique set.
const tags = FuzzySet(['javascript', 'python', 'java']);
const match = tags.get('javscript'); // Matches 'javascript'

🌱 When Not to Use These

These utilities are great for client-side search, but consider alternatives when:

  • You need server-side search over millions of records: use Elasticsearch or Algolia.
  • You need full-text search with stemming: use a dedicated search engine.
  • Your list is static and small: native Array.filter() with includes() may suffice.

📌 Summary Table

PackageAlgorithmData ShapeConfigurableActive Maintenance
fuse.jsBitwiseObjects/Arrays✅ High✅ Yes
fuzzyLevenshteinStrings❌ Low⚠️ Limited
fuzzy-searchLevenshteinObjects✅ Medium⚠️ Limited
fuzzysetLevenshteinSets❌ Low❌ No

💡 Final Recommendation

Think in terms of scale and complexity:

  • Need robust features and active support? → Use fuse.js.
  • Need simple string matching for small lists? → Use fuzzy.
  • Need quick object search without config? → Use fuzzy-search.
  • Need unique set resolution? → Use fuzzyset (but consider fuse.js instead).

These tools help you add search functionality without building algorithms from scratch — which saves time and reduces bugs in your frontend code.

如何选择: fuse.js vs fuzzy vs fuzzy-search vs fuzzyset

  • fuse.js:

    Choose fuse.js for production-grade search features where configuration and accuracy matter. It supports weighted keys, threshold tuning, and nested data structures without heavy performance costs. This package is actively maintained and widely adopted in modern frontend stacks. It is the best fit for complex search bars, documentation sites, and data-rich dashboards.

  • fuzzy:

    Choose fuzzy when you need simple string-to-string matching without complex configuration. It works well for small utilities like command palettes or basic filter inputs where speed is critical and features are minimal. Avoid this for large datasets or when you need to search through object properties. It is a lightweight dependency for straightforward tasks.

  • fuzzy-search:

    Choose fuzzy-search if you need a ready-made searcher class for arrays of objects with minimal setup. It simplifies the process of defining searchable keys and returns matched items directly. This package is suitable for quick implementations where you do not need deep customization of the scoring algorithm. It balances ease of use with reasonable performance for medium-sized lists.

  • fuzzyset:

    Choose fuzzyset only for legacy systems or specific set-based lookup requirements where unique identification is key. Be aware that this package is older and may lack modern optimizations found in newer libraries. It is not recommended for new projects unless you have a specific dependency on its set logic. Evaluate fuse.js as a modern alternative before committing to this tool.

fuse.js的README

Fuse.js

Node.js CI Version Downloads code style: prettier Contributors License

Fuse.js is a lightweight, zero-dependency fuzzy-search library written in TypeScript. It works in the browser and on the server, and is designed for searching small-to-medium datasets on the client side where you can't rely on a dedicated search backend.

✨ What's New: Token Search

Multi-word fuzzy search with relevance ranking. Type "javascrpt paterns" and find "JavaScript Patterns" — typo tolerance, multiple words, and smart ranking all at once.

const fuse = new Fuse(docs, {
  useTokenSearch: true,
  keys: ['title', 'author', 'description']
})

fuse.search('javascrpt paterns')
// → [{ item: { title: 'JavaScript Patterns', ... } }]

See Token Search below for details.

Web Workers

Search large datasets without freezing the UI. FuseWorker splits your data across multiple Web Workers and searches in parallel — ~5x faster on 100K documents.

import { FuseWorker } from 'fuse.js/worker'

const fuse = new FuseWorker(docs, {
  keys: ['title', 'author', 'description']
})

const results = await fuse.search('query')
fuse.terminate()

Same options and results as Fuse — just async. Function-valued options (sortFn, getFn, keys[].getFn) aren't supported because functions can't be transferred to a worker; everything else carries over. See the Web Workers docs for the interactive demo and full API.

Installation

npm install fuse.js
yarn add fuse.js

Or include directly via CDN:

<script src="https://cdn.jsdelivr.net/npm/fuse.js/dist/fuse.min.mjs"></script>

Quick Start

import Fuse from 'fuse.js'

const books = [
  { title: "Old Man's War", author: 'John Scalzi' },
  { title: 'The Lock Artist', author: 'Steve Hamilton' },
  { title: 'HTML5', author: 'Remy Sharp' },
  { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' }
]

const fuse = new Fuse(books, {
  keys: ['title', 'author']
})

fuse.search('javscript')
// → [{ item: { title: 'JavaScript: The Good Parts', ... }, ... }]

Features

Fuzzy Search

The core of Fuse.js. Uses the Bitap algorithm for approximate string matching — handles typos, misspellings, and partial matches out of the box.

fuse.search('javscript')
// → [{ item: { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' } }]

Weighted Keys

Search across multiple fields with different importance levels. Title matches can rank higher than description matches.

const fuse = new Fuse(docs, {
  keys: [
    { name: 'title', weight: 2 },
    { name: 'description', weight: 1 }
  ]
})

Extended Search

Use operators for precise control: exact match (=), prefix (^), suffix (!), and more. Enable with useExtendedSearch: true.

const fuse = new Fuse(list, {
  useExtendedSearch: true,
  keys: ['title']
})

fuse.search('=exact match')   // exact match
fuse.search('^prefix')        // starts with
fuse.search('!term')          // does not include

Token Search

Splits multi-word queries into individual terms, fuzzy-matches each independently, and ranks results using BM25-style IDF weighting. Enable with useTokenSearch: true.

const fuse = new Fuse(docs, {
  useTokenSearch: true,
  keys: ['title', 'body']
})

fuse.search('express midleware rout')
// Finds "Express Middleware" and "Express Routing Guide" despite typos
  • Typo tolerance per word — each term is fuzzy-matched independently
  • Relevance ranking — rare terms are weighted higher than common ones
  • Word order independent — "patterns javascript" and "javascript patterns" return identical results
  • No query length limit — long multi-word queries work naturally since each term is searched separately
  • AND or OR — tokenMatch: 'all' returns only records matching every word (filtering); the default 'any' matches any word
  • Custom tokenizer — pass a regex or function via tokenize for tokens with internal punctuation (node.js, c++), or use Intl.Segmenter for CJK / Thai word segmentation. Unicode-aware by default

Available in the full build. See the Token Search docs for details and performance benchmarks.

Logical Search

Combine conditions with $and and $or for complex queries. Available in the full build.

fuse.search({
  $and: [
    { title: 'javascript' },
    { author: 'crockford' }
  ]
})

Match Highlighting

Get character-level match indices for highlighting search results in your UI.

const fuse = new Fuse(list, {
  includeMatches: true,
  keys: ['title']
})

const result = fuse.search('javscript')
// result[0].matches[0].indices → [[0, 9]]

Single String Matching

Use Fuse.match() to fuzzy-match a pattern against a single string without creating an index. Useful for one-off comparisons or custom filtering.

const result = Fuse.match('javscript', 'JavaScript: The Good Parts')
// → { isMatch: true, score: 0.04, indices: [[0, 9]] }

Fuse.match() does not support useTokenSearch — token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison can't provide. Passing useTokenSearch: true throws an explicit error. Use new Fuse(docs, { useTokenSearch: true }).search(query) for token-search behavior.

Dynamic Collections

Add and remove documents from a live index without rebuilding.

fuse.add({ title: 'New Book', author: 'New Author' })
fuse.remove((doc) => doc.title === 'Old Book')

Builds

Fuse.js ships in two variants:

BuildIncludesMin + gzip
FullFuzzy + Extended + Logical + Token search~8.6 kB
BasicFuzzy search only~6.8 kB

Use the basic build if you only need fuzzy search and want the smallest bundle size.

Documentation

For the full API reference, configuration options, scoring theory, and interactive demos, visit fusejs.io.

Official ports

  • fuse-swift: Swift port for iOS, macOS, tvOS, watchOS, visionOS, and Linux. Byte-equivalent results, idiomatic Swift API, syncs with each upstream release. Currently in 2.0.0-rc.1.

Supporting Fuse.js

Develop

See DEVELOPERS.md for setup, scripts, and project structure.

Contribute

See CONTRIBUTING.md for guidelines on issues and pull requests.