关于golang:golang-elasticsearch7的使用

6次阅读

共计 3210 个字符,预计需要花费 9 分钟才能阅读完成。

Golang 操作 elasticsearch7

  • 包:github.com/olivere/elastic/v7
  • elasticsearch 版本 7.6
    首先能够定义一个全量, 构建连接池

    var esCli *elastic.Client
    func init() {
          var err error
          esCli, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL("http://127.0.0.1:9200")
          if err != nil {panic(err)
          }
       }

应用办法
1、增加

 func EsAdd(es_index string, es_body interface{}) string {
    var id string
    rsAdd, err := esCli.Index().
        Index(es_index).
        BodyJson(es_body).
        Do(context.Background())
    if err != nil {panic(err)
    } else {id = rsAdd.Id}
    return id
 }
PS:id 是指 ES 主动生成的 id, 如果想自定义 id 能够在 Index() 前面加.Id(string)。目前用的是 es7.6,所以能够不必加 Type 默认_doc,也能够指定办法 Type()。

2、批量增加

func EsAddBulk(es_index string, es_body []interface{}) {bulkRequest := esCli.Bulk()
    for _, v := range es_body {
        tmp := v
        req := elastic.NewBulkIndexRequest().Index(es_index).Doc(tmp)
        bulkRequest = bulkRequest.Add(req)
    }
    _, err := bulkRequest.Do(context.Background())
    if err != nil {panic(err)
    }
}

3、增加

func EsUpdate(es_index string, es_id string, es_body interface{}) {_, err := esCli.Update().
        Index(es_index).
        Id(es_id).
        Doc(es_body).
        Do(context.Background())
    if err != nil {panic(err)
    }
}

4、批量批改

func EsUpdateBulk(es_index string, es_body []map[string]string) {bulkRequest := esCli.Bulk()
    for _, v := range es_body {
        tmp := v
        tmps := make(map[string]string)
        for is, vs := range tmp {
            if is != "id" {tmps[is] = vs
            }
        }
        req := elastic.NewBulkUpdateRequest().Index(es_index).Id(tmp["id"]).Doc(tmps).DocAsUpsert(true)
        bulkRequest = bulkRequest.Add(req)
    }
    _, err := bulkRequest.Do(context.Background())
    if err != nil {panic(err)
    }
}
PS:批量批改和批量减少办法是不同的,批量批改的办法 NewBulkUpdateRequest,要调用这个才有 DocAsUpsert。之前在 NewBulkIndexRequest 下始终没有找到 DocAsUpsert。另外用 []map[string]string 是因为每个数据要批改的 key 可能不同, 如果要批改的 key 雷同能够用 interface 或 struct。

5、删除文档

func Delete(es_index string, id string) {_, err := esCli.Delete().Index(es_index).Id(id).Do(context.Background())
    if err != nil {panic(err)
    }
}

6、查问以后 index 是否存在

func ExistsIndex(es_index string) bool {exists, err := esCli.IndexExists(es_index).Do(context.Background())
    if err != nil {panic(err)
    }
    return exists
}

7、查问

func Search(es_index string,page int ,li int) interface{} {p := (page - 1) * li
    collapsedata := elastic.NewCollapseBuilder("company")
    esq := elastic.NewBoolQuery()
    esq.Must(elastic.NewMatchPhraseQuery("company", "CO LTD."))
    esq.Must(elastic.NewMatchQuery("country", "US"))
    search := esCli.Search().
        Index(es_index).
        From(p).Size(li).
        Query(esq).
        Collapse(collapsedata).
        Pretty(true)
    searchResult, err := search.Do(context.Background())
    if err != nil {panic(err)
    } else {return searchResult}
}
PS:NewMatchPhraseQuery 是代表短语的匹配,Collapse 是指定字段雷同后果的折叠

查找延长:
像下面的后果返回的是 es 所有的参数,有时候只想用_Souce 那要在把外面的后果抽取进去。官网也配有办法:

func PrintTradedata(res *elastic.SearchResult, err error) tradedata {
    if err != nil {panic(err)
    }
    var typ tradedata
    var re tradedata
    for _, item := range res.Each(reflect.TypeOf(typ)) {te := item.(tradedata)
        jsonValue, _ := json.Marshal(te)
        json.Unmarshal(jsonValue, &re)
    }
    return re
}

然而这种的话,也有肯定的限制性就是如果我还想要_id 的话可能又要本人在循环一边构造获取。所以我去看来官网的办法,而后本人从新写一遍:

func PrintTradedata(res *elastic.SearchResult, err error) tradedata {
    if err != nil {panic(err)
    }
    var re tradedata
    for _, item := range res.Hits.Hits {
        if item.Source != nil {jsonValue, _ := json.Marshal(item.Source)
            json.Unmarshal(jsonValue, &re)
            re.ID = item.Id
        }
    }
    return re
}
这样就能提取出 es 的_id 和_source 的联合,可能感觉就这样几行为什么官网要封装多一个办法,其实官网封装的办法还做构造的验证安全性要比我的高,如果只有_source 举荐还是用官网的。

以上就是一些 golang 应用 es7 的根本办法,低的版本也实用不过要加上 type。es 最弱小的还是它的搜寻性能我只是写了根底的,应用 bool 查问,还有 term、math、fuzzy、wildcard 等等,还有翻页 scroll 和 search after,大家都能够去 elastic 包中查看。如果有须要,等有空我也能够写一篇专门对于搜寻的用法。
上述内容欢送大家斧正和交换。

正文完
 0