fuse.js vs fuzzy-search vs fuzzyset
前端模糊搜索方案选型:Fuse.js vs Fuzzy-Search vs Fuzzyset
fuse.jsfuzzy-searchfuzzyset类似的npm包:

前端模糊搜索方案选型:Fuse.js vs Fuzzy-Search vs Fuzzyset

fuse.js、fuzzy-search 和 fuzzyset 都是用于在 JavaScript 中实现模糊搜索功能的库,但它们的侧重点和适用场景有所不同。fuse.js 是目前最流行的选择,支持对复杂对象数组进行加权搜索,配置灵活且维护活跃。fuzzy-search 提供了一个更简单的接口,适合快速实现基础的字符串匹配。fuzzyset 则专注于字符串集合的成员资格测试和最近邻查找,更适合处理唯一字符串集而非对象列表。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
fuse.js20,797,44920,535417 kB274 个月前Apache-2.0
fuzzy-search301,12822713 kB02 个月前ISC
fuzzyset29,1471,37835.6 kB15 年前see LICENSE.md

前端模糊搜索方案选型:Fuse.js vs Fuzzy-Search vs Fuzzyset

在前端开发中,实现一个好用的搜索框往往需要模糊匹配能力。fuse.js、fuzzy-search 和 fuzzyset 是三个常见的选择,但它们的底层逻辑和适用场景差异很大。本文将从架构角度对比这三者,帮助你在实际工程中做出正确选择。

🔍 核心匹配机制:对象搜索 vs 集合匹配

fuse.js 专为搜索对象数组设计。它允许你指定对象中的哪些字段参与搜索,并为不同字段设置权重。

// fuse.js: 搜索对象数组
const books = [
  { title: "The Hobbit", author: "J.R.R. Tolkien" },
  { title: "Harry Potter", author: "J.K. Rowling" }
];
const fuse = new Fuse(books, { keys: ["title", "author"] });
const results = fuse.search("potter");

fuzzy-search 同样针对对象数组,但配置相对简单,通常用于快速集成。

// fuzzy-search: 搜索对象数组
const FuzzySearch = require('fuzzy-search');
const books = [
  { title: "The Hobbit", author: "J.R.R. Tolkien" },
  { title: "Harry Potter", author: "J.K. Rowling" }
];
const searcher = new FuzzySearch(books, ["title", "author"]);
const results = searcher.search("potter");

fuzzyset 的核心是字符串集合。它主要用于判断输入字符串是否接近集合中的某个唯一字符串,而不是搜索对象列表。

// fuzzyset: 字符串集合匹配
const FuzzySet = require('fuzzyset');
const set = new FuzzySet(["The Hobbit", "Harry Potter"]);
const results = set.get("potter"); 
// 返回匹配度数组,如 [[0.8, "Harry Potter"]]

⚙️ 配置灵活性:权重与阈值

fuse.js 提供极高的配置自由度。你可以为每个键设置权重,调整匹配阈值,甚至包含匹配的索引位置。

// fuse.js: 高级配置
const fuse = new Fuse(books, {
  keys: [{ name: "title", weight: 0.8 }, { name: "author", weight: 0.2 }],
  threshold: 0.3,
  includeMatches: true
});

fuzzy-search 的配置选项较少,主要集中在大小写敏感和结果限制上,适合不需要精细调优的场景。

// fuzzy-search: 基础配置
const searcher = new FuzzySearch(books, ["title"], {
  caseSensitive: false,
  limit: 10
});

fuzzyset 专注于匹配度阈值,用于过滤低质量的字符串匹配结果。

// fuzzyset: 阈值过滤
const results = set.get("potter", 0.5); 
// 只返回匹配度大于 0.5 的结果

📦 数据结构支持:嵌套属性 vs 平面字符串

fuse.js 支持深度嵌套的对象属性搜索,这对于复杂的数据模型非常有用。

// fuse.js: 嵌套属性
const users = [{ profile: { name: "Alice" } }];
const fuse = new Fuse(users, { keys: ["profile.name"] });

fuzzy-search 通常只支持平面对象的键,处理嵌套数据需要预先 flattening 数据。

