文档第一

《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. Block(二)内存管理与其他特性-b

    一.block放在哪里 我们针对不同情况来讨论block的存放位置: 1.栈和堆 以下情况中的block位于堆中: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  2. 轻量级验证码生成插件webutil-licenseImage源码与实例应用

    webutil-licenseImage 插件内置4种验证码样式,支持用户扩展.自定义样式实现简单验证码. 源码脱管地址: http://code.google.com/p/licenseimage/ ...

  3. 1142 - show view command denied to user

    原因是没有给test用户授予"show_view_priv"权限 mysql> SELECT * FROM mysql.user WHERE User = 'test' an ...

  4. Fix SharePoint 2013 Site in Read only mode after an interrupted backup

    Problem When I was backing up SharePoint Site Collection Automatically with PowerShell and Windows T ...

  5. 第一篇:初识ASP.NET控件开发_第一节:控件类及其继承关系

    1)System.Web.UI.Control(以下简称Control) Control 类是包括自定义控件.用户控件和页在内的所有 ASP.NET 服务器控件的基类..定义由所有 ASP.NET 服 ...

  6. Cadence 5141 下TSMC 05U工艺库安装

    以下资料摘自:<T13RF PDK簡介>-張文旭 观念与TSMC工艺库的安装 管理者安裝TSMC 0.13 MS/RF的環境下之PDK的安裝方式相當容易,首先以root的方式進入Unix/ ...

  7. Spring boot注解(annotation)含义详解

    Spring boot注解(annotation)含义详解 @Service用于标注业务层组件@Controller用于标注控制层组件(如struts中的action)@Repository用于标注数 ...

  8. 摘抄JPA官方文档原文 防呆

    Spring Data JPA - Reference Documentation Oliver GierkeThomas DarimontChristoph StroblMark PaluchVer ...

  9. Spring Hibernate JPA 联表查询 复杂查询(转)

    今天刷网,才发现: 1)如果想用hibernate注解,是不是一定会用到jpa的? 是.如果hibernate认为jpa的注解够用,就直接用.否则会弄一个自己的出来作为补充. 2)jpa和hibern ...

  10. CentOS 7 重装mysql编译过程报错解决方法

    错误记录: [ 82%] Building C object libmysql/CMakeFiles/clientlib.dir/__/sql-common/client.c.o/usr/local/ ...