go語言操作es的實(shí)現(xiàn)示例
Elasticsearch
介紹
Elasticsearch(ES)是一個(gè)基于Lucene構(gòu)建的開源、分布式、RESTful接口的全文搜索引擎。Elasticsearch還是一個(gè)分布式文檔數(shù)據(jù)庫(kù),其中每個(gè)字段均可被索引,而且每個(gè)字段的數(shù)據(jù)均可被搜索,ES能夠橫向擴(kuò)展至數(shù)以百計(jì)的服務(wù)器存儲(chǔ)以及處理PB級(jí)的數(shù)據(jù)??梢栽跇O短的時(shí)間內(nèi)存儲(chǔ)、搜索和分析大量的數(shù)據(jù)。通常作為具有復(fù)雜搜索場(chǎng)景情況下的核心發(fā)動(dòng)機(jī)。
Elasticsearch能做什么
- 當(dāng)你經(jīng)營(yíng)一家網(wǎng)上商店,你可以讓你的客戶搜索你賣的商品。在這種情況下,你可以使用ElasticSearch來存儲(chǔ)你的整個(gè)產(chǎn)品目錄和庫(kù)存信息,為客戶提供精準(zhǔn)搜索,可以為客戶推薦相關(guān)商品。
- 當(dāng)你想收集日志或者交易數(shù)據(jù)的時(shí)候,需要分析和挖掘這些數(shù)據(jù),尋找趨勢(shì),進(jìn)行統(tǒng)計(jì),總結(jié),或發(fā)現(xiàn)異常。在這種情況下,你可以使用Logstash或者其他工具來進(jìn)行收集數(shù)據(jù),當(dāng)這引起數(shù)據(jù)存儲(chǔ)到ElasticsSearch中。你可以搜索和匯總這些數(shù)據(jù),找到任何你感興趣的信息。
- 對(duì)于程序員來說,比較有名的案例是GitHub,GitHub的搜索是基于ElasticSearch構(gòu)建的,在github.com/search頁(yè)面,你可以搜索項(xiàng)目、用戶、issue、pull request,還有代碼。共有40~50個(gè)索引庫(kù),分別用于索引網(wǎng)站需要跟蹤的各種數(shù)據(jù)。雖然只索引項(xiàng)目的主分支(master),但這個(gè)數(shù)據(jù)量依然巨大,包括20億個(gè)索引文檔,30TB的索引文件。
go語言操作es
go get github.com/olivere/elastic
解決golang使用elastic連接elasticsearch時(shí)自動(dòng)轉(zhuǎn)換連接地址

