golang

关于 golang 中使用 ES

2019-08-28  本文已影响0人  顶尖少爷

需要使用到的包

gopkg.in/olivere/elastic.v6
golang.org/x/elasti

创建一个接口

controllers/base.go

package controllers

import (
    "context"
    "fmt"
    "log"
    "os"
    "gopkg.in/olivere/elastic.v6"
)


var EsClient *elastic.Client

var host = "http://127.0.0.1:9200/"

func  init(){
    //es 配置
    errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
    var err error
    EsClient, err =elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(host))
    if err != nil {
        panic(err)
    }
    info, code, err := EsClient.Ping(host).Do(context.Background())
    if err != nil {
        panic(err)
    }

    fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

    esversion, err := EsClient.ElasticsearchVersion(host)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Elasticsearch version %s\n", esversion)
}

在其他接口上调用

controllers/question.go


import (
    "context"
    "encoding/json"
    "fmt"
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
    "goGame/controllers"
    "golang.org/x/elastic"
    "zhihu/models"
)


//根据id查询
type ZhiHuGetWithIdController struct{
  beego.Controller
}

func (this *ZhiHuGetWithIdController) Get(){
    get ,err:= EsClient.Get().Index("elas_ar_zhihu_article").Type("elas_ar_zhihu_article_type").Id("1").Do(context.Background())
    if err != nil {
        panic(err)
    }
    if get.Found {
        this.Data["json"] = get.Source
        this.ServeJSON()
    }
}

//根据条件查询query
type ZhiHuSearchController struct {
    beego.Controller
}

//查询 es查询

type EsItem struct {
    Id int `json:"id"`
    OrContent string `json:"or_content"`
    ArContent string `json:"ar_content"`
}

type EsData struct {
    Total int64 `json:"total"`
    Items  interface{} `json:"items"`
}
type EsResult struct {
    Status string `json:"status"`
    Data  EsData `json:"data"`

}

func (this *ZhiHuSearchController) Get(){
    var q ,query elastic.Query
    or_value := this.GetString("or_content")
    if or_value!=""{
        query = elastic.NewMatchPhraseQuery("or_content",or_value)
    }

    ar_value := this.GetString("ar_content")
    if ar_value !=""{
        q  =elastic.NewMatchPhraseQuery("ar_content",ar_value)
    }
    res ,err:= EsClient.Search().Index("elas_ar_zhihu_article").Type("elas_ar_zhihu_article_type").Query(query).Query(q).Do(context.Background())
    if err !=nil{
        println(err.Error())
    }
    var data EsData
    if res.Hits.TotalHits>0{
        var items []interface{}
        data.Total = res.Hits.TotalHits
        for _,hit :=range res.Hits.Hits{
            var item EsItem
            err := json.Unmarshal(*hit.Source, &item) //另外一种取数据的方法
            if err !=nil{
                fmt.Print(err.Error())
            }
            items = append(items,item)
        }
        data.Items = items

    }
    var result EsResult
    result.Status = "success"
    result.Data = data
    this.Data["json"] = result
    this.ServeJSON()
}

上一篇下一篇

猜你喜欢

热点阅读