go整合elasticsearch
- 基于docker搭建开发环境
在开发之前我们首先需要借助docker来构建我们的开发环境,先创建一个文件名称为docker-compose.yaml, 里面写入下面的内容:
---
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 启动容器,之后在浏览器中分别验证es和kibana的运行状态
验证es:http://localhost:9200/
验证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)
}
- 索引相关操作
- 创建索引
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"
// 准备文档数据
doc := Document{
Title: "Document Title",
Body: "This is the body of the document.",
}
// 将文档数据序列化为JSON字节
data, err := json.Marshal(doc)
if err != nil {
log.Fatalf("Error marshaling document: %s", err)
}
// 创建PUT请求
req := esapi.IndexRequest{
Index: indexName,
DocumentID: documentID,
Body: bytes.NewReader(data),
}
// 发送PUT请求
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())
- 单元测试补充案例
package es
import (
"context"
"encoding/json"
"fmt"
es8 "github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/update"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
"testing"
)
var (
cli *es8.TypedClient
)
func init() {
config := es8.Config{
Addresses: []string{"http://127.0.0.1:9200"},
}
client, err := es8.NewTypedClient(config)
if err != nil {
panic(err)
}
cli = client
}
func TestCreateIndex(t *testing.T) {
resp, err := cli.Indices.Create("one").Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestDeleteIndex(t *testing.T) {
resp, err := cli.Indices.Delete("one").Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestQueryIndexIsExist(t *testing.T) {
resp, err := cli.Indices.Exists("one").Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestQueryAllIndex(t *testing.T) {
}
func TestCreateIndexBelongedDoc(t *testing.T) {
documentID := "2"
document := map[string]interface{}{
"title": "Example Document",
"content": "This is an example document.",
"author": "John Doe",
"date": "2022-01-01",
"tags": []string{"example", "document"},
"views": 100,
"rating": 4.5,
}
resp, err := cli.Index("my-index").Id(documentID).Document(document).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestUpdateIndexBelongedDoc(t *testing.T) {
str := `{
"author": "6666",
"content": "This is an example document.",
"date": "2022-01-01",
"rating": 4.5,
"tags": [
"example",
"document"
],
"title": "Example Document",
"views": 100
}`
resp, err := cli.Update("my-index", "1").Request(&update.Request{Doc: json.RawMessage(str)}).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestDeleteIndexBelongedDoc(t *testing.T) {
resp, err := cli.Delete("my-index", "2").Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(resp)
}
func TestQueryIndexBelongedDoc(t *testing.T) {
resp, err := cli.Get("my-index", "1").Do(context.Background())
if err != nil {
panic(err)
}
fmt.Println(string(resp.Source_))
}
func TestQueryIndexBelongedDocByCondition(t *testing.T) {
resp, err := cli.Search().Index("my-index").Request(&search.Request{Query: &types.Query{MatchAll: &types.MatchAllQuery{}}}).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("total: %d\n", resp.Hits.Total.Value)
for _, hit := range resp.Hits.Hits {
fmt.Printf("%s\n", hit.Source_)
}
}
参考资料
- https://cloud.tencent.com/developer/article/1911255