elastic.SetSniff(false)
client, _ := elastic.NewClient( // ... // 將sniff設(shè)置為false后,便不會(huì)自動(dòng)轉(zhuǎn)換地址 elastic.SetSniff(false), )

初始化
var client *elastic.Client
var host = "http://xxx:9200"
//初始化es驅(qū)動(dòng)
func init() {
errorlog := log.New(os.Stdout, "app", log.LstdFlags)
var err error
client, err = elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(host), elastic.SetSniff(false))
if err != nil {
panic(err)
}
info, code, err := client.Ping(host).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("Es return with code %d and version %s \n", code, info.Version.Number)
esversionCode, err := client.ElasticsearchVersion(host)
if err != nil {
panic(err)
}
fmt.Printf("es version %s\n", esversionCode)
}
數(shù)據(jù)創(chuàng)建
info —>employee -------FirstName,LastName,Age,About,Interests
結(jié)構(gòu)體方式
type Employee struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Age int `json:"age"`
About string `json:"about"`
Interests []string `json:"interests"`
}
//創(chuàng)建索引
func create() {
//1.使用結(jié)構(gòu)體方式存入到es里面
e1 := Employee{"jane", "Smith", 20, "I like music", []string{"music"}}
put, err := client.Index().Index("info").Type("employee").Id("1").BodyJson(e1).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("indexed %d to index %s, type %s \n", put.Id, put.Index, put.Type)
}
func main() {
create()
}
字符串方式:
func create1() {
//使用字符串
e1 := `{"firstname":"john","lastname":"smith","age":22,"about":"i like book","interests":["book","music"]}`
put, err := client.Index().Index("info").Type("employee").Id("2").BodyJson(e1).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("indexed %d to index %s, type %s \n", put.Id, put.Index, put.Type)
}
查找
//查找
func get() {
get, err := client.Get().Index("info").Type("employee").Id("1").Do(context.Background())
if err != nil {
panic(err)
}
if get.Found {
fmt.Printf("got document %s in version %d from index %s,type %s \n", get.Id, get.Version, get.Index, get.Type)
}
}
func main() {
get()
}
修改
func update() {
res, err := client.Update().Index("info").Type("employee").Id("1").Doc(map[string]interface{}{"age": 88}).Do(context.Background())
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("update age %s \n", res.Result)
}
func main() {
update()
}
刪除
//刪除
func delete() {
res, err := client.Delete().Index("info").Type("employee").Id("1").Do(context.Background())
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("delete result %s", res.Result)
}
func main() {
delete()
}
查找
func query() {
var res *elastic.SearchResult
var err error
res, err = client.Search("info").Type("employee").Do(context.Background())
printEmployee(res, err)
}
//打印查詢的employee
func printEmployee(res *elastic.SearchResult, err error) {
if err != nil {
fmt.Print(err.Error())
return
}
var typ Employee
for _, item := range res.Each(reflect.TypeOf(typ)) {
t := item.(Employee)
fmt.Printf("%#v\n", t)
}
}
//條件查找
func query1() {
var res *elastic.SearchResult
var err error
//查找方式一:
q := elastic.NewQueryStringQuery("lastname:smith")
res, err = client.Search("info").Type("employee").Query(q).Do(context.Background())
printEmployee(res, err)
//查找方法二:
if res.Hits.TotalHits > 0 {
fmt.Printf("found a total fo %d Employee", res.Hits.TotalHits)
for _, hit := range res.Hits.Hits {
var t Employee
err := json.Unmarshal(*hit.Source, &t) //另一種取出的方法
if err != nil {
fmt.Println("failed")
}
fmt.Printf("employee name %s:%s\n", t.FirstName, t.LastName)
}
} else {
fmt.Printf("found no employee \n")
}
}
年齡大于21的查找
//年齡大于21的
func query3() {
var res *elastic.SearchResult
var err error
boolq := elastic.NewBoolQuery()
boolq.Must(elastic.NewMatchQuery("lastname", "smith"))
boolq.Filter(elastic.NewRangeQuery("age").Gt(21))
res, err = client.Search("info").Type("employee").Query(boolq).Do(context.Background())
printEmployee(res, err)
}
//打印查詢的employee
func printEmployee(res *elastic.SearchResult, err error) {
if err != nil {
fmt.Print(err.Error())
return
}
var typ Employee
for _, item := range res.Each(reflect.TypeOf(typ)) {
t := item.(Employee)
fmt.Printf("%#v\n", t)
}
}
包含book的
//包含book的
func query4() {
var res *elastic.SearchResult
var err error
matchPhrase := elastic.NewMatchPhraseQuery("about", "book")
res, err = client.Search("info").Type("employee").Query(matchPhrase).Do(context.Background())
printEmployee(res, err)
}
分頁(yè)
//分頁(yè)
func list(size, page int) {
var res *elastic.SearchResult
var err error
if size < 0 || page < 1 {
fmt.Printf("param error")
return
}
res, err = client.Search("info").Type("employee").Size(size).From((page - 1) * size).Do(context.Background())
printEmployee(res, err)
}
集群搭建
配置文件修改
node.name : node-102 node.name : node-103 network.host: 192.168.1.102 network.host: 192.168.1.103 discovery.zen.ping.unicast.hosts: ["s201","s202","s203"]


到此這篇關(guān)于go語言操作es的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)go語言操作es內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang實(shí)現(xiàn)簡(jiǎn)易的分布式系統(tǒng)方法
這篇文章主要介紹了golang實(shí)現(xiàn)簡(jiǎn)易的分布式系統(tǒng)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10
golang中拿slice當(dāng)queue和拿list當(dāng)queue使用分析
這篇文章主要為大家介紹了golang?中拿slice當(dāng)queue和拿list當(dāng)queue使用分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
golang中實(shí)現(xiàn)graphql請(qǐng)求的方法
這篇文章主要介紹了如何在golang中實(shí)現(xiàn)graphql請(qǐng)求,在本文中,我們介紹了如何使用gqlgen來構(gòu)建GraphQL服務(wù),需要的朋友可以參考下2023-04-04
Golang?Template實(shí)現(xiàn)自定義函數(shù)的操作指南
這篇文章主要為大家詳細(xì)介紹了Golang如何利用Template實(shí)現(xiàn)自定義函數(shù)的操作,文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-02-02
Go語言Gin框架實(shí)現(xiàn)HTML頁(yè)面渲染
Web開發(fā)中,我們經(jīng)常要面對(duì)如何將數(shù)據(jù)渲染到前端的問題,這就涉及到了模板引擎的知識(shí),Go語言的Gin框架就提供了強(qiáng)大的HTML模板渲染功能,本文就來為大家介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助2024-01-01
golang API請(qǐng)求隊(duì)列的實(shí)現(xiàn)
本文主要介紹了golang API請(qǐng)求隊(duì)列的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04

