Go:如何获取ES数据

2024-07-11 10:20:03 浏览数 (3)

连接ES

  • 必要参数 [Addresses]ES连接地址 [Username]登录账号 [Password]登录账号密码
代码语言:javascript复制
addresses := []string{"http://es-logdata-cluster-n0.host.com:9200"}
	config := elasticsearch.Config{
		Addresses: addresses,
		Username:  "Username",
		Password:  "Password",
	}

	es, err := elasticsearch.NewClient(config)
	if err != nil {
		log.Error(err, "Error creating the es client")
	}

	res, err := es.Info()
	if err != nil {
		log.Error(err, "Error getting es response")
	}

获取数据

  • 必要的参数: [index]es索引名称 [body]请求体搜索,即request body search,简单来说就是query语句,示例如下:
代码语言:javascript复制
{
  "query": {
    "filtered": {
      "filter": {
1        { "term": { "brand": "gucci" }}
      }
    }
  },
  "aggs": {
    "colors": {
2      "terms": { "field": "color" },
    },
    "color_red": {
      "filter": {
3        "term": { "color": "red" }
      },
      "aggs": {
        "models": {
4          "terms": { "field": "model" }
        }
      }
    }
  },
5  "post_filter": {
    "term": { "color": "red" },
  }
}

[num]要获取查询结果的条数

代码语言:javascript复制
buf := strings.NewReader(body)
	res, err = es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex(index),
		es.Search.WithIgnoreUnavailable(true),
		es.Search.WithBody(buf),
		es.Search.WithPretty(),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithSize(num),
	)

	if err != nil {
		fmt.Println("err: ", err)
		log.Error(err, "Error getting response")
	}

	defer res.Body.Close()
	return  res.String()

0 人点赞