golang操作elasticsearch的實現(xiàn)
1、前提
1.1 docker 安裝elasticsearch
查詢elasticsearch 版本
docker search elasticsearch
將對應的版本拉到本地
docker.elastic.co/elasticsearch/elasticsearch:7.3.0
創(chuàng)建一個網(wǎng)絡
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
可以試一下界面還是很美觀的

2、golang 實現(xiàn)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*/
//創(chuàng)建
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)) { //從搜索結果中取數(shù)據(jù)的方法
t := item.(Employee)
fmt.Printf("%#v\n", t)
}
}
func main() {
create()
delete()
update()
gets()
query()
list(2,1)
}
有一個小坑要注意在代碼中已經(jīng)注釋了,如果沒有添加就會有下面錯誤
no active connection found: no Elasticsearch node available
解決
Docker No Elastic Node Aviable
關閉sniff模式;或者設置es的地址為 publish_address 地址
代碼設置 sniff 為false
到此這篇關于golang 操作 elasticsearch的實現(xiàn)的文章就介紹到這了,更多相關golang操作elasticsearch內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解如何使用Golang實現(xiàn)自定義規(guī)則引擎
規(guī)則引擎的功能可以簡化為當滿足一些條件時觸發(fā)一些操作,通常使用 DSL 自定義語法來表述,本文給大家介紹了如何使用Golang實現(xiàn)自定義規(guī)則引擎,文中有相關的代碼示例供大家參考,需要的朋友可以參考下2024-05-05
Golang實現(xiàn)Redis網(wǎng)絡協(xié)議實例探究
這篇文章主要為大家介紹了Golang實現(xiàn)Redis網(wǎng)絡協(xié)議實例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
golang實現(xiàn)頁面靜態(tài)化操作的示例代碼
這篇文章主要介紹了golang實現(xiàn)頁面靜態(tài)化操作的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02

