以下是一个简单的 Golang 代码示例,用于连接和查询 Elasticsearch:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strings"

    "github.com/elastic/go-elasticsearch/v7"
    "github.com/elastic/go-elasticsearch/v7/esapi"
)

func main() {
    // 创建 Elasticsearch 连接客户端实例
    es, err := elasticsearch.NewDefaultClient()
    if err != nil {
        log.Fatalf("Error creating the client: %s", err)
    }

    // 构建查询请求
    var (
        res *esapi.Response
        body map[string]interface{}
        r map[string]interface{}
    )
    res, err = es.Search(
        es.Search.WithContext(context.Background()),
        es.Search.WithIndex("my-index"),
        es.Search.WithBody(strings.NewReader(`{
          "query": {
            "match": {
              "message": "hello"
            }
          }
        }`)),
        es.Search.WithTrackTotalHits(true),
        es.Search.WithPretty(),
    )
    if err != nil {
        log.Fatalf("Error getting response: %s", err)
    }
    defer res.Body.Close()

    // 解析响应内容
    if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
        log.Fatalf("Error parsing the response body: %s", err)
    }
    // 解析 hits
    hits := body["hits"].(map[string]interface{})["hits"].([]interface{})
    for _, hit := range hits {
        r = hit.(map[string]interface{})["_source"].(map[string]interface{})
        fmt.Printf("Message: %s\n", r["message"])
    }
}

这个代码示例使用了 go-elasticsearch 库来连接 Elasticsearch,并执行了一个简单的查询请求。具体来说,它向名为 my-index 的索引中搜索包含 "hello" 的 message 字段的文档,并打印出每个文档的 message 字段。

当然,你也可以使用其他的 Elasticsearch 客户端库来连接 Elasticsearch。


原文地址: https://www.cveoy.top/t/topic/m9m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录