Fuse.js 模糊匹配库用法总结

目录

  • Fuse.js 模糊匹配库用法总结
    • 简介
    • 安装与引入
    • 基本用法
      • 1. 对字符串数组进行模糊搜索
      • 2. 对对象数组进行模糊搜索
    • 主要配置项(Options)
    • 进阶用法
      • 1. 权重搜索(Weighted Search)
      • 2. 嵌套搜索(Nested Search)
      • 3. 扩展搜索(Extended Search)
      • 4. 逻辑查询(Logical Query Operators)
      • 5. 索引优化(Indexing)
      • 6. 全局配置(Global Config)
    • 主要方法
    • 参考链接

Fuse.js 模糊匹配库用法总结

简介

Fuse.js 是一个强大的 JavaScript 模糊搜索库,适用于在前端或 Node.js 项目中对数组、对象等数据结构进行高效的模糊查找。


安装与引入

npm install fuse.js
import Fuse from 'fuse.js'

基本用法

1. 对字符串数组进行模糊搜索

const list = ['Apple', 'Orange', 'Banana']
const fuse = new Fuse(list)
const result = fuse.search('appl')
console.log(result)

2. 对对象数组进行模糊搜索

const books = [
  { title: 'Old Man and the Sea', author: 'Hemingway' },
  { title: 'War and Peace', author: 'Tolstoy' }
]
const options = {
  keys: ['title', 'author']
}
const fuse = new Fuse(books, options)
const result = fuse.search('war')
console.log(result)

主要配置项(Options)

选项 类型 默认值 说明
isCaseSensitive boolean false 是否区分大小写
ignoreDiacritics boolean false 是否忽略变音符(重音)
includeScore boolean false 结果中是否包含匹配分数
includeMatches boolean false 结果中是否包含匹配字符索引
minMatchCharLength number 1 最小匹配字符长度
shouldSort boolean true 是否按分数排序
findAllMatches boolean false 是否查找所有匹配
keys Array [] 要搜索的字段数组,支持嵌套、权重
threshold number 0.6 匹配阈值,0.0 完全匹配,1.0 匹配所有
location number 0 期望匹配出现在文本中的大致位置
distance number 100 匹配位置的容忍度
ignoreLocation boolean false 是否忽略 location 和 distance
useExtendedSearch boolean false 是否启用扩展搜索语法
getFn Function - 自定义获取对象属性的方法
sortFn Function - 自定义排序方法
ignoreFieldNorm boolean false 是否忽略字段长度归一化
fieldNormWeight number 1 字段长度归一化权重

详细配置说明见官方文档。


进阶用法

1. 权重搜索(Weighted Search)

为不同字段分配权重,提高某些字段的匹配优先级:

const options = {
  keys: [
    'title',
    { name: 'author', weight: 2 }
  ]
}

2. 嵌套搜索(Nested Search)

支持通过点语法或数组语法搜索嵌套对象:

const options = {
  keys: ['author.firstName', 'author.lastName']
}

3. 扩展搜索(Extended Search)

支持更复杂的查询语法:

  • jscript:模糊匹配
  • =scheme:精确匹配
  • 'python:包含匹配
  • !ruby:排除精确匹配
  • ^java:前缀匹配
  • .js$:后缀匹配

示例:

fuse.search("'python !ruby")

更多用法见官方示例。

4. 逻辑查询(Logical Query Operators)

支持 $and$or 逻辑操作:

const result = fuse.search({
  $and: [
    { author: 'Hemingway' },
    { title: 'Old' }
  ]
})

详细用法见逻辑查询文档。

5. 索引优化(Indexing)

对于大数据量,可以预先生成索引,加快实例化速度:

const myIndex = Fuse.createIndex(['title', 'author'], books)
const fuse = new Fuse(books, options, myIndex)

索引也可以序列化和反序列化,便于持久化和加载。

详细用法见索引文档。

6. 全局配置(Global Config)

可以通过 Fuse.config 设置全局默认选项:

Fuse.config.getFn = (obj, path) => {
  // 自定义获取对象属性的方法
}

详细用法见全局配置文档。


主要方法

  • search(pattern, options):执行搜索,支持字符串、路径、扩展查询、逻辑查询
  • setCollection(newCollection):替换数据集合
  • add(doc):添加新文档
  • remove(predicate):移除符合条件的文档
  • removeAt(index):移除指定索引的文档
  • getIndex():获取当前索引对象

详细方法见官方方法文档。


参考链接

  • 配置项 Options
  • 方法 Methods
  • 索引 Indexing
  • 逻辑查询 Query
  • 官方示例 Examples
  • 全局配置 Config

Fuse.js 提供了灵活且强大的模糊搜索能力,适用于绝大多数前端和 Node.js 项目的搜索需求。

你可能感兴趣的:(javascript,开发语言,ecmascript)