golang实现 elastic demo

使用 CloudID 和 APIKey 连接到 Elasticsearch 云实例

package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "github.com/elastic/go-elasticsearch/v8"
    "log"
    "time"
)

//TIP To run your code, right-click the code and select <b>Run</b>. Alternatively, click
// the <icon src="AllIcons.Actions.Execute"/> icon in the gutter and select the <b>Run</b> menu item from here.

type Document struct {
    Title       string    `json:"title"`
    Description string    `json:"description"`
    CreatedAt   time.Time `json:"created_at"`
}

const IndexName = "documents"

var Es *elasticsearch.Client

func init() {
    cfg := elasticsearch.Config{
        CloudID: "********",
        APIKey:  "*******",
    }

    var err error
    Es, err = elasticsearch.NewClient(cfg)
    if err != nil {
        log.Fatalf("Error creating the Elasticsearch client: %s", err)
    }

    // You can test the connection by pinging the Elasticsearch cluster
    res, err := Es.Info()
    if err != nil {
        log.Fatalf("Error getting Elasticsearch info: %s", err)
    }
    defer res.Body.Close()
    fmt.Println(res.String())
}
func main() {
    docId := addDocument()
    fmt.Println(getDocument(docId))
    updateDocument(docId)
    searchDocument("Golang")
}

//TIP See GoLand help at <a href="https://www.jetbrains.com/help/go/">jetbrains.com/help/go/</a>.
// Also, you can try interactive lessons for GoLand by selecting 'Help | Learn IDE Features' from the main menu.

func addDocument() string {
    // Document to index (Create)
    doc := Document{
        Title:       "Elasticsearch with Golang",
        Description: "A document about using Elasticsearch with Golang.",
        CreatedAt:   time.Now(),
    }

    docJson, err := json.Marshal(doc)
    if err != nil {
        log.Fatalf("Error marshaling the document: %s", err)
    }
    fmt.Println(docJson)
    res, err := Es.Index(IndexName, bytes.NewReader(docJson))
    if err != nil {
        log.Fatalf("Error indexing the document: %s", err)
    }
    defer res.Body.Close()
    var r map[string]interface{}
    if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
        log.Fatalf("Error parsing the response: %s", err)
    }

    return r["_id"].(string)
}

func getDocument(docId string) *Document {
    res, err := Es.Get(IndexName, docId)
    if err != nil {
        log.Fatalf("Error getting the document: %s", err)
    }
    defer res.Body.Close()
    var r map[string]interface{}
    if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
        log.Fatalf("Error parsing the response: %s", err)
    }
    source, _ := json.Marshal(r["_source"])
    var doc Document
    json.Unmarshal(source, &doc)

    return &doc
}

func updateDocument(docId string) *Document {
    // Document to index (Create)
    doc := Document{
        Title:       "Elasticsearch with Golang",
        Description: "A document about using Elasticsearch with Golang.",
        CreatedAt:   time.Now(),
    }
    update := map[string]interface{}{
        "doc": map[string]interface{}{
            "description": "Updated description for the document.",
            "created_at":  doc.CreatedAt,
        },
    }

    updateJSON, _ := json.Marshal(update)
    res, err := Es.Update(IndexName, docId, bytes.NewReader(updateJSON))
    if err != nil {
        log.Fatalf("Error updating the document: %s", err)
    }
    defer res.Body.Close()
    return getDocument(docId)
}

func deleteDocument(docId string) {
    res, err := Es.Delete(IndexName, docId)
    if err != nil {
        log.Fatalf("Error deleting the document: %s", err)
    }
    defer res.Body.Close()
    if res.IsError() {
        log.Fatalf("Error response from Elasticsearch: %s", res.Status())
    }
}

func searchDocument(query string) {
    searchQuery := map[string]interface{}{
        "query": map[string]interface{}{
            "match": map[string]interface{}{
                "title": query,
            },
        },
    }
    var buf bytes.Buffer
    if err := json.NewEncoder(&buf).Encode(searchQuery); err != nil {
        log.Fatalf("Error encoding query: %s", err)
    }
    res, err := Es.Search(
        Es.Search.WithContext(context.Background()),
        Es.Search.WithIndex(IndexName),
        Es.Search.WithBody(&buf),
        Es.Search.WithTrackTotalHits(true),
        Es.Search.WithPretty(),
    )
    if err != nil {
        log.Fatalf("Error getting response: %s", err)
    }
    defer res.Body.Close()
    fmt.Println(res.String())
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容