fuse.js、fuzzy-search、fuzzysearch 和 fuzzyset.js 都是用于在 JavaScript 应用中实现模糊搜索功能的 npm 包,适用于前端或 Node.js 环境。它们通过不同的算法(如 Levenshtein 距离、子序列匹配或 n-gram 索引)来匹配用户输入与数据项之间的近似关系,常用于搜索框、自动补全、过滤列表等交互场景。这些库在功能完整性、性能特征、API 设计和维护状态上存在显著差异,开发者需根据具体需求选择合适方案。
在前端开发中,实现快速、准确的模糊搜索是提升用户体验的关键环节。本文将深入比较四个主流的 JavaScript 模糊搜索库 —— fuse.js、fuzzy-search、fuzzysearch 和 fuzzyset.js —— 从核心算法、API 设计、功能支持和适用场景出发,帮助你做出合理的技术选型。
不同库采用的模糊匹配策略直接影响搜索结果的相关性和性能表现。
fuse.js 使用改进版的 Bitap 算法(基于 Levenshtein 距离),支持关键词权重、字段优先级、位置敏感度等高级配置。它不仅能匹配子字符串,还能处理拼写错误,并通过打分机制对结果排序。
// fuse.js 示例:带权重的多字段搜索
const list = [
{ title: 'Old Man\'s War', author: 'John Scalzi' },
{ title: 'The Lock Artist', author: 'Steve Hamilton' }
];
const options = {
keys: [
{ name: 'title', weight: 0.7 },
{ name: 'author', weight: 0.3 }
]
};
const fuse = new Fuse(list, options);
const result = fuse.search('old'); // 返回按相关性排序的结果
fuzzy-search 同样基于 Levenshtein 距离,但仅支持对象数组的字段匹配,不提供打分或排序能力。它会返回所有距离小于阈值的项,但无法区分“更相关”的结果。
// fuzzy-search 示例
const FuzzySearch = require('fuzzy-search');
const searcher = new FuzzySearch(
[{ name: 'Alice' }, { name: 'Bob' }],
['name']
);
const results = searcher.search('alic'); // 返回匹配项数组,无排序
fuzzysearch 是最轻量的方案,仅实现简单的子序列匹配(subsequence matching)。它不计算编辑距离,而是检查查询字符串是否作为子序列出现在目标中。例如 'abc' 能匹配 'aXbYcZ',但无法容忍字符替换或插入错误。
// fuzzysearch 示例
const fuzzysearch = require('fuzzysearch');
console.log(fuzzysearch('mt', 'match')); // true
console.log(fuzzysearch('mxt', 'match')); // false(不支持替换)
fuzzyset.js 采用完全不同的思路:它构建一个基于 n-gram 的倒排索引,在预处理阶段生成所有可能的变体,从而实现近似词的快速查找。但它不支持对象字段搜索,仅适用于纯字符串集合。
// fuzzyset.js 示例
const FuzzySet = require('fuzzyset.js');
const fz = FuzzySet(['color', 'flavor', 'behavior']);
console.log(fz.get('colour')); // [['color', 0.8]] — 返回相似项及置信度
⚠️ 注意:截至 2024 年,
fuzzyset.js的 npm 页面已明确标注 “This package is no longer maintained”(该包不再维护)。虽然仍可使用,但新项目应谨慎评估其长期支持风险。
fuse.js:原生支持对象数组,可指定多个字段进行搜索,并为每个字段设置权重。fuzzy-search:仅支持对象数组,需预先声明要搜索的字段名。fuzzysearch:仅接受两个字符串参数,适合简单文本匹配。fuzzyset.js:仅接受字符串数组,返回最接近的匹配项及其相似度分数。只有 fuse.js 和 fuzzyset.js 提供相关性打分:
fuse.js 返回包含 item 和 refIndex 的结果数组,默认按分数升序(可通过 shouldSort: false 关闭)。fuzzyset.js 返回 [match, score] 数组,score 越高表示越相似。fuzzy-search 和 fuzzysearch 仅返回布尔值或原始匹配项,无排序能力。fuse.js 支持索引缓存,适合静态数据集的重复查询;也提供 Fuse.createIndex() 手动构建索引以提升性能。fuzzyset.js 在初始化时构建完整索引,查询极快,但内存占用较高。fuzzysearch 无预处理开销,每次调用都是 O(n) 扫描,适合小规模或一次性匹配。fuzzy-search 每次搜索都遍历整个列表,无优化机制。✅ 首选 fuse.js
理由:需要根据商品名称、描述、标签等多个字段综合打分,且用户可能输入错别字(如 “iphnoe” → “iPhone”)。fuse.js 的权重配置和排序能力完美匹配此需求。
const products = [
{ name: 'iPhone 15', brand: 'Apple', tags: ['phone', 'ios'] },
{ name: 'Galaxy S24', brand: 'Samsung', tags: ['phone', 'android'] }
];
const fuse = new Fuse(products, {
keys: ['name', 'brand', 'tags'],
threshold: 0.3, // 允许一定拼写错误
includeScore: true
});
fuse.search('iphnoe'); // 返回高相关性结果
✅ 首选 fuzzysearch
理由:数据量小(通常 < 300 项),只需判断输入是否为有效前缀或子序列,无需复杂打分。fuzzysearch 体积小(< 1KB)、零依赖,集成成本最低。
const countries = ['China', 'United States', 'Germany'];
const input = 'ger';
const filtered = countries.filter(c => fuzzysearch(input.toLowerCase(), c.toLowerCase()));
✅ 可考虑 fuzzyset.js(但需注意维护状态)
理由:若需从大量日志消息中找出与“error”、“warn”等关键词近似的条目,fuzzyset.js 的 n-gram 索引能快速返回候选。但鉴于其已停止维护,建议评估 fuse.js 替代方案。
✅ 可选 fuzzy-search
理由:当数据结构为 { name: string } 且无需排序时,fuzzy-search 提供了比手写 filter + includes 更强的容错能力(支持 Levenshtein 距离 ≤1)。
const contacts = [{ name: '张伟' }, { name: '李娜' }];
const searcher = new FuzzySearch(contacts, ['name']);
searcher.search('张威'); // 可能匹配“张伟”
| 特性 | fuse.js | fuzzy-search | fuzzysearch | fuzzyset.js |
|---|---|---|---|---|
| 维护状态 | ✅ 活跃 | ✅ 活跃 | ✅ 活跃 | ❌ 已停止维护 |
| 支持对象字段 | ✅ | ✅ | ❌ | ❌ |
| 支持打分排序 | ✅ | ❌ | ❌ | ✅ |
| 拼写容错能力 | 高(可调阈值) | 低(固定距离≤1) | 无(仅子序列) | 中(基于 n-gram) |
| 适合数据规模 | 中到大 | 小到中 | 小 | 中(需预建索引) |
| Bundle 体积 | 较大 | 中等 | 极小 | 中等 |
fuse.js:它功能全面、文档完善、社区活跃,能覆盖从简单到复杂的各种模糊搜索需求。fuzzysearch:当你只需要一个 < 1KB 的子序列匹配函数,且不关心拼写错误时。fuzzyset.js:尽管其算法独特,但缺乏维护意味着潜在的安全和兼容性风险。fuzzy-search 作为中间选项:仅在你明确不需要排序、且数据结构简单时考虑。记住:模糊搜索的核心不是“能否找到”,而是“能否把最相关的放在最前面”。在这方面,fuse.js 依然是前端领域的事实标准。
选择 fuse.js 如果你需要一个功能全面、活跃维护的模糊搜索解决方案,支持对象字段权重配置、结果打分排序、可调阈值的拼写容错,以及良好的性能优化(如索引缓存)。它适用于大多数现代 Web 应用中的复杂搜索场景,如电商产品搜索或多字段内容过滤。
选择 fuzzy-search 如果你的数据是简单的对象数组,只需基于少数字段进行基本的 Levenshtein 距离匹配(默认容忍距离 ≤1),且不需要结果排序或高级配置。它比手写过滤更健壮,但功能远不如 fuse.js 灵活,适合轻量级内部工具或小型应用。
选择 fuzzysearch 如果你只需要极简的子序列匹配(例如判断 "abc" 是否作为子序列出现在 "aXbYcZ" 中),且数据量小、无拼写容错需求。它的优势在于体积超小(<1KB)、零依赖、API 极简,非常适合下拉菜单过滤或一次性文本匹配场景。
不要在新项目中选择 fuzzyset.js,因为其官方已明确标注“不再维护”。尽管它基于 n-gram 索引提供独特的近似词查找能力,但缺乏安全更新和兼容性保障。如需类似功能,建议使用 fuse.js 替代。
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.
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.
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.
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>
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', ... }, ... }]
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' } }]
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 }
]
})
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
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
"patterns javascript" and "javascript patterns" return identical resultstokenMatch: 'all' returns only records matching every word (filtering); the default 'any' matches any wordtokenize for tokens with internal punctuation (node.js, c++), or use Intl.Segmenter for CJK / Thai word segmentation. Unicode-aware by defaultAvailable in the full build. See the Token Search docs for details and performance benchmarks.
Combine conditions with $and and $or for complex queries. Available in the full build.
fuse.search({
$and: [
{ title: 'javascript' },
{ author: 'crockford' }
]
})
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]]
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.
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')
Fuse.js ships in two variants:
| Build | Includes | Min + gzip |
|---|---|---|
| Full | Fuzzy + Extended + Logical + Token search | ~8.6 kB |
| Basic | Fuzzy search only | ~6.8 kB |
Use the basic build if you only need fuzzy search and want the smallest bundle size.
For the full API reference, configuration options, scoring theory, and interactive demos, visit fusejs.io.
See DEVELOPERS.md for setup, scripts, and project structure.
See CONTRIBUTING.md for guidelines on issues and pull requests.