模糊搜索
要達到的目標是用戶不需要關心搜索系統的結構,任意輸入一串字符或者數字,只要搜索範圍中包含該信息,通過該方法就能夠找出該信息包含在哪個表,哪個字段裏,或者具體哪個位置,進而可以進行更爲詳細的查詢。
系統允許被搜索信息和搜索提問之間存在一定的差異,這種差異就是“模糊”在搜索中的含義。例如,查找名字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小龍蝦”獨家授權,其他人未經允許不得轉載。