分享
  1. 首页
  2. 文章

Golang操作elasticsearch(一)

Mandelbrot_Kobe · · 4527 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Golang操作elasticsearch

  • 使用第三方包:olivere github。总结一下olivere操作ES的常用功能,方便查阅。
  • 说明:以下例子用到的es index:"test", es type:"test", es address: "http://10.1.1.1:9200"
  1. 新建es client

    func ESClient() (client *elastic.Client,err error){
     file := "./log.log"
     logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766) // 应该判断error,此处简略
     cfg := []elastic.ClientOptionFunc{
     elastic.SetURL("http://10.1.1.1:9200"),
     elastic.SetSniff(false),
     elastic.SetInfoLog(log.New(logFile, "ES-INFO: ", 0)),
     elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
     elastic.SetErrorLog(log.New(logFile, "ES-ERROR: ", 0)),
     }
     client,err =elastic.NewClient(cfg ...)
     return
    }
  2. 查看某文档是否存在,给定文档ID查询

    func isExists(id string)bool{
     client,_ := ESClient()
     defer client.Stop()
     exist,_ := client.Exists().Index("test").Type("test").Id(id).Do(context.Background())
     if !exist{
     log.Println("ID may be incorrect! ",id)
     return false
     }
     return true
    }
  3. 获取某文档的内容

    func(doc *myDocument) Get(id string){
     client ,_:= ESClient()
     defer client.Stop() 
     if !isExists(id){
     return
     }
     esResponse,err := client.Get().Index("test").Type("test").Id(id).Do(context.Background())
     if err != nil {
     // Handle Error
     return
     }
     json.Unmarshal(*esResponse.Source,&doc)
    }
  4. 新增文档

    func(doc *myDocument) Add(id string){
     client ,_:= ESClient()
     defer client.Stop() 
     if !isExists(id){
     return
     }
     client.Index().Index("test").Type("test").Id(id).BodyJson(doc).Do(context.Background())
    }
  5. 批量新增

    func BulkAdd(docs []myDocument){
     bulkRequest := seriesClient.Bulk()
     client ,_:= ESClient()
     defer client.Stop()
     for _,doc := range docs{
     esRequest := elastic.NewBulkIndexRequest().Index("test").Type("test").Id(id).Doc(doc)
     bulkRequest = bulkRequest.Add(esRequest)
     }
     bulkRequest.Do(context.Background())
    }
  6. 更新文档

    func Update(updateField *map[string]interface{},id string){
     client ,_:= ESClient()
     defer client.Stop()
     if !isExists(id){
     return
     }
     _,err:=client.Update().Index("test").Type("test").Id(id).Doc(updateField).Do(context.Background())
     if err != nil{
     //Handle Error
     }
    }
  7. 删除文档

    func Delete(id string){
     client ,_:= ESClient()
     defer client.Stop()
     if !isExists(id){
     return
     }
     _,err:=client.Delete().Index("test").Type("test").Id(id).Do(context.Background())
     if err != nil{
     //Handle Error
     }
    }
  8. 搜索文档(搜索是ES非常引以为傲的功能,以下示例是相对复杂的查询条件,需将查询结果排序,按页返回)

    func Search(criteria *SearchCriteria)(docs []myDocument){
     client ,_:= ESClient()
     defer client.Stop()
     query := elastic.NewBoolQuery()
     query = query.Must(elastic.NewTermQuery("category",criteria.Category))
     query=query.Must(elastic.NewMatchQuery("title",criteria.Title))
     query=query.Must(elastic.NewRangeQuery("update_timestamp").Gte(criteria.UpdateTime))
     esResponse,_ :=client.Search().Index("test").Type("test").
     Query(query).Sort(criteria.Sort,criteria.Order=="ASC"||criteria.Order=="asc").
     From(criteria.Offset).Size(criteria.Limit).Do(context.Background())
     for _,value:= range esResponse.Hits.Hits{
     var doc *myDocument
     json.Unmarshal(*value.Source,&doc)
     docs = append(docs,doc)
     }
     return
    }
    type SearchCriteria struct{
     Category string `json:"category"`
     Limit int `json:"limit"`
     Offset int `json:"offset"`
     Title string `json:"title"`
     UpdateTime int64 `json:"update_timestamp"`
     Order string `json:"order"`
     Sort string `json:"sort"`
    }

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:Mandelbrot_Kobe

查看原文:Golang操作elasticsearch(一)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
4527 次点击
被以下专栏收入,发现更多相似内容
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