Go整合ElasticSearch的示例代碼
go整合elasticsearch
基于docker搭建開(kāi)發(fā)環(huán)境
在開(kāi)發(fā)之前我們首先需要借助docker來(lái)構(gòu)建我們的開(kāi)發(fā)環(huán)境,先創(chuàng)建一個(gè)文件名稱為docker-compose.yaml, 里面寫(xiě)入下面的內(nèi)容:
--- version: "3" services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.10.0 container_name: es01 environment: - node.name=es01 - cluster.name=docker-cluster - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - discovery.type=single-node ulimits: memlock: soft: -1 hard: -1 volumes: - esdata:/usr/share/elasticsearch/data ports: - 9200:9200 kibana: image: docker.elastic.co/kibana/kibana:7.10.0 ports: - 5601:5601 depends_on: - elasticsearch volumes: esdata: driver: local
使用docker-compose up -d 啟動(dòng)容器,之后在瀏覽器中分別驗(yàn)證es和kibana的運(yùn)行狀態(tài)
驗(yàn)證es:http://localhost:9200/
驗(yàn)證kibana:http://localhost:5601
檢查客戶端api
package main import ( "fmt" "github.com/elastic/go-elasticsearch/v7" ) func main() { es, err := elasticsearch.NewDefaultClient() if err != nil { fmt.Println(err) return } res, err := es.Info() if err != nil { fmt.Println(err) return } defer res.Body.Close() fmt.Println(res) }
索引相關(guān)操作
創(chuàng)建索引
package main import ( "context" "fmt" "github.com/elastic/go-elasticsearch/v7" "log" ) func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } indexName := "test_20230726" res, err := es.Indices.Create( indexName, es.Indices.Create.WithContext(context.Background()), es.Indices.Create.WithPretty()) if err != nil { log.Fatalf("Error creating the index: %s", err) } defer res.Body.Close() fmt.Println(res.String()) }
刪除索引
package main import ( "context" "fmt" "github.com/elastic/go-elasticsearch/v7" "log" ) func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } indexName := "test_20230726" res, err := es.Indices.Delete( []string{indexName}, es.Indices.Delete.WithContext(context.Background()), es.Indices.Delete.WithIgnoreUnavailable(true), es.Indices.Delete.WithPretty(), ) if err != nil { log.Fatalf("Error deleting the index: %s", err) } defer res.Body.Close() fmt.Println(res.String()) }
修改索引
package main import ( "bytes" "context" "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v7" "github.com/elastic/go-elasticsearch/v7/esapi" "log" ) func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } indexName := "your_index_name" documentID := "your_document_id" // 準(zhǔn)備文檔數(shù)據(jù) doc := Document{ Title: "Document Title", Body: "This is the body of the document.", } // 將文檔數(shù)據(jù)序列化為JSON字節(jié) data, err := json.Marshal(doc) if err != nil { log.Fatalf("Error marshaling document: %s", err) } // 創(chuàng)建PUT請(qǐng)求 req := esapi.IndexRequest{ Index: indexName, DocumentID: documentID, Body: bytes.NewReader(data), } // 發(fā)送PUT請(qǐng)求 res, err := req.Do(context.Background(), es) if err != nil { log.Fatalf("Error indexing document: %s", err) } defer res.Body.Close() fmt.Println(res.String()) }
查詢索引列表
package main import ( "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v7" "log" ) func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } res, err := es.Indices.Get([]string{"_all"}) if err != nil { log.Fatalf("Error getting indices: %s", err) } defer res.Body.Close() if res.IsError() { log.Fatalf("Error response: %s", res.String()) } var result map[string]interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatalf("Error parsing the response body: %s", err) } indices, ok := result["test_20230726"].(map[string]interface{}) if !ok { log.Fatalf("Invalid indices format in the response") } for index := range indices { fmt.Println(index) } }
插入文檔
package main import ( "bytes" "context" "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v7" "github.com/elastic/go-elasticsearch/v7/esapi" "log" ) type Document struct { Title string `json:"title"` Body string `json:"body"` } func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } indexName := "test_20230726" documentID := "20230726" doc := Document{ Title: "Document Title", Body: "This is the body of the document.", } data, err := json.Marshal(doc) if err != nil { log.Fatalf("Error marshaling document: %s", err) } req := esapi.IndexRequest{ Index: indexName, DocumentID: documentID, Body: bytes.NewReader(data), } res, err := req.Do(context.Background(), es) if err != nil { log.Fatalf("Error indexing document: %s", err) } defer res.Body.Close() fmt.Println(res.String())
參考資料
https://cloud.tencent.com/developer/article/1911255
到此這篇關(guān)于Go整合ElasticSearch的文章就介紹到這了,更多相關(guān)Go整合ElasticSearch內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang設(shè)計(jì)模式之原型模式詳細(xì)講解
如果一個(gè)類的有非常多的屬性,層級(jí)還很深。每次構(gòu)造起來(lái),不管是直接構(gòu)造還是用建造者模式,都要對(duì)太多屬性進(jìn)行復(fù)制,那么有沒(méi)有一種好的方式讓我們創(chuàng)建太的時(shí)候使用體驗(yàn)更好一點(diǎn)呢? 今天的文章里就給大家介紹一種設(shè)計(jì)模式,來(lái)解決這個(gè)問(wèn)題2023-01-01go select編譯期的優(yōu)化處理邏輯使用場(chǎng)景分析
select 是 Go 中的一個(gè)控制結(jié)構(gòu),類似于用于通信的 switch 語(yǔ)句。每個(gè) case 必須是一個(gè)通信操作,要么是發(fā)送要么是接收。接下來(lái)通過(guò)本文給大家介紹go select編譯期的優(yōu)化處理邏輯使用場(chǎng)景分析,感興趣的朋友一起看看吧2021-06-06Go語(yǔ)言實(shí)現(xiàn)websocket推送程序
這篇文章主要介紹了Go語(yǔ)言實(shí)現(xiàn)websocket推送程序,WebSocket是基于TCP的一個(gè)雙向傳輸數(shù)據(jù)的協(xié)議,和HTTP協(xié)議一樣,是在應(yīng)用層的,他的出現(xiàn),是為了解決網(wǎng)頁(yè)進(jìn)行持久雙向傳輸數(shù)據(jù)的問(wèn)題2023-01-01Go語(yǔ)言生成UUID的利器(github.com/google/uuid)
UUID是確保每個(gè)元素唯一性的重要工具,Go語(yǔ)言雖然在標(biāo)準(zhǔn)庫(kù)中沒(méi)有直接提供UUID生成功能,但可以通過(guò)安裝github.com/google/uuid庫(kù)來(lái)實(shí)現(xiàn),本文就來(lái)介紹一下,感興趣的可以了解一下2024-11-11在Go網(wǎng)絡(luò)請(qǐng)求中配置代理的方法詳解
這篇文章主要給大家介紹了如何在Go網(wǎng)絡(luò)請(qǐng)求中配置代理的方法,文章通過(guò)代碼示例介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-09-09Go語(yǔ)言實(shí)現(xiàn)的樹(shù)形結(jié)構(gòu)數(shù)據(jù)比較算法實(shí)例
這篇文章主要介紹了Go語(yǔ)言實(shí)現(xiàn)的樹(shù)形結(jié)構(gòu)數(shù)據(jù)比較算法,實(shí)例分析了樹(shù)形結(jié)構(gòu)數(shù)據(jù)比較算法的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02