fuse.js、fuzzy-search 和 fuzzyset 都是用于在 JavaScript 中实现模糊搜索功能的库,但它们的侧重点和适用场景有所不同。fuse.js 是目前最流行的选择,支持对复杂对象数组进行加权搜索,配置灵活且维护活跃。fuzzy-search 提供了一个更简单的接口,适合快速实现基础的字符串匹配。fuzzyset 则专注于字符串集合的成员资格测试和最近邻查找,更适合处理唯一字符串集而非对象列表。
在前端开发中,实现一个好用的搜索框往往需要模糊匹配能力。fuse.js、fuzzy-search 和 fuzzyset 是三个常见的选择,但它们的底层逻辑和适用场景差异很大。本文将从架构角度对比这三者,帮助你在实际工程中做出正确选择。
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 的结果
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 的版本
尽管三者有差异,但它们都解决了模糊匹配的基本问题。
// 三者都能处理 "harry potter" 匹配 "Harry Potter"
// fuse.js
fuse.search("harry potter");
// fuzzy-search
searcher.search("harry potter");
// fuzzyset
set.get("harry potter");
// 都在前端初始化
const instance = new Library(data);
// 都返回结果列表
// fuse.js: [{ item, refIndex, score }]
// fuzzy-search: [item, item...]
// fuzzyset: [[score, string], ...]
| 特性 | fuse.js | fuzzy-search | fuzzyset |
|---|---|---|---|
| 主要用途 | 复杂对象列表搜索 | 简单对象列表搜索 | 字符串集合匹配 |
| 嵌套支持 | ✅ 支持嵌套键 | ❌ 通常不支持 | ❌ 仅字符串 |
| 权重配置 | ✅ 精细权重控制 | ⚠️ 有限支持 | ❌ 无 |
| 维护状态 | 🟢 活跃 | 🟡 稳定但更新少 | 🟡 需注意版本 |
| 返回格式 | 详细元数据 | 简单数组 | 分数与字符串对 |
fuse.js 是大多数前端搜索场景的首选 🏆。它的 API 设计现代,支持 TypeScript,并且能够处理复杂的业务数据模型。如果你的项目需要高质量的搜索体验,不要犹豫,直接使用它。
fuzzy-search 适合那些只需要“能跑就行”的场景 🏃。比如内部工具的简单过滤,或者数据量极小的情况。它的配置少,上手快,但扩展性有限。
fuzzyset 是一个特殊工具 🛠️。当你需要实现“猜你想搜”或者标签自动补全,且数据源是一组唯一字符串时,它非常高效。但不要试图用它来搜索商品列表或用户信息。
最后提醒:在选择 fuzzyset 时,请仔细检查 npm 上的具体包名,社区中 fuzzyset.js 往往比 fuzzyset 维护得更好。对于生产环境,fuse.js 是最安全、最可靠的选择。
选择 fuse.js 如果你需要搜索包含多个字段的商品列表、用户数据或文档。它支持权重配置、嵌套属性搜索和高精度匹配,适合对搜索体验要求较高的生产环境项目。
选择 fuzzy-search 如果你的需求非常简单,只需要在少量数据中进行基本的关键词匹配,且不希望引入过多的配置选项。它适合小型工具或原型开发。
选择 fuzzyset 如果你主要需要判断一个字符串是否存在于某个集合中,或者寻找与输入最接近的唯一字符串。它不适合搜索包含多个字段的结构化对象列表。
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.