// fuzzy-search: 平面键
const users = [{ profile: { name: "Alice" } }];
// 需要手动处理嵌套,库本身不直接支持 "profile.name" 语法
const searcher = new FuzzySearch(users, ["profile"]); 

fuzzyset 仅处理字符串数组,不支持对象属性。

// fuzzyset: 仅字符串
const names = ["Alice", "Bob"];
const set = new FuzzySet(names);

🛠️ 维护状态与社区生态

fuse.js 是目前维护最活跃的库,定期更新以修复漏洞和优化性能,拥有庞大的社区支持。

// fuse.js: 现代 ES 模块导入
import Fuse from 'fuse.js';

fuzzy-search 更新频率较低,功能稳定但缺乏新特性,适合不需要长期维护的小型项目。

// fuzzy-search: 传统 CommonJS 导入
const FuzzySearch = require('fuzzy-search');

fuzzyset 需要注意,npm 上的 fuzzyset 包可能不如 fuzzyset.js 活跃。如果在新项目中使用,建议确认其维护状态或考虑替代方案。

// fuzzyset: 检查包状态
const FuzzySet = require('fuzzyset');
// 注意:社区常推荐使用 fuzzyset.js 作为更 maintained 的版本

🌱 共同点:核心相似之处

尽管三者有差异,但它们都解决了模糊匹配的基本问题。

1. 🔤 基于字符的相似度算法

  • 都使用某种形式的编辑距离或位运算算法来计算相似度。
  • 都能处理拼写错误。
// 三者都能处理 "harry potter" 匹配 "Harry Potter"
// fuse.js
fuse.search("harry potter");
// fuzzy-search
searcher.search("harry potter");
// fuzzyset
set.get("harry potter");

2. ⚡ 客户端执行

  • 都在浏览器端运行,无需后端支持。
  • 适合小型数据集(通常 < 10,000 条)。
// 都在前端初始化
const instance = new Library(data);

3. 🔙 返回匹配结果

  • 都返回匹配到的项及其相关度信息。
// 都返回结果列表
// fuse.js: [{ item, refIndex, score }]
// fuzzy-search: [item, item...]
// fuzzyset: [[score, string], ...]

📊 总结:关键差异对比

特性fuse.jsfuzzy-searchfuzzyset
主要用途复杂对象列表搜索简单对象列表搜索字符串集合匹配
嵌套支持✅ 支持嵌套键❌ 通常不支持❌ 仅字符串
权重配置✅ 精细权重控制⚠️ 有限支持❌ 无
维护状态🟢 活跃🟡 稳定但更新少🟡 需注意版本
返回格式详细元数据简单数组分数与字符串对

💡 架构师建议

fuse.js 是大多数前端搜索场景的首选 🏆。它的 API 设计现代,支持 TypeScript,并且能够处理复杂的业务数据模型。如果你的项目需要高质量的搜索体验,不要犹豫,直接使用它。

fuzzy-search 适合那些只需要“能跑就行”的场景 🏃。比如内部工具的简单过滤,或者数据量极小的情况。它的配置少,上手快,但扩展性有限。

fuzzyset 是一个特殊工具 🛠️。当你需要实现“猜你想搜”或者标签自动补全,且数据源是一组唯一字符串时,它非常高效。但不要试图用它来搜索商品列表或用户信息。

最后提醒:在选择 fuzzyset 时,请仔细检查 npm 上的具体包名,社区中 fuzzyset.js 往往比 fuzzyset 维护得更好。对于生产环境,fuse.js 是最安全、最可靠的选择。

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

  • fuse.js:

    选择 fuse.js 如果你需要搜索包含多个字段的商品列表、用户数据或文档。它支持权重配置、嵌套属性搜索和高精度匹配,适合对搜索体验要求较高的生产环境项目。

  • fuzzy-search:

    选择 fuzzy-search 如果你的需求非常简单,只需要在少量数据中进行基本的关键词匹配,且不希望引入过多的配置选项。它适合小型工具或原型开发。

  • fuzzyset:

    选择 fuzzyset 如果你主要需要判断一个字符串是否存在于某个集合中,或者寻找与输入最接近的唯一字符串。它不适合搜索包含多个字段的结构化对象列表。

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.