go数据操作-elasticsearch
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
)
func main() {
// 创建Elasticsearch客户端
es, err := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: 0,
},
})
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
// 1. 获取索引信息
res, err := es.Info(es.Info.WithContext(context.Background()))
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
fmt.Println(res)
// 2. 创建索引
var createIndexBody = `
{
"mappings": {
"properties": {
"message": {
"type": "text"
}
}
}
}`
createIndexRes, err := es.Indices.Create(
"my-index-000001",
es.Indices.Create.WithBody(strings.NewReader(createIndexBody)),
es.Indices.Create.WithPretty(),
)
if err != nil {
log.Fatalf("Error creating index: %s", err)
}
defer createIndexRes.Body.Close()
fmt.Println(createIndexRes)
// 3. 添加文档
var document = `
{
"message": "Hello, World!"
}`
put1Res, err := es.Index(
"my-index-000001",
strings.NewReader(document),
es.Index.WithDocumentID("1"),
es.Index.WithPretty(),
)
if err != nil {
log.Fatalf("Error putting document: %s", err)
}
defer put1Res.Body.Close()
fmt.Println(put1Res)
// 4. 更新文档
var updateDocument = `
{
"doc": { "message": "Goodbye, World!" }
}`
updateRes, err := es.Update(
"my-index-000001",
"1",
strings.NewReader(updateDocument),
es.Update.WithPretty(),
)
if err != nil {
log.Fatalf("Error updating document: %s", err)
}
defer updateRes.Body.Close()
fmt.Println(updateRes)
// 5. 获取文档
get1Res, err := es.Get(
"my-index-000001",
"1",
es.Get.WithPretty(),
)
if err != nil {
log.Fatalf("Error getting document: %s", err)
}
defer get1Res.Body.Close()
fmt.Println(get1Res)
// 6. 删除文档
deleteRes, err := es.Delete(
"my-index-000001",
"1",
es.Delete.WithPretty(),
)
if err != nil {
log.Fatalf("Error deleting document: %s", err)
}
defer deleteRes.Body.Close()
fmt.Println(deleteRes)
}
这段代码展示了如何使用Elast
评论已关闭