脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - golang操作elasticsearch的实现

golang操作elasticsearch的实现

2020-07-20 11:33guyan0319 Golang

这篇文章主要介绍了golang操作elasticsearch,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1、前提

1.1 docker 安装elasticsearch

查询elasticsearch 版本

?
1
docker search elasticsearch

将对应的版本拉到本地

?
1
docker.elastic.co/elasticsearch/elasticsearch:7.3.0

创建一个网络

?
1
docker network create esnet

启动容器

?
1
docker run --name es -p 9200:9200 -p 9300:9300 --network esnet -e "discovery.type=single-node" bdaab402b220

1.2这里过后就可以去写go代码 为了直观搞了个可视化工具 ElisticHD 这里使用docker 部署

?
1
docker run -p 9800:9800 -d --link es:demo --network esnet -e "discovery.type=single-node" containerize/elastichd

可以试一下界面还是很美观的

golang操作elasticsearch的实现

2、golang 实现elasticsearch 简单的增删改查

直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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*/
 
//创建
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)) { //从搜索结果中取数据的方法
    t := item.(Employee)
    fmt.Printf("%#v\n", t)
  }
}
 
func main() {
  create()
  delete()
  update()
  gets()
  query()
  list(2,1)
}

有一个小坑要注意在代码中已经注释了,如果没有添加就会有下面错误

no active connection found: no Elasticsearch node available

解决

Docker No Elastic Node Aviable

关闭sniff模式;或者设置es的地址为 publish_address 地址

代码设置 sniff 为false

到此这篇关于golang 操作 elasticsearch的实现的文章就介绍到这了,更多相关golang操作elasticsearch内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.jianshu.com/p/e3e40af0dba7

延伸 · 阅读

精彩推荐
  • GolangGo语言实现自动填写古诗词实例代码

    Go语言实现自动填写古诗词实例代码

    这篇文章主要给大家介绍了关于Go语言实现自动填写古诗词的相关资料,这是最近在项目中遇到的一个需求,文中通过示例代码介绍的非常详细,需要的朋...

    FengY5862020-05-14
  • GolangGo语言range关键字循环时的坑

    Go语言range关键字循环时的坑

    今天小编就为大家分享一篇关于Go语言range关键字循环时的坑,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来...

    benben_20154202020-05-23
  • Golang深入浅析Go中三个点(...)用法

    深入浅析Go中三个点(...)用法

    这篇文章主要介绍了深入浅析Go中三个点(...)用法,需要的朋友可以参考下...

    踏雪无痕SS6472021-11-17
  • GolangGO语言字符串处理Strings包的函数使用示例讲解

    GO语言字符串处理Strings包的函数使用示例讲解

    这篇文章主要为大家介绍了GO语言字符串处理Strings包的函数使用示例讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加...

    Jeff的技术栈6882022-04-14
  • GolangGolang 语言极简类型转换库cast的使用详解

    Golang 语言极简类型转换库cast的使用详解

    本文我们通过 cast.ToString() 函数的使用,简单介绍了cast 的使用方法,除此之外,它还支持很多其他类型,在这没有多多介绍,对Golang 类型转换库 cast相关知...

    Golang语言开发栈6112021-12-02
  • GolangGolang实现四种负载均衡的算法(随机,轮询等)

    Golang实现四种负载均衡的算法(随机,轮询等)

    本文介绍了示例介绍了Golang 负载均衡的四种实现,主要包括了随机,轮询,加权轮询负载,一致性hash,感兴趣的小伙伴们可以参考一下...

    Gundy_8442021-08-09
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7812021-12-05
  • Golanggo语言获取系统盘符的方法

    go语言获取系统盘符的方法

    这篇文章主要介绍了go语言获取系统盘符的方法,涉及Go语言调用winapi获取系统硬件信息的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    无尽海3862020-04-24