|
| 1 | +[[connecting]] |
| 2 | +== Connecting |
| 3 | + |
| 4 | +This page contains the information you need to connect and use the Client with |
| 5 | +{es}. |
| 6 | + |
| 7 | +**On this page** |
| 8 | + |
| 9 | +* <<auth-reference, Authentication options>> |
| 10 | +* <<client-usage, Using the client>> |
| 11 | + |
| 12 | +[discrete] |
| 13 | +[[auth-reference]] |
| 14 | +=== Authentication |
| 15 | + |
| 16 | +This document contains code snippets to show you how to connect to various {es} |
| 17 | +providers. |
| 18 | + |
| 19 | + |
| 20 | +[discrete] |
| 21 | +[[auth-basic]] |
| 22 | +==== Basic authentication |
| 23 | + |
| 24 | +To set the cluster endpoints, the username, and the password programatically, pass a configuration object to the `elasticsearch.NewClient()` function. |
| 25 | + |
| 26 | +[source,go] |
| 27 | +------------------------------------ |
| 28 | +cfg := elasticsearch.Config{ |
| 29 | + Addresses: []string{ |
| 30 | + "http://localhost:9200", |
| 31 | + "http://localhost:9201", |
| 32 | + }, |
| 33 | + Username: "foo", |
| 34 | + Password: "bar", |
| 35 | +} |
| 36 | +es, err := elasticsearch.NewClient(cfg) |
| 37 | +------------------------------------ |
| 38 | + |
| 39 | +You can also include the username and password in the endpoint URL: |
| 40 | + |
| 41 | +``` |
| 42 | +'https://username:password@localhost:9200' |
| 43 | +``` |
| 44 | + |
| 45 | + |
| 46 | +[discrete] |
| 47 | +[[auth-ec]] |
| 48 | +==== Elastic Cloud |
| 49 | + |
| 50 | +If you are using https://www.elastic.co/cloud[Elastic Cloud], the client offers |
| 51 | +an easy way to connect to it. You must pass the Cloud ID that you can find in |
| 52 | +the cloud console and the corresponding API key. |
| 53 | + |
| 54 | +[source,go] |
| 55 | +------------------------------------ |
| 56 | +cfg := elasticsearch.Config{ |
| 57 | + CloudID: "CLOUD_ID", |
| 58 | + APIKey: "API_KEY" |
| 59 | +} |
| 60 | +es, err := elasticsearch.NewClient(cfg) |
| 61 | +------------------------------------ |
| 62 | + |
| 63 | + |
| 64 | +[discrete] |
| 65 | +[[client-usage]] |
| 66 | +=== Using the client |
| 67 | + |
| 68 | +The {es} package ties together two separate packages for calling the Elasticsearch APIs and transferring data over HTTP: `esapi` and `estransport`, respectively. |
| 69 | + |
| 70 | +Use the `elasticsearch.NewDefaultClient()` function to create the client with the default settings. |
| 71 | + |
| 72 | +[source,go] |
| 73 | +------------------------------------ |
| 74 | +es, err := elasticsearch.NewDefaultClient() |
| 75 | +if err != nil { |
| 76 | + log.Fatalf("Error creating the client: %s", err) |
| 77 | +} |
| 78 | +
|
| 79 | +res, err := es.Info() |
| 80 | +if err != nil { |
| 81 | + log.Fatalf("Error getting response: %s", err) |
| 82 | +} |
| 83 | +
|
| 84 | +defer res.Body.Close() |
| 85 | +log.Println(res) |
| 86 | +------------------------------------ |
0 commit comments