设为首页 收藏本站
查看: 874|回复: 0

[经验分享] elasticsearch golang的sdk使用

[复制链接]

尚未签到

发表于 2018-9-20 09:04:29 | 显示全部楼层 |阅读模式
package main  import (
  "context"
  "encoding/json"
  "fmt"
  "gopkg.in/olivere/elastic.v5" //这里使用的是版本5,最新的是6,有改动
  "log"
  "os"
  "reflect"
  )
  var client *elastic.Client
  var host = "http://127.0.0.1:9200/"
  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
  client, err = elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(host))
  if err != nil {
  panic(err)
  }
  info, code, 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)
  esversion, 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 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 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)
  }
  }
  //搜索
  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)
  if res.Hits.TotalHits > 0 {
  fmt.Printf("Found a total of %d Employee \n", res.Hits.TotalHits)
  for _, hit := range res.Hits.Hits {
  var t Employee
  err := json.Unmarshal(*hit.Source, &t) //另外一种取数据的方法
  if err != nil {
  fmt.Println("Deserialization failed")
  }
  fmt.Printf("Employee name %s : %s\n", t.FirstName, t.LastName)
  }
  } else {
  fmt.Printf("Found no Employee \n")
  }
  //条件查询
  //年龄大于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>  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()
  }


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-598633-1-1.html 上篇帖子: GO语言的进阶之路 下篇帖子: golang/TLS 采坑
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表