文档第一

《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使用的更多相关文章

  1. 上传golang 版本SDK

    在上传的时候,文件都上传成功了,但是返回的信息里面errcode 404 token 是"".是不是因为我的callbackUrl(随便写的) 写错导致的. 上传golang 版本 ...

  2. golang DynamoDB sdk AccessDeniedException

    golang调用aws sdk时候提示: AccessDeniedException: User: arn:aws:sts::818539432014:assumed-role/bj-develop/ ...

  3. [golang学习] 在idea中code & debug

    [已废弃]不需要看 idea 虽然审美倒退了n年. 不过功能还是相当好用的. idea 的go插件堪称最好的go ide. 1. 语法高亮支持 2. 智能提示 3. 跳转定义(反跳转回来) 4. 集成 ...

  4. Mac OS X下环境搭建 Sublime Text 2 环境变量配置 开发工具配置Golang (Go语言)

    Golang (Go语言) Mac OS X下环境搭建 环境变量配置 开发工具配置 Sublime Text 2 一.安装Golang的SDK 在官网http://golang.org/ 直接下载安装 ...

  5. Intellij IDEA安装golang插件

    原文作者:Jianan - qinxiandiqi@foxmail.com 原文地址:http://blog.csdn.net/qinxiandiqi/article/details/50319953 ...

  6. Golang (Go语言) Mac OS X下环境搭建 环境变量配置 开发工具配置 Sublime Text 2 【转】

    一.安装Golang的SDK 在官网 http://golang.org/ 直接下载安装包安装即可.下载pkg格式的最新安装包,直接双击运行,一路按照提示操作即可完成安装. 安装完成后,打开终端,输入 ...

  7. 关于go语言的环境配置 SDK+path+工作目录

    第一步: 安装Golang的SDK http://golang.org,下载最新的安装包,之后双击安装即可. 安装完成之后,打开终端,输入go.或者go version(查看安装版本)出现如下信息即表 ...

  8. 令人懊恼的阉割版fabric sdk功能缺失

    按理说,fabric本身都是用golang开发的,那么fabric-sdk-go作为其亲儿子,功能应该是最为完善的.然而,与我们想法相左的是,golang版本的sdk反而是最不完备的,开发进度滞后,功 ...

  9. Mac系统搭建Go语言Sublime Text 2环境配置

    Go语言是谷歌自家的编译型语言,旨在不损失性能的前提下降低代码复杂率.其优势是让软件充分发挥多核心处理器同步多工的优点,并可解决面向对象程序设计的麻烦. 一.安装Golang的SDK 在官网http: ...

随机推荐

  1. 【SqlServer】SqlServer中Alter语句的使用

    在修改Sql Server表结构时,常用到Alter语句,把一些常用的alter语句列举如下. 1:向表中添加字段 Alter table [表名] add [列名] 类型 2:  删除字段 Alte ...

  2. [.NET] 使用VALIDATIONCONTEXT快速进行模型资料的验证 》简单xml创建-json转xml

    [.NET] 使用VALIDATIONCONTEXT快速进行模型资料的验证 在进行WebAPI功能开发的时候,一般传统的验证资料是否合法的方式,都是透过if/else的方式进行判断若是使用Valida ...

  3. 'Agent XPs' component is turned off as part of the security configuration for this server

    To turn on Agent XP's by running this script: sp_configure 'show advanced options', 1; Go RECONFIGUR ...

  4. 使用ShellExecute打开文件夹并选中文件

    原文链接: http://futurecode.is-programmer.com/posts/24780.html 假设在C:\目录下存在文件a.txt. 打开这个目录是ShellExecute的常 ...

  5. 解决sklearn 随机森林数据不平衡的方法

    Handle Imbalanced Classes In Random Forest   Preliminaries # Load libraries from sklearn.ensemble im ...

  6. 在java项目中使用 Lombok 及可能问题

    一.Maven项目使用步骤一般包含两步,1)引入依赖 2)特定的 IDE 引入对应的插件 1)在POM中引入依赖 <!-- https://mvnrepository.com/artifact/ ...

  7. xbox360 双65厚机自制系统无硬盘 U盘玩游戏方法

    因为没有硬盘,又没有光盘.所以想把游戏放在U盘里面.用U盘来做为硬盘玩游戏. 现有的自制系统主要是FSD,但是FSD要用硬盘才能安装,理论上U盘也可以,但是我没有尝试了. 这里介绍的是玩xex格式的游 ...

  8. hive splict, explode, lateral view, concat_ws

    hive> create table arrays (x array<string>) > row format delimited fields terminated by ...

  9. rocketmq 学习记录-2

    产品选型 我们在进行中间件选型时,一般都是通过下面几点来进行产品选型的: 1.性能 2.功能支持程度 3.开发语言(团队中是否有成员熟悉此中间件的开发语言,市场上此种语言的开发人员是否好招) 4.有多 ...

  10. ios支付宝问题整合

           1. 报错:rsa_private read error : private key is NULL     原因:私钥没有转成PKCS8   解决方法: 1)在RSADataSigne ...