From 19ef9f937c12abf10720c8db1813df65af268be2 Mon Sep 17 00:00:00 2001 From: Sinh Date: Wed, 13 Oct 2021 16:30:00 +0700 Subject: [PATCH 1/2] add query search string --- go.mod | 1 + go.sum | 2 ++ 2 files changed, 3 insertions(+) diff --git a/go.mod b/go.mod index 753acf7..8ca4092 100644 --- a/go.mod +++ b/go.mod @@ -5,4 +5,5 @@ go 1.16 require ( github.com/logrusorgru/aurora v2.0.3+incompatible go.mongodb.org/mongo-driver v1.7.1 + golang.org/x/text v0.3.7 // indirect ) diff --git a/go.sum b/go.sum index ad47448..e87e9d4 100644 --- a/go.sum +++ b/go.sum @@ -103,6 +103,8 @@ golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= From 48c904d272a7ed0342523d90a2e059b4fadfc823 Mon Sep 17 00:00:00 2001 From: Sinh Date: Wed, 13 Oct 2021 16:30:23 +0700 Subject: [PATCH 2/2] add query search string --- search_string.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 search_string.go diff --git a/search_string.go b/search_string.go new file mode 100644 index 0000000..5015bad --- /dev/null +++ b/search_string.go @@ -0,0 +1,37 @@ +package mongodb + +import ( + "regexp" + "strings" + "unicode" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "golang.org/x/text/runes" + "golang.org/x/text/transform" + "golang.org/x/text/unicode/norm" +) + +// GenerateQuerySearchString ... +func GenerateQuerySearchString(s string) bson.M { + return bson.M{ + "$regex": bsonx.Regex(NonAccentVietnamese(s), "i"), + } +} + +// NonAccentVietnamese ... +func NonAccentVietnamese(str string) string { + str = strings.ToLower(str) + str = replaceStringWithRegex(str, `đ`, "d") + t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) + result, _, _ := transform.String(t, str) + result = replaceStringWithRegex(result, `[^a-zA-Z0-9\s]`, "") + + return result +} + +// replaceStringWithRegex ... +func replaceStringWithRegex(src string, regex string, replaceText string) string { + reg := regexp.MustCompile(regex) + return reg.ReplaceAllString(src, replaceText) +}