Fuse.js——用于JavaScript中数据的模糊搜索

介绍

Fuse.js是一个功能强大、轻量级的模糊搜索库,没有依赖关系。一般来说,模糊搜索(更正式地称为近似字符串匹配)是一种寻找近似等于给定模式(而不是精确地)的字符串的技术。


Fuse.js——用于JavaScript中数据的模糊搜索


Github

https://github.com/krisk/fuse

使用场景

当你需要对小到中等大小的数据集进行客户端模糊搜索时。

基本使用

// 1. 要搜索的数据列表 const books = [   {     title: "Old Man's War",     author: {       firstName: 'John',       lastName: 'Scalzi'     }   },   {     title: 'The Lock Artist',     author: {       firstName: 'Steve',       lastName: 'Hamilton'     }   } ]  // 2. 设置fuse实例 const fuse = new Fuse(books, {   keys: ['title', 'author.firstName'] })  // 3. 搜索! fuse.search('jon')  // 输出: // [ //   { //     item: { //       title: "Old Man's War", //       author: { //         firstName: 'John', //         lastName: 'Scalzi' //       } //     }, //     refIndex: 0 //   } // ]

安装

  • NPM
npm install --save fuse.js
  • Yarn
yarn add fuse.js
  • 引入

ES6模块

import Fuse from 'fuse.js'

CommonJS:

const Fuse = require('fuse.js')

使用范例

  • 字符串数组搜索
["Old Man's War", "The Lock Artist"]  const options = {   includeScore: true }  const fuse = new Fuse(list, options)  const result = fuse.search('od man')
  • 对象数组搜索
[   {     "title": "Old Man's War",     "author": "John Scalzi",     "tags": ["fiction"]   },   {     "title": "The Lock Artist",     "author": "Steve",     "tags": ["thriller"]   } ]
const options = {   includeScore: true,   // 在数组中搜索author` and in `tags`两个字段   keys: ['author', 'tags'] }  const fuse = new Fuse(list, options)  const result = fuse.search('tion')
  • 嵌套搜索
[   {     "title": "Old Man's War",     "author": {       "name": "John Scalzi",       "tags": [         {           "value": "American"         }       ]     }   },   {     "title": "The Lock Artist",     "author": {       "name": "Steve Hamilton",       "tags": [         {           "value": "English"         }       ]     }   } ]
const options = {   includeScore: true,   // //等价于“keys:[['author','tags','value']]   keys: ['author.tags.value'] }  const fuse = new Fuse(list, options)  const result = fuse.search('engsh')
  • 加权检索
[   {     "title": "Old Man's War fiction",     "author": "John X",     "tags": ["war"]   },   {     "title": "Right Ho Jeeves",     "author": "P.D. Mans",     "tags": ["fiction", "war"]   } ]  const options = {   includeScore: true,   keys: [     {       name: 'title',       weight: 0.3     },     {       name: 'author',       weight: 0.7     }   ] }  // 创建Fuse的新实例 const fuse = new Fuse(books, options)  const result = fuse.search('Man')
  • 默认权重

如果未提供权重,则默认为1。在下面的示例中,author的权重为2,但title的权重为1。

const fuse = new Fuse(books, {   keys: [     'title', // 将分配“权重”1     {       name: 'author',       weight: 2     }   ] })
  • 扩展搜索

这其中包括一些特殊符号进行的搜索方式,详情可看文档

总结

Fuse.js为我们在客户端提供了很方便的数据匹配方式,相较于手动去处理这些数据。Fuse显得更加方便!

您可能还会对下面的文章感兴趣: