Go语言 模糊搜索实验(一)

本文介绍了一种模糊搜索技术,使用户能通过输入部分字符或数字,查找包含相似信息的数据。重点讲解了Go语言的FuzzySearch库使用方法,演示了如何在在线广告中查找包含特定关键词的所有条目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模糊搜索

要达到的目标是用户不需要关心搜索系统的结构,任意输入一串字符或者数字,只要搜索范围中包含该信息,通过该方法就能够找出该信息包含在哪个表,哪个字段里,或者具体哪个位置,进而可以进行更为详细的查询。

系统允许被搜索信息和搜索提问之间存在一定的差异,这种差异就是“模糊”在搜索中的含义。例如,查找名字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小龙虾”独家授权,其他人未经允许不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值