Golang操作elasticsearch(一)

栏目: Go · 发布时间: 7年前

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"`
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Reality Is Broken

Reality Is Broken

Jane McGonigal / Penguin Press HC, The / 2011-1-20 / USD 26.95

Visionary game designer Jane McGonigal reveals how we can harness the power of games to solve real-world problems and boost global happiness. More than 174 million Americans are gamers, and......一起来看看 《Reality Is Broken》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具