欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

golang操作elasticsearch的实现

程序员文章站 2022-03-12 10:52:54
1、前提1.1 docker 安装elasticsearch查询elasticsearch 版本docker search elasticsearch将对应的版本拉到本地docker.elastic....

1、前提

1.1 docker 安装elasticsearch

查询elasticsearch 版本

docker search elasticsearch

将对应的版本拉到本地

docker.elastic.co/elasticsearch/elasticsearch:7.3.0

创建一个网络

docker network create esnet

启动容器

docker run --name es -p 9200:9200 -p 9300:9300 --network esnet -e "discovery.type=single-node" bdaab402b220

1.2这里过后就可以去写go代码 为了直观搞了个可视化工具 elistichd 这里使用docker 部署

docker run -p 9800:9800 -d --link es:demo --network esnet -e "discovery.type=single-node" containerize/elastichd

可以试一下界面还是很美观的

golang操作elasticsearch的实现

2、golang 实现elasticsearch 简单的增删改查

直接上代码:

package main

import (
  "context"
  "encoding/json"
  "fmt"
  "github.com/olivere/elastic/v7"
  "reflect"
)

var client *elastic.client
var host = "http://ip:port"

type employee struct {
  firstname string  `json:"first_name"`
  lastname string  `json:"last_name"`
  age    int   `json:"age"`
  about   string  `json:"about"`
  interests []string `json:"interests"`
}

//初始化
func init() {
  //errorlog := log.new(os.stdout, "app", log.lstdflags)
  var err error
      //这个地方有个小坑 不加上elastic.setsniff(false) 会连接不上 
  client, err = elastic.newclient(elastic.setsniff(false), elastic.seturl(host))
  if err != nil {
    panic(err)
  }
  _,_,err = client.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)

  _,err = client.elasticsearchversion(host)
  if err != nil {
    panic(err)
  }
  //fmt.printf("elasticsearch version %s\n", esversion)

}

/*下面是简单的curd*/

//创建
func create() {

  //使用结构体
  e1 := employee{"jane", "smith", 32, "i like to collect rock albums", []string{"music"}}
  put1, err := client.index().
    index("megacorp").
    type("employee").
    id("1").
    bodyjson(e1).
    do(context.background())
  if err != nil {
    panic(err)
  }
  fmt.printf("indexed tweet %s to index s%s, type %s\n", put1.id, put1.index, put1.type)

  //使用字符串
  e2 := `{"first_name":"john","last_name":"smith","age":25,"about":"i love to go rock climbing","interests":["sports","music"]}`
  put2, err := client.index().
    index("megacorp").
    type("employee").
    id("2").
    bodyjson(e2).
    do(context.background())
  if err != nil {
    panic(err)
  }
  fmt.printf("indexed tweet %s to index s%s, type %s\n", put2.id, put2.index, put2.type)

  e3 := `{"first_name":"douglas","last_name":"fir","age":35,"about":"i like to build cabinets","interests":["forestry"]}`
  put3, err := client.index().
    index("megacorp").
    type("employee").
    id("3").
    bodyjson(e3).
    do(context.background())
  if err != nil {
    panic(err)
  }
  fmt.printf("indexed tweet %s to index s%s, type %s\n", put3.id, put3.index, put3.type)

}


//查找
func gets() {
  //通过id查找
  get1, err := client.get().index("megacorp").type("employee").id("2").do(context.background())
  if err != nil {
    panic(err)
  }
  if get1.found {
    fmt.printf("got document %s in version %d from index %s, type %s\n", get1.id, get1.version, get1.index, get1.type)
    var bb employee
    err:=json.unmarshal(get1.source,&bb)
    if err!=nil{
      fmt.println(err)
    }
    fmt.println(bb.firstname)
    fmt.println(string(get1.source))
  }

}
//
//删除
func delete() {

  res, err := client.delete().index("megacorp").
    type("employee").
    id("1").
    do(context.background())
  if err != nil {
    println(err.error())
    return
  }
  fmt.printf("delete result %s\n", res.result)
}
//
//修改
func update() {
  res, err := client.update().
    index("megacorp").
    type("employee").
    id("2").
    doc(map[string]interface{}{"age": 88}).
    do(context.background())
  if err != nil {
    println(err.error())
  }
  fmt.printf("update age %s\n", res.result)

}
//
////搜索
func query() {
  var res *elastic.searchresult
  var err error
  //取所有
  res, err = client.search("megacorp").type("employee").do(context.background())
  printemployee(res, err)

  //字段相等
  q := elastic.newquerystringquery("last_name:smith")
  res, err = client.search("megacorp").type("employee").query(q).do(context.background())
  if err != nil {
    println(err.error())
  }
  printemployee(res, err)



  //条件查询
  //年龄大于30岁的
  boolq := elastic.newboolquery()
  boolq.must(elastic.newmatchquery("last_name", "smith"))
  boolq.filter(elastic.newrangequery("age").gt(30))
  res, err = client.search("megacorp").type("employee").query(q).do(context.background())
  printemployee(res, err)

  //短语搜索 搜索about字段中有 rock climbing
  matchphrasequery := elastic.newmatchphrasequery("about", "rock climbing")
  res, err = client.search("megacorp").type("employee").query(matchphrasequery).do(context.background())
  printemployee(res, err)

  //分析 interests
  aggs := elastic.newtermsaggregation().field("interests")
  res, err = client.search("megacorp").type("employee").aggregation("all_interests", aggs).do(context.background())
  printemployee(res, err)

}
//
////简单分页
func list(size,page int) {
  if size < 0 || page < 1 {
    fmt.printf("param error")
    return
  }
  res,err := client.search("megacorp").
    type("employee").
    size(size).
    from((page-1)*size).
    do(context.background())
  printemployee(res, err)

}
//
//打印查询到的employee
func printemployee(res *elastic.searchresult, err error) {
  if err != nil {
    print(err.error())
    return
  }
  var typ employee
  for _, item := range res.each(reflect.typeof(typ)) { //从搜索结果中取数据的方法
    t := item.(employee)
    fmt.printf("%#v\n", t)
  }
}

func main() {
  create()
  delete()
  update()
  gets()
  query()
  list(2,1)
}

有一个小坑要注意在代码中已经注释了,如果没有添加就会有下面错误

no active connection found: no elasticsearch node available

解决

docker no elastic node aviable

关闭sniff模式;或者设置es的地址为 publish_address 地址

代码设置 sniff 为false

到此这篇关于golang 操作 elasticsearch的实现的文章就介绍到这了,更多相关golang操作elasticsearch内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!