Accessing an Elasticsearch Cluster Using Go

This section describes how to access a CSS cluster using Go.

Preparations

Connecting to a Non-Security Mode Cluster

Connect to a non-security mode cluster. The sample code is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"github.com/elastic/go-elasticsearch/v7"
	"log"
)

func main() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://HOST:9200/",
		},
	}

	es, _ := elasticsearch.NewClient(cfg)
	log.Println(es.Info())
}

In the information above, HOST indicates the internal IP address of a cluster node.

Connecting to a Security-Mode Cluster

Table 1 Variables

Parameter

Description

HOST

IP address for accessing the Elasticsearch cluster. If there are multiple IP addresses, separate them with commas (,).

USERNAME

Username for accessing the cluster.

PASSWORD

Password of the user.

Running Code

Write the code above to the EsTest.gc file based on the cluster type and save the file to an independent directory. Run the following command in that directory to run the code:

go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.io,direct 
go env -w GONOSUMDB=*

go mod init test
go mod tidy
go run EsTest.go