国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

[golang gin框架] 38.Gin操作Elasticsearch創(chuàng)建索引、修改映射、數(shù)據(jù)CURD以及數(shù)據(jù)分頁(yè)

這篇具有很好參考價(jià)值的文章主要介紹了[golang gin框架] 38.Gin操作Elasticsearch創(chuàng)建索引、修改映射、數(shù)據(jù)CURD以及數(shù)據(jù)分頁(yè)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

一.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ù)的增刪改查

  1. 新建 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)
    }
}
  1. 路由

在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)
  1. 控制器相關(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 全文搜索引擎的使用

[下一節(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)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • [golang gin框架] 40.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之Captcha驗(yàn)證碼微服務(wù)

    [golang gin框架] 40.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之Captcha驗(yàn)證碼微服務(wù)

    本次內(nèi)容需要 gin框架基礎(chǔ)知識(shí), golang微服務(wù)基礎(chǔ)知識(shí)才能更好理解 在前面,講解了微服務(wù)的架構(gòu)等,這里,來(lái)講解前面商城項(xiàng)目的 Captcha驗(yàn)證碼 微服務(wù) ,captcha驗(yàn)證碼功能在前臺(tái),后端 都要用到 ,可以把它 抽離出來(lái) ,做成微服務(wù)功能 編輯 這個(gè)驗(yàn)證碼功能封裝代碼captcha.go如下: 把這個(gè)

    2024年02月16日
    瀏覽(30)
  • 【golang】Windows環(huán)境下Gin框架安裝和配置

    【golang】Windows環(huán)境下Gin框架安裝和配置

    我終于搞定了Gin框架的安裝,花了兩三個(gè)小時(shí),只能說(shuō)道阻且長(zhǎng),所以寫(xiě)下這篇記錄文章 先需要修改一些變量,這就需要打開(kāi)終端,為了一次奏效,我們直接設(shè)置全局的: 首先創(chuàng)建一個(gè)項(xiàng)目 進(jìn)去之后先創(chuàng)建go.mod文件,創(chuàng)建完之后通常會(huì)為你自動(dòng)配置參數(shù) 然后我們打開(kāi)Files

    2024年02月07日
    瀏覽(63)
  • [golang gin框架] 26.Gin 商城項(xiàng)目-前臺(tái)自定義商品列表模板, 商品詳情數(shù)據(jù)渲染,Markdown語(yǔ)法使用

    [golang gin框架] 26.Gin 商城項(xiàng)目-前臺(tái)自定義商品列表模板, 商品詳情數(shù)據(jù)渲染,Markdown語(yǔ)法使用

    當(dāng)在首頁(yè)分類點(diǎn)擊進(jìn)入分類商品列表頁(yè)面時(shí),可以根據(jù)后臺(tái)分類中的分類模板跳轉(zhuǎn)到對(duì)應(yīng)的模板商品列表頁(yè)面 (1).商品控制器方法Category()完善 修改controllers/frontend/productController.go中的方法Category(), 判斷分類模板,如果后臺(tái)沒(méi)有設(shè)置,則使用默認(rèn)模板 (2).模板頁(yè)面案例 先來(lái)回顧一

    2024年02月01日
    瀏覽(27)
  • [golang gin框架] 45.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之角色權(quán)限關(guān)聯(lián)

    [golang gin框架] 45.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之角色權(quán)限關(guān)聯(lián)

    角色和權(quán)限的關(guān)聯(lián)關(guān)系在前面文章中有講解,見(jiàn)[golang gin框架] 14.Gin 商城項(xiàng)目-RBAC管理之角色和權(quán)限關(guān)聯(lián),角色授權(quán),在這里通過(guò)微服務(wù)來(lái)實(shí)現(xiàn) 角色對(duì)權(quán)限的授權(quán) 操作,這里要實(shí)現(xiàn)的有兩個(gè)功能,一個(gè)是進(jìn)入授權(quán),另一個(gè)是,授權(quán)提交操作,頁(yè)面如下: ?這里需要在proto/rbacRole.proto中增加

    2024年02月14日
    瀏覽(30)
  • [golang gin框架] 42.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)角色增刪改查微服務(wù)

    [golang gin框架] 42.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)角色增刪改查微服務(wù)

    上一節(jié)講解了后臺(tái)Rbac微服務(wù)用戶登錄功能以及Gorm數(shù)據(jù)庫(kù)配置單獨(dú)抽離,Consul配置單獨(dú)抽離,這一節(jié)講解 后臺(tái)Rbac微服務(wù) 角色 增刪改查微服務(wù) 功能,Rbac微服務(wù)角色增刪改查微服務(wù)和 后 臺(tái)Rbac用戶登錄微服務(wù) 是屬于 同一個(gè)Rbac微服務(wù) 的 不同子微服務(wù)功能 ,為了區(qū)分不同子微

    2024年02月15日
    瀏覽(24)
  • [golang gin框架] 44.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之權(quán)限的增刪改查微服務(wù)

    [golang gin框架] 44.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之權(quán)限的增刪改查微服務(wù)

    上一節(jié)講解了[golang gin框架] 43.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之管理員的增刪改查以及管理員和角色關(guān)聯(lián),這里講解權(quán)限管理Rbac微服務(wù)權(quán)限的增刪改查微服務(wù) 要實(shí)現(xiàn)權(quán)限的增刪改查,就需要?jiǎng)?chuàng)建對(duì)應(yīng)的模型,故在server/rbac/models下創(chuàng)建Access.go模型文件,參考[golang gin框架]

    2024年02月14日
    瀏覽(20)
  • [golang gin框架] 43.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之管理員的增刪改查以及管理員和角色關(guān)聯(lián)

    [golang gin框架] 43.Gin商城項(xiàng)目-微服務(wù)實(shí)戰(zhàn)之后臺(tái)Rbac微服務(wù)之管理員的增刪改查以及管理員和角色關(guān)聯(lián)

    上一節(jié)講解了后臺(tái)Rbac微服務(wù)角色增刪改查微服務(wù),這里講解權(quán)限管理Rbac微服務(wù)管理員的增刪改查微服務(wù)以及管理員和角色關(guān)聯(lián)微服務(wù)功能 要實(shí)現(xiàn)管理員的增刪改查,就需要?jiǎng)?chuàng)建對(duì)應(yīng)的模型,故在server/rbac/models下創(chuàng)建manager.go模型文件,參考[golang gin框架] 14.Gin 商城項(xiàng)目-RBAC管理代碼

    2024年02月14日
    瀏覽(38)
  • Golang學(xué)習(xí)日志 ━━ 通過(guò)將gin-vue-admin項(xiàng)目上傳到自己的倉(cāng)庫(kù)并且與原版保持更新來(lái)學(xué)習(xí)github操作

    Golang學(xué)習(xí)日志 ━━ 通過(guò)將gin-vue-admin項(xiàng)目上傳到自己的倉(cāng)庫(kù)并且與原版保持更新來(lái)學(xué)習(xí)github操作

    gin-vue-admin是一套國(guó)人用golang開(kāi)發(fā)的后臺(tái)管理系統(tǒng),本文是從作者早期原文中截取的一部分,后期會(huì)以本文為框架進(jìn)行擴(kuò)展說(shuō)明。 官網(wǎng):https://www.gin-vue-admin.com/ 學(xué)習(xí)視頻:https://www.bilibili.com/video/BV1kv4y1g7nT/?p=6 在gin-vue-admin根目錄里打開(kāi)終端,執(zhí)行 此時(shí)已經(jīng)把自己的代碼推到自

    2024年02月10日
    瀏覽(25)
  • golang Gin實(shí)現(xiàn)websocket

    golang Gin實(shí)現(xiàn)websocket

    golang使用?Gin實(shí)現(xiàn) websocket,這里筆者重新搭建一個(gè)項(xiàng)目 項(xiàng)目名為?go-gin-websocket 在指定文件夾下,新建項(xiàng)目文件夾?go-gin-websocket 進(jìn)入項(xiàng)目文件夾,打開(kāi)cmd窗口,在項(xiàng)目(go-gin-websocket)文件夾路徑下,執(zhí)行初始化命令?go mod init?go-gin-websocket 安裝依賴 安裝gin ?安裝websocket 在項(xiàng)

    2024年02月06日
    瀏覽(21)
  • 【Golang | Gin】net/http和Gin起web服務(wù)時(shí)的簡(jiǎn)單對(duì)比

    Gin 是一個(gè)用 Go (Golang) 編寫(xiě)的 Web 框架,詳細(xì)介紹參考官網(wǎng):https://gin-gonic.com/zh-cn/docs/introduction/ 開(kāi)始學(xué)習(xí)Gin之前,我們先首先回顧下使用net/http起一個(gè)簡(jiǎn)單的helloworld服務(wù) 注: 1、 http.HandleFunc : 使用一個(gè)默認(rèn)的 DefaultServeMux 來(lái)注冊(cè)路由信息。 / 是一個(gè) pattern , greet 是一個(gè) ha

    2024年02月08日
    瀏覽(26)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包