模糊搜索
要达到的目标是用户不需要关心搜索系统的结构,任意输入一串字符或者数字,只要搜索范围中包含该信息,通过该方法就能够找出该信息包含在哪个表,哪个字段里,或者具体哪个位置,进而可以进行更为详细的查询。
系统允许被搜索信息和搜索提问之间存在一定的差异,这种差异就是“模糊”在搜索中的含义。例如,查找名字Smith时,就会找出与之相似的Smithe, Smythe, Smyth, Smitt等。
需求
业务要求用户输入Query为“手机”时,返回所有包含“手机”关键词的在线词。
这里面我们介绍一下go语言的“Fuzzy Search”模糊匹配库的用法,该库灵活的对字符串进行配置,有助于轻量级用户快速过滤数据。
项目地址:https://github.com/lithammer/fuzzysearch
安装golang.org/x包
mkdir -p $GOPATH/src/golang.org/x
cd $GOPATH/src/golang.org/x
git clone https://github.com/golang/sys.git
git clone https://github.com/golang/net.git
git clone https://github.com/golang/text.git
git clone https://github.com/golang/lint.git
git clone https://github.com/golang/tools.git
git clone https://github.com/golang/crypto.git
go.mod
module fuzzySearch
go 1.13
require (
golang.org/x/text v0.3.2
github.com/renstrom/fuzzysearch v1.1.0
)
编码例子
package main
import (
"fmt"
"github.com/lithammer/fuzzysearch/fuzzy"
"sort"
)
func main() {
var onlineAdverts = []string{"鲜花", "北京鲜花", "1+手机", "小米手机", "华为手机", "华为P30", "苹果手机"}
var userQuery = "手机"
matches1 := fuzzy.Find(userQuery, onlineAdverts)
fmt.Println("在线广告:", onlineAdverts)
fmt.Println("用户Query:", userQuery)
fmt.Println("模糊查询到在线广告 : ", matches1)
matches2 := fuzzy.RankFind(userQuery, onlineAdverts)
fmt.Println("RandFind:", matches2)
sort.Sort(matches2)
fmt.Println("Sort RandFind:", matches2)
matches3 := fuzzy.MatchNormalized("cartwheel", "cartwhéél")
fmt.Println("match normalized:", matches3)
}
编译命令
#windows:
set GOPROXY=https://goproxy.io
go mod tidy
go build
#Linux:
export GOPROXY=https://goproxy.io
go mod tidy
go build
运行结果
好,到此处基本上能够满足业务需求,喜欢的小伙伴,可以自己动手实现一下。
该文章公众号:“sir小龙虾”独家授权,其他人未经允许不得转载。