Go语言 模糊搜索实验(一)
生活随笔
收集整理的這篇文章主要介紹了
Go语言 模糊搜索实验(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模糊搜索
要達到的目標是用戶不需要關心搜索系統的結構,任意輸入一串字符或者數字,只要搜索范圍中包含該信息,通過該方法就能夠找出該信息包含在哪個表,哪個字段里,或者具體哪個位置,進而可以進行更為詳細的查詢。
系統允許被搜索信息和搜索提問之間存在一定的差異,這種差異就是“模糊”在搜索中的含義。例如,查找名字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/xgit 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.gitgo.mod
module fuzzySearchgo 1.13require (golang.org/x/text v0.3.2github.com/renstrom/fuzzysearch v1.1.0 )編碼例子
package mainimport ("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小龍蝦”獨家授權,其他人未經允許不得轉載。
總結
以上是生活随笔為你收集整理的Go语言 模糊搜索实验(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Go语言 gRPC 实践(一)
- 下一篇: Go语言 XML生成和解析