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 install --save fuse.js
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显得更加方便!

展开阅读全文

页面更新:2024-05-01

标签:模糊   数据   嵌套   权重   数组   字段   近似   示例   字符串   范例   功能强大   精确   客户端   实例   方式   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top