elasticsearch golang的sdk使用
文档第一
《elasticsearch权威指南》直接看官网在线版的,比较新,网上那些pdf版的,都是2.x版的,许多不兼容
官方API手册,可以选择版本。
golang sdk库的选择
主要有以下两个
- github.com/olivere/elastic 第三方开发,各个版本都有对应的sdk,文档也丰富
- github.com/elastic/go-elasticsearch 不做评论
最终我们选择了olivere/elastic
restful api和olivere/elastic 的对应代码如下:
package main
import (
"context"
"encoding/json"
"fmt"
"gopkg.in/olivere/elastic.v5" //这里使用的是版本5,最新的是6,有改动
"log"
"os"
"reflect"
)
var client *elastic.Client
var host = "http://127.0.0.1:9200/"
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
client, err = elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(host))
if err != nil {
panic(err)
}
info, code, 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)
esversion, 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 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 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)
}
}
//搜索
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)
if res.Hits.TotalHits > 0 {
fmt.Printf("Found a total of %d Employee \n", res.Hits.TotalHits)
for _, hit := range res.Hits.Hits {
var t Employee
err := json.Unmarshal(*hit.Source, &t) //另外一种取数据的方法
if err != nil {
fmt.Println("Deserialization failed")
}
fmt.Printf("Employee name %s : %s\n", t.FirstName, t.LastName)
}
} else {
fmt.Printf("Found no Employee \n")
}
//条件查询
//年龄大于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()
}
辅助工具
- ElasticHD 单文件可执行文件,而且支持sql转es的查询
- mobz/elasticsearch-head es 5.0以后不支持插件安装,而是需要通过node来运行http服务器,或者通过Google浏览器插件
最终选择了ElasticHD
elasticsearch golang的sdk使用的更多相关文章
- 上传golang 版本SDK
在上传的时候,文件都上传成功了,但是返回的信息里面errcode 404 token 是"".是不是因为我的callbackUrl(随便写的) 写错导致的. 上传golang 版本 ...
- golang DynamoDB sdk AccessDeniedException
golang调用aws sdk时候提示: AccessDeniedException: User: arn:aws:sts::818539432014:assumed-role/bj-develop/ ...
- [golang学习] 在idea中code & debug
[已废弃]不需要看 idea 虽然审美倒退了n年. 不过功能还是相当好用的. idea 的go插件堪称最好的go ide. 1. 语法高亮支持 2. 智能提示 3. 跳转定义(反跳转回来) 4. 集成 ...
- Mac OS X下环境搭建 Sublime Text 2 环境变量配置 开发工具配置Golang (Go语言)
Golang (Go语言) Mac OS X下环境搭建 环境变量配置 开发工具配置 Sublime Text 2 一.安装Golang的SDK 在官网http://golang.org/ 直接下载安装 ...
- Intellij IDEA安装golang插件
原文作者:Jianan - qinxiandiqi@foxmail.com 原文地址:http://blog.csdn.net/qinxiandiqi/article/details/50319953 ...
- Golang (Go语言) Mac OS X下环境搭建 环境变量配置 开发工具配置 Sublime Text 2 【转】
一.安装Golang的SDK 在官网 http://golang.org/ 直接下载安装包安装即可.下载pkg格式的最新安装包,直接双击运行,一路按照提示操作即可完成安装. 安装完成后,打开终端,输入 ...
- 关于go语言的环境配置 SDK+path+工作目录
第一步: 安装Golang的SDK http://golang.org,下载最新的安装包,之后双击安装即可. 安装完成之后,打开终端,输入go.或者go version(查看安装版本)出现如下信息即表 ...
- 令人懊恼的阉割版fabric sdk功能缺失
按理说,fabric本身都是用golang开发的,那么fabric-sdk-go作为其亲儿子,功能应该是最为完善的.然而,与我们想法相左的是,golang版本的sdk反而是最不完备的,开发进度滞后,功 ...
- Mac系统搭建Go语言Sublime Text 2环境配置
Go语言是谷歌自家的编译型语言,旨在不损失性能的前提下降低代码复杂率.其优势是让软件充分发挥多核心处理器同步多工的优点,并可解决面向对象程序设计的麻烦. 一.安装Golang的SDK 在官网http: ...
随机推荐
- golang学习笔记 ---命名
Go语言中的函数名.变量名.常量名.类型名.语句标号和包名等所有的命名,都遵循一个简单的命名规则:一个名字必须以一个字母(Unicode字母)或下划线开头,后面可以跟任意数量的字母.数字或下划线.大写 ...
- emergency monitoring和real-time ADDM
emergency monitoring面临的挑战: 1.sick systems 2.slow database -所有用户查询响应慢 -性能界面刷新数据慢 -吞吐量严重降低 3.因为内部资源竞争数 ...
- Fuel4d 2.3 公布
[版本号编号]:Fuel4D 2.3. [公布日期]:2014年10月20日. [编译环境]:UNICODE.VS2010.x86. [开发环境]:ANSI/UTF-8/UNICODE.VS2005/ ...
- Java 内存溢出思维导图
文 by / 林本托 Tips 做一个终身学习的人. 在 Java 内存中,只有一个区域不会发生 OOM 异常,那就是程序计数器内存.下面的思维导图记录了每个内存区域发生内存异常的条件和基本的解决思路 ...
- FreeSWITCH呼叫参数之sip_cid_type
这个参数定义了呼叫中主叫信息的头字段类型.支持两种类型: 1. rpidRemote-Party-ID头,这是默认的设置.{sip_cid_type=rpid}sofia/default/user@e ...
- Hadoop JobTracker和NameNode运行时参数查看
1)JobTracker运行时参数: hadoop@ubuntu:/home/zhangchao3$ ps -ef | grep job hadoop 29563 1 0 11:34 pts/12 ...
- 如何使用 t-sql 更新数据库中日期字段的部分数据(年?月?日?时?分?秒?)
嗯,从网上找到了一些内容,综合利用了sql server的一些内置方法 首先是 convert 方法:https://msdn.microsoft.com/zh-cn/library/ms187928 ...
- iOS底层原理总结 - 探寻block的本质(一)
面试题 block的原理是怎样的?本质是什么? __block的作用是什么?有什么使用注意点? block的属性修饰词为什么是copy?使用block有哪些使用注意? block在修改NSMu ...
- 打造 Vue.js 可复用组件
Vue.js 是一套构建用户界面的渐进式框架.我们可以使用简单的 API 来实现响应式的数据绑定和组合的视图组件. 从维护视图到维护数据,Vue.js 让我们快速地开发应用.但随着业务代码日益庞大,组 ...
- [Windows Azure] Using the Graph API to Query Windows Azure AD
Using the Graph API to Query Windows Azure AD 4 out of 4 rated this helpful - Rate this topic This d ...