一.Golang 操作 ElasticSearch 的插件介紹
常見(jiàn)的 Golang 操作 ElasticSearch 的插件主要有下面兩個(gè):
第三方插件: github.com/olivere/elastic
官網(wǎng)插件 github.com/elastic/go-elasticsearch
其中 elastic 比 go-elasticsearch 文檔更全面一些,start 量也更多一些,本節(jié)講解 elastic
二.elastic 插件的使用
使用第三方庫(kù) https://github.com/olivere/elastic 來(lái)連接 ES 并進(jìn)行操作
注意:
下載與 ES 相同版本的 client,例如這里使用的 ES 是 7.x 的版本,那么下
載的 client 也要與之對(duì)應(yīng)為 github.com/olivere/elastic/v7
import (
? ? ... "github.com/olivere/elastic/v7"
)
官方實(shí)例代碼參考:https://godoc.org/github.com/olivere/elastic
三.Gin 中使用 elastic 插件實(shí)現(xiàn)數(shù)據(jù)的增刪改查
新建 models/esCore.go
引入elastic插件,先在esCore.go中import github.com/olivere/elastic/v7,然后在main.go文件下運(yùn)行命令:go mod tidy即可; 注意:elastic版本要和ES版本對(duì)應(yīng)
package models
//es插件使用
import (
"fmt"
"github.com/olivere/elastic/v7"
)
var EsClient *elastic.Client
func init() {
//注意IP和端口
EsClient, err = elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))
if err != nil {
fmt.Println(err)
}
}
路由
在routers/frontendRouters.go中增加ElasticSearch相關(guān)路由
//設(shè)置es索引以及配置
defaultRouters.GET("/search", frontend.SearchController{}.Index)
//獲取一條es數(shù)據(jù)
defaultRouters.GET("/search/getOne", frontend.SearchController{}.GetOne)
//增加數(shù)據(jù)到es中
defaultRouters.GET("/search/addGoods", frontend.SearchController{}.AddGoods)
//更新es中對(duì)應(yīng)的數(shù)據(jù)
defaultRouters.GET("/search/updateGoods", frontend.SearchController{}.UpdateGoods)
//刪除es中的數(shù)據(jù)
defaultRouters.GET("/search/deleteGoods", frontend.SearchController{}.DeleteGoods)
//模糊查詢es數(shù)據(jù)
defaultRouters.GET("/search/query", frontend.SearchController{}.Query)
//條件篩選es查詢
defaultRouters.GET("/search/filterQuery", frontend.SearchController{}.FilterQuery)
//分頁(yè)查詢es數(shù)據(jù)
defaultRouters.GET("/search/pagingQuery", frontend.SearchController{}.PagingQuery)
控制器相關(guān)代碼
相關(guān)方法:
設(shè)置es索引以及配置,獲取一條es數(shù)據(jù),增加數(shù)據(jù)到es中,更新es中對(duì)應(yīng)的數(shù)據(jù),刪除es中的數(shù)據(jù),模糊查詢es數(shù)據(jù),條件篩選es查詢,分頁(yè)查詢es數(shù)據(jù)
package frontend
//Elasticsearch 控制器
import (
"context"
"encoding/json"
"fmt"
"goshop/models"
"reflect"
"strconv"
"github.com/gin-gonic/gin"
"github.com/olivere/elastic/v7"
)
type SearchController struct {
BaseController
}
//初始化的時(shí)候判斷索引goods是否存在,創(chuàng)建索引配置映射
func (con SearchController) Index(c *gin.Context) {
exists, err := models.EsClient.IndexExists("goods").Do(context.Background())
if err != nil {
// Handle error
fmt.Println(err)
}
print(exists)
if !exists {
// 配置映射
mapping := `
{
"settings": { //設(shè)置
"number_of_shards": 1, //分區(qū)數(shù)配置
"number_of_replicas": 0 //副本數(shù)配置
},
"mappings": { //映射
"properties": {
"Content": { //映射屬性
"type": "text", //類型
"analyzer": "ik_max_word", // 檢測(cè)粒度
"search_analyzer": "ik_max_word" //搜索粒度
},
"Title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
}
`
//注意:增加的寫(xiě)法-創(chuàng)建索引配置映射
_, err := models.EsClient.CreateIndex("goods").Body(mapping).Do(context.Background())
if err != nil {
// Handle error
fmt.Println(err)
}
}
c.String(200, "創(chuàng)建索引配置映射成功")
}
//增加商品數(shù)據(jù)到es
func (con SearchController) AddGoods(c *gin.Context) {
//獲取數(shù)據(jù)庫(kù)中的商品數(shù)據(jù)
goods := []models.Goods{}
models.DB.Find(&goods)
//循環(huán)商品,把每個(gè)商品存入es
for i := 0; i < len(goods); i++ {
_, err := models.EsClient.Index().
Index("goods"). //設(shè)置索引
Type("_doc"). //設(shè)置類型
Id(strconv.Itoa(goods[i].Id)). //設(shè)置id
BodyJson(goods[i]). //設(shè)置商品數(shù)據(jù)(結(jié)構(gòu)體格式)
Do(context.Background())
if err != nil {
// Handle error
fmt.Println(err)
}
}
c.String(200, "AddGoods success")
}
//更新數(shù)據(jù)
func (con SearchController) UpdateGoods(c *gin.Context) {
goods := []models.Goods{}
models.DB.Find(&goods)
goods[0].Title = "我是修改后的數(shù)據(jù)"
goods[0].GoodsContent = "我是修改后的數(shù)據(jù)GoodsContent"
_, err := models.EsClient.Update().
Index("goods").
Type("_doc").
Id("19"). //要修改的數(shù)據(jù)id
Doc(goods[0]). //要修改的數(shù)據(jù)結(jié)構(gòu)體
Do(context.Background())
if err != nil {
// Handle error
fmt.Println(err)
}
c.String(200, "修改數(shù)據(jù) success")
}
//刪除
func (con SearchController) DeleteGoods(c *gin.Context) {
_, err := models.EsClient.Delete().
Index("goods").
Type("_doc").
Id("19").
Do(context.Background())
if err != nil {
// Handle error
fmt.Println(err)
}
c.String(200, "刪除成功 success")
}
//查詢一條數(shù)據(jù)
func (con SearchController) GetOne(c *gin.Context) {
//defer 操作:捕獲panic數(shù)據(jù)
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
c.String(200, "GetOne Error")
}
}()
result, err := models.EsClient.Get().
Index("goods").
Type("_doc").
Id("19").
Do(context.Background())
if err != nil { //判斷數(shù)據(jù)是否存在,不存在則panic
// Some other kind of error
panic(err)
}
goods := models.Goods{} //實(shí)例化一個(gè)商品結(jié)構(gòu)體
json.Unmarshal(result.Source, &goods) //把result結(jié)果解析到goods中
c.JSON(200, gin.H{
"goods": goods,
})
}
//模糊查詢數(shù)據(jù)
func (con SearchController) Query(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
c.String(200, "Query Error")
}
}()
//模糊查詢操作
query := elastic.NewMatchQuery("Title", "手機(jī)") //Title中包含 手機(jī) 的數(shù)據(jù)
searchResult, err := models.EsClient.Search().
Index("goods"). // search in index "goods"
Query(query). // specify the query
Do(context.Background()) // execute
if err != nil {
// Handle error
panic(err)
}
goods := models.Goods{}
c.JSON(200, gin.H{
"searchResult": searchResult.Each(reflect.TypeOf(goods)), //查詢的結(jié)果:reflect.TypeOf(goods)類型斷言,可以判斷是否商品結(jié)構(gòu)體
})
}
//分頁(yè)查詢
func (con SearchController) PagingQuery(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
c.String(200, "Query Error")
}
}()
page, _ := strconv.Atoi(c.Query("page")) //獲取當(dāng)前頁(yè)碼數(shù)
if page == 0 {
page = 1
}
pageSize := 2
query := elastic.NewMatchQuery("Title", "手機(jī)")
searchResult, err := models.EsClient.Search().
Index("goods"). // search in index "goods"
Query(query). // specify the query
Sort("Id", true). // true 表示升序 false 降序
From((page - 1) * pageSize).Size(pageSize). // 分頁(yè)查詢
Do(context.Background()) // execute
if err != nil {
// Handle error
panic(err)
}
goods := models.Goods{}
c.JSON(200, gin.H{
"searchResult": searchResult.Each(reflect.TypeOf(goods)),
})
}
//條件篩選查詢
func (con SearchController) FilterQuery(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
c.String(200, "Query Error")
}
}()
//篩選
boolQ := elastic.NewBoolQuery()
boolQ.Must(elastic.NewMatchQuery("Title", "小米"))
boolQ.Filter(elastic.NewRangeQuery("Id").Gt(19)) //Id 大于19
boolQ.Filter(elastic.NewRangeQuery("Id").Lt(42)) //Id 小于42
searchResult, err := models.EsClient.Search().
Index("goods").
Type("_doc").
Sort("Id", true).
Query(boolQ).
Do(context.Background())
if err != nil {
fmt.Println(err)
}
goodsList := []models.Goods{}
var goods models.Goods
for _, item := range searchResult.Each(reflect.TypeOf(goods)) { //循環(huán)搜索結(jié)果,并把結(jié)果類型斷言goods,如果結(jié)果類型是商品數(shù)據(jù)類型,則循環(huán)處理
t := item.(models.Goods)
fmt.Printf("Id:%v 標(biāo)題:%v\n", t.Id, t.Title)
goodsList = append(goodsList, t)
}
c.JSON(200, gin.H{
"goodsList": goodsList,
})
}
[上一節(jié)][golang gin框架] 37.ElasticSearch 全文搜索引擎的使用文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-489044.html
[下一節(jié)][golang gin框架] 39.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之微服務(wù)架構(gòu)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-489044.html
到了這里,關(guān)于[golang gin框架] 38.Gin操作Elasticsearch創(chuàng)建索引、修改映射、數(shù)據(jù)CURD以及數(shù)據(jù)分頁(yè)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!