fuse.js vs lunr vs flexsearch vs search-index vs elasticlunr
前端全文搜索库选型指南:性能、功能与架构权衡
fuse.jslunrflexsearchsearch-indexelasticlunr类似的npm包:

前端全文搜索库选型指南:性能、功能与架构权衡

elasticlunr、flexsearch、fuse.js、lunr 和 search-index 都是用于在浏览器或 Node.js 环境中实现全文搜索的 JavaScript 库。它们的核心目标是将数据索引化,以便快速检索,但实现策略截然不同。lunr 是经典的轻量级倒排索引库,适合静态数据;elasticlunr 是其分支,增加了对字段权重和布尔查询的支持;flexsearch 专注于极致的搜索速度和内存效率,支持部分匹配;fuse.js 则专注于模糊匹配(容错搜索),适合处理用户拼写错误;search-index 是一个更通用的数据库式索引,支持复杂的布尔逻辑和持久化存储。选择哪个库取决于你的数据量、是否需要模糊搜索、对查询复杂度的要求以及是否需要实时更新索引。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
fuse.js20,262,76720,534417 kB264 个月前Apache-2.0
lunr9,480,4009,202-1306 年前MIT
flexsearch1,288,66613,8242.33 MB401 年前Apache-2.0
search-index54,1371,421722 kB113 个月前MIT
elasticlunr26,6162,064-7710 年前MIT

前端全文搜索库深度对比:架构、性能与实战选型

在前端架构中,实现高效的全文搜索往往意味着要在“用户体验”、“内存占用”和“功能复杂度”之间做权衡。elasticlunr、flexsearch、fuse.js、lunr 和 search-index 代表了五种不同的解决思路。有的追求极致速度,有的专注模糊匹配,有的则提供数据库级的查询能力。本文将深入剖析它们的核心机制,通过代码实战展示差异,帮助你做出最符合工程场景的决策。

⚙️ 核心机制:倒排索引 vs 模糊匹配

理解这些库的第一步是看清它们如何存储和查找数据。

lunr 和 elasticlunr 基于经典的倒排索引(Inverted Index)。它们将文本拆分为词元(tokens),建立“词 -> 文档 ID

如何选择: fuse.js vs lunr vs flexsearch vs search-index vs elasticlunr

  • fuse.js:

    如果你的应用场景高度依赖容错能力,例如用户经常输入错别字、需要搜索人名或非结构化文本,选择 fuse.js。它不建立传统的倒排索引,而是基于位运算进行模糊匹配,因此在大数据量下性能不如其他库,但在小数据量下的用户体验极佳。

  • lunr:

    对于大多数标准的静态网站搜索需求(如文档站、博客),若只需简单的全文检索且希望依赖稳定、成熟的社区生态,选择 lunr。它 API 简单、文档完善,是构建静态站点搜索的默认首选,但缺乏原生模糊搜索和复杂的字段过滤功能。

  • flexsearch:

    当你的首要目标是极致的搜索性能和低内存占用,且需要支持部分匹配(如输入一半单词即出结果)时,选择 flexsearch。它非常适合大型数据集的前端实时搜索,但其查询语法相对独特,且不支持复杂的模糊匹配算法。

  • search-index:

    当你需要在 Node.js 服务端或本地环境中构建一个支持复杂布尔查询、分面搜索(faceting)、且需要持久化存储和实时更新的大型索引时,选择 search-index。它更像是一个嵌入式的搜索引擎数据库,适合构建复杂的企业级搜索应用,而非简单的前端静态搜索。

  • elasticlunr:

    如果你需要比原生 lunr 更强大的查询能力(如多字段加权、布尔逻辑),且数据是静态的或很少变化,选择 elasticlunr。它在 lunr 的基础上扩展了类似 Elasticsearch 的查询语法,适合文档类应用的静态搜索,但需注意其维护频率低于主库。

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.