Skip to content

Commit 0d8b396

Browse files
github-actions[bot]szabosteveAnaethelion
authored
[DOCS] Restructures the repo README (#697) (#699)
Co-authored-by: István Zoltán Szabó <[email protected]> Co-authored-by: Laurent Saint-Félix <[email protected]>
1 parent d279808 commit 0d8b396

File tree

1 file changed

+13
-323
lines changed

1 file changed

+13
-323
lines changed

README.md

Lines changed: 13 additions & 323 deletions
Original file line numberDiff line numberDiff line change
@@ -41,335 +41,25 @@ The `main` branch of the client is compatible with the current `master` branch o
4141

4242
## Installation
4343

44-
Add the package to your `go.mod` file:
45-
46-
require github.com/elastic/go-elasticsearch/v8 main
47-
48-
Or, clone the repository:
49-
50-
git clone --branch main https://github.com/elastic/go-elasticsearch.git $GOPATH/src/github.com/elastic/go-elasticsearch
51-
52-
A complete example:
53-
54-
```bash
55-
mkdir my-elasticsearch-app && cd my-elasticsearch-app
56-
57-
cat > go.mod <<-END
58-
module my-elasticsearch-app
59-
60-
require github.com/elastic/go-elasticsearch/v8 main
61-
END
62-
63-
cat > main.go <<-END
64-
package main
65-
66-
import (
67-
"log"
68-
69-
"github.com/elastic/go-elasticsearch/v8"
70-
)
71-
72-
func main() {
73-
es, _ := elasticsearch.NewDefaultClient()
74-
log.Println(elasticsearch.Version)
75-
log.Println(es.Info())
76-
}
77-
END
78-
79-
go run main.go
80-
```
81-
44+
Refer to the [Installation section](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_installation)
45+
of the getting started documentation.
8246

8347
<!-- ----------------------------------------------------------------------------------------------- -->
8448

85-
## Usage
86-
87-
The `elasticsearch` package ties together two separate packages for calling the Elasticsearch APIs and transferring data over HTTP: `esapi` and `elastictransport`, respectively.
88-
89-
Use the `elasticsearch.NewDefaultClient()` function to create the client with the default settings.
90-
91-
```golang
92-
es, err := elasticsearch.NewDefaultClient()
93-
if err != nil {
94-
log.Fatalf("Error creating the client: %s", err)
95-
}
96-
97-
res, err := es.Info()
98-
if err != nil {
99-
log.Fatalf("Error getting response: %s", err)
100-
}
101-
102-
defer res.Body.Close()
103-
log.Println(res)
104-
105-
// [200 OK] {
106-
// "name" : "node-1",
107-
// "cluster_name" : "go-elasticsearch"
108-
// ...
109-
```
110-
111-
> NOTE: It is _critical_ to both close the response body _and_ to consume it, in order to re-use persistent TCP connections in the default HTTP transport. If you're not interested in the response body, call `io.Copy(ioutil.Discard, res.Body)`.
112-
113-
When you export the `ELASTICSEARCH_URL` environment variable,
114-
it will be used to set the cluster endpoint(s). Separate multiple addresses by a comma.
115-
116-
To set the cluster endpoint(s) programmatically, pass a configuration object
117-
to the `elasticsearch.NewClient()` function.
118-
119-
```golang
120-
cfg := elasticsearch.Config{
121-
Addresses: []string{
122-
"https://localhost:9200",
123-
"https://localhost:9201",
124-
},
125-
// ...
126-
}
127-
es, err := elasticsearch.NewClient(cfg)
128-
```
129-
130-
To set the username and password, include them in the endpoint URL,
131-
or use the corresponding configuration options.
132-
133-
```golang
134-
cfg := elasticsearch.Config{
135-
// ...
136-
Username: "foo",
137-
Password: "bar",
138-
}
139-
```
140-
141-
To set a custom certificate authority used to sign the certificates of cluster nodes,
142-
use the `CACert` configuration option.
143-
144-
```golang
145-
cert, _ := ioutil.ReadFile(*cacert)
146-
147-
cfg := elasticsearch.Config{
148-
// ...
149-
CACert: cert,
150-
}
151-
```
152-
153-
To set a fingerprint to validate the HTTPS connection use the `CertificateFingerprint` configuration option.
154-
155-
```golang
156-
cfg := elasticsearch.Config{
157-
// ...
158-
CertificateFingerprint: fingerPrint,
159-
}
160-
```
161-
162-
To configure other HTTP settings, pass an [`http.Transport`](https://golang.org/pkg/net/http/#Transport)
163-
object in the configuration object.
164-
165-
```golang
166-
cfg := elasticsearch.Config{
167-
Transport: &http.Transport{
168-
MaxIdleConnsPerHost: 10,
169-
ResponseHeaderTimeout: time.Second,
170-
TLSClientConfig: &tls.Config{
171-
MinVersion: tls.VersionTLS12,
172-
// ...
173-
},
174-
// ...
175-
},
176-
}
177-
```
178-
179-
See the [`_examples/configuration.go`](_examples/configuration.go) and
180-
[`_examples/customization.go`](_examples/customization.go) files for
181-
more examples of configuration and customization of the client.
182-
See the [`_examples/security`](_examples/security) for an example of a security configuration.
183-
184-
The following example demonstrates a more complex usage. It fetches the Elasticsearch version from the cluster, indexes a couple of documents concurrently, and prints the search results, using a lightweight wrapper around the response body.
185-
186-
```golang
187-
// $ go run _examples/main.go
188-
189-
package main
190-
191-
import (
192-
"bytes"
193-
"context"
194-
"encoding/json"
195-
"log"
196-
"strconv"
197-
"strings"
198-
"sync"
199-
200-
"github.com/elastic/go-elasticsearch/v8"
201-
"github.com/elastic/go-elasticsearch/v8/esapi"
202-
)
203-
204-
func main() {
205-
log.SetFlags(0)
206-
207-
var (
208-
r map[string]interface{}
209-
wg sync.WaitGroup
210-
)
211-
212-
// Initialize a client with the default settings.
213-
//
214-
// An `ELASTICSEARCH_URL` environment variable will be used when exported.
215-
//
216-
es, err := elasticsearch.NewDefaultClient()
217-
if err != nil {
218-
log.Fatalf("Error creating the client: %s", err)
219-
}
220-
221-
// 1. Get cluster info
222-
//
223-
res, err := es.Info()
224-
if err != nil {
225-
log.Fatalf("Error getting response: %s", err)
226-
}
227-
defer res.Body.Close()
228-
// Check response status
229-
if res.IsError() {
230-
log.Fatalf("Error: %s", res.String())
231-
}
232-
// Deserialize the response into a map.
233-
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
234-
log.Fatalf("Error parsing the response body: %s", err)
235-
}
236-
// Print client and server version numbers.
237-
log.Printf("Client: %s", elasticsearch.Version)
238-
log.Printf("Server: %s", r["version"].(map[string]interface{})["number"])
239-
log.Println(strings.Repeat("~", 37))
240-
241-
// 2. Index documents concurrently
242-
//
243-
for i, title := range []string{"Test One", "Test Two"} {
244-
wg.Add(1)
245-
246-
go func(i int, title string) {
247-
defer wg.Done()
248-
249-
// Build the request body.
250-
data, err := json.Marshal(struct {
251-
Title string `json:"title"`
252-
}{Title: title})
253-
if err != nil {
254-
log.Fatalf("Error marshaling document: %s", err)
255-
}
256-
257-
// Set up the request object.
258-
req := esapi.IndexRequest{
259-
Index: "test",
260-
DocumentID: strconv.Itoa(i + 1),
261-
Body: bytes.NewReader(data),
262-
Refresh: "true",
263-
}
264-
265-
// Perform the request with the client.
266-
res, err := req.Do(context.Background(), es)
267-
if err != nil {
268-
log.Fatalf("Error getting response: %s", err)
269-
}
270-
defer res.Body.Close()
271-
272-
if res.IsError() {
273-
log.Printf("[%s] Error indexing document ID=%d", res.Status(), i+1)
274-
} else {
275-
// Deserialize the response into a map.
276-
var r map[string]interface{}
277-
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
278-
log.Printf("Error parsing the response body: %s", err)
279-
} else {
280-
// Print the response status and indexed document version.
281-
log.Printf("[%s] %s; version=%d", res.Status(), r["result"], int(r["_version"].(float64)))
282-
}
283-
}
284-
}(i, title)
285-
}
286-
wg.Wait()
287-
288-
log.Println(strings.Repeat("-", 37))
289-
290-
// 3. Search for the indexed documents
291-
//
292-
// Build the request body.
293-
var buf bytes.Buffer
294-
query := map[string]interface{}{
295-
"query": map[string]interface{}{
296-
"match": map[string]interface{}{
297-
"title": "test",
298-
},
299-
},
300-
}
301-
if err := json.NewEncoder(&buf).Encode(query); err != nil {
302-
log.Fatalf("Error encoding query: %s", err)
303-
}
304-
305-
// Perform the search request.
306-
res, err = es.Search(
307-
es.Search.WithContext(context.Background()),
308-
es.Search.WithIndex("test"),
309-
es.Search.WithBody(&buf),
310-
es.Search.WithTrackTotalHits(true),
311-
es.Search.WithPretty(),
312-
)
313-
if err != nil {
314-
log.Fatalf("Error getting response: %s", err)
315-
}
316-
defer res.Body.Close()
317-
318-
if res.IsError() {
319-
var e map[string]interface{}
320-
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
321-
log.Fatalf("Error parsing the response body: %s", err)
322-
} else {
323-
// Print the response status and error information.
324-
log.Fatalf("[%s] %s: %s",
325-
res.Status(),
326-
e["error"].(map[string]interface{})["type"],
327-
e["error"].(map[string]interface{})["reason"],
328-
)
329-
}
330-
}
331-
332-
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
333-
log.Fatalf("Error parsing the response body: %s", err)
334-
}
335-
// Print the response status, number of results, and request duration.
336-
log.Printf(
337-
"[%s] %d hits; took: %dms",
338-
res.Status(),
339-
int(r["hits"].(map[string]interface{})["total"].(map[string]interface{})["value"].(float64)),
340-
int(r["took"].(float64)),
341-
)
342-
// Print the ID and document source for each hit.
343-
for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
344-
log.Printf(" * ID=%s, %s", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"])
345-
}
346-
347-
log.Println(strings.Repeat("=", 37))
348-
}
349-
350-
// Client: 8.0.0-SNAPSHOT
351-
// Server: 8.0.0-SNAPSHOT
352-
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
353-
// [201 Created] updated; version=1
354-
// [201 Created] updated; version=1
355-
// -------------------------------------
356-
// [200 OK] 2 hits; took: 5ms
357-
// * ID=1, map[title:Test One]
358-
// * ID=2, map[title:Test Two]
359-
// =====================================
360-
```
361-
362-
As you see in the example above, the `esapi` package allows to call the Elasticsearch APIs in two distinct ways: either by creating a struct, such as `IndexRequest`, and calling its `Do()` method by passing it a context and the client, or by calling the `Search()` function on the client directly, using the option functions such as `WithIndex()`. See more information and examples in the
363-
[package documentation](https://godoc.org/github.com/elastic/go-elasticsearch/esapi).
364-
365-
The `elastictransport` package handles the transfer of data to and from Elasticsearch, including retrying failed requests, keeping a connection pool, discovering cluster nodes and logging.
49+
## Connecting
36650

367-
Read more about the client internals and usage in the following blog posts:
51+
Refer to the [Connecting section](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_connecting)
52+
of the getting started documentation.
36853

369-
* https://www.elastic.co/blog/the-go-client-for-elasticsearch-introduction
370-
* https://www.elastic.co/blog/the-go-client-for-elasticsearch-configuration-and-customization
371-
* https://www.elastic.co/blog/the-go-client-for-elasticsearch-working-with-data
54+
## Operations
37255

56+
* [Creating an index](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_creating_an_index)
57+
* [Indexing documents](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_indexing_documents)
58+
* [Getting documents](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_getting_documents)
59+
* [Searching documents](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_searching_documents)
60+
* [Updating documents](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_updating_documents)
61+
* [Deleting documents](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_deleting_documents)
62+
* [Deleting an index](https://www.elastic.co/guide/en/elasticsearch/client/go-api/current/getting-started-go.html#_deleting_an_index)
37363
<!-- ----------------------------------------------------------------------------------------------- -->
37464

37565
## Helpers

0 commit comments

Comments
 (0)