未验证 提交 bfed3a6b 编写于 作者: H huanggze

update dependencies

Signed-off-by: Nhuanggze <loganhuang@yunify.com>
上级 70293cc6
......@@ -32,6 +32,9 @@ require (
github.com/docker/go-connections v0.3.0 // indirect
github.com/docker/go-units v0.3.3 // indirect
github.com/docker/spdystream v0.0.0-20181023171402-6480d4af844c // indirect
github.com/elastic/go-elasticsearch/v5 v5.6.1
github.com/elastic/go-elasticsearch/v6 v6.8.2
github.com/elastic/go-elasticsearch/v7 v7.3.0
github.com/elazarl/go-bindata-assetfs v1.0.0 // indirect
github.com/elazarl/goproxy v0.0.0-20190711103511-473e67f1d7d2 // indirect
github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 // indirect
......@@ -210,6 +213,9 @@ replace (
github.com/eapache/go-resiliency => github.com/eapache/go-resiliency v1.1.0
github.com/eapache/go-xerial-snappy => github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21
github.com/eapache/queue => github.com/eapache/queue v1.1.0
github.com/elastic/go-elasticsearch/v5 => github.com/elastic/go-elasticsearch/v5 v5.6.1
github.com/elastic/go-elasticsearch/v6 => github.com/elastic/go-elasticsearch/v6 v6.8.2
github.com/elastic/go-elasticsearch/v7 => github.com/elastic/go-elasticsearch/v7 v7.3.0
github.com/elazarl/go-bindata-assetfs => github.com/elazarl/go-bindata-assetfs v1.0.0
github.com/elazarl/goproxy => github.com/elazarl/goproxy v0.0.0-20190711103511-473e67f1d7d2
github.com/elazarl/goproxy/ext => github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2
......
......@@ -507,7 +507,7 @@ func syncFluentbitCRDOutputWithConfigMap(outputs []fb.OutputPlugin) error {
}
// Parse es host, port and index
func ParseEsOutputParams(params []fb.Parameter) *es.ESConfigs {
func ParseEsOutputParams(params []fb.Parameter) *es.Config {
var (
isEsFound bool
......@@ -551,5 +551,5 @@ func ParseEsOutputParams(params []fb.Parameter) *es.ESConfigs {
}
}
return &es.ESConfigs{Host: host, Port: port, Index: index}
return &es.Config{Host: host, Port: port, Index: index}
}
......@@ -13,11 +13,9 @@ limitations under the License.
package esclient
import (
"bytes"
"encoding/json"
"fmt"
"github.com/golang/glog"
"io/ioutil"
"net/http"
"strconv"
"strings"
......@@ -30,28 +28,31 @@ import (
var jsonIter = jsoniter.ConfigCompatibleWithStandardLibrary
var (
mu sync.RWMutex
esConfigs *ESConfigs
)
type ESConfigs struct {
Host string
Port string
Index string
}
mu sync.Mutex
config *Config
func readESConfigs() *ESConfigs {
mu.RLock()
defer mu.RUnlock()
client Client
)
return esConfigs
type Config struct {
Host string
Port string
Index string
VersionMajor string
}
func (configs *ESConfigs) WriteESConfigs() {
func (cfg *Config) WriteESConfigs() {
mu.Lock()
defer mu.Unlock()
esConfigs = configs
config = cfg
if err := detectVersionMajor(config); err != nil {
glog.Errorln(err)
client = nil
return
}
client = NewForConfig(config)
}
type Request struct {
......@@ -303,8 +304,9 @@ type Shards struct {
}
type Hits struct {
Total int64 `json:"total"`
Hits []Hit `json:"hits"`
// As of ElasticSearch v7.x, hits.total is changed
Total interface{} `json:"total"`
Hits []Hit `json:"hits"`
}
type Hit struct {
......@@ -457,7 +459,7 @@ func parseQueryResult(operation int, param QueryParameters, body []byte, query [
switch operation {
case OperationQuery:
var readResult ReadResult
readResult.Total = response.Hits.Total
readResult.Total = client.GetTotalHitCount(response.Hits.Total)
readResult.From = param.From
readResult.Size = param.Size
for _, hit := range response.Hits.Hits {
......@@ -476,24 +478,24 @@ func parseQueryResult(operation int, param QueryParameters, body []byte, query [
case OperationStatistics:
var statisticsResponse StatisticsResponseAggregations
err := jsonIter.Unmarshal(response.Aggregations, &statisticsResponse)
if err != nil {
if err != nil && response.Aggregations != nil {
glog.Errorln(err)
queryResult.Status = http.StatusInternalServerError
queryResult.Error = err.Error()
return &queryResult
}
queryResult.Statistics = &StatisticsResult{Containers: statisticsResponse.ContainerCount.Value, Logs: response.Hits.Total}
queryResult.Statistics = &StatisticsResult{Containers: statisticsResponse.ContainerCount.Value, Logs: client.GetTotalHitCount(response.Hits.Total)}
case OperationHistogram:
var histogramResult HistogramResult
histogramResult.Total = response.Hits.Total
histogramResult.Total = client.GetTotalHitCount(response.Hits.Total)
histogramResult.StartTime = calcTimestamp(param.StartTime)
histogramResult.EndTime = calcTimestamp(param.EndTime)
histogramResult.Interval = param.Interval
var histogramAggregations HistogramAggregations
err := jsonIter.Unmarshal(response.Aggregations, &histogramAggregations)
if err != nil {
if err != nil && response.Aggregations != nil {
glog.Errorln(err)
queryResult.Status = http.StatusInternalServerError
queryResult.Error = err.Error()
......@@ -541,58 +543,25 @@ type QueryParameters struct {
Size int64
}
func stubResult() *QueryResult {
var queryResult QueryResult
queryResult.Status = http.StatusOK
return &queryResult
}
func Query(param QueryParameters) *QueryResult {
var queryResult *QueryResult
client := &http.Client{}
var queryResult = new(QueryResult)
operation, query, err := createQueryRequest(param)
if err != nil {
queryResult = new(QueryResult)
queryResult.Status = http.StatusInternalServerError
queryResult.Error = err.Error()
if client == nil {
queryResult.Status = http.StatusBadRequest
queryResult.Error = fmt.Sprintf("Invalid elasticsearch address: host=%s, port=%s", config.Host, config.Port)
return queryResult
}
es := readESConfigs()
if es == nil {
queryResult = new(QueryResult)
queryResult.Status = http.StatusInternalServerError
queryResult.Error = "Elasticsearch configurations not found. Please check if they are properly configured."
return queryResult
}
url := fmt.Sprintf("http://%s:%s/%s*/_search", es.Host, es.Port, es.Index)
request, err := http.NewRequest("GET", url, bytes.NewBuffer(query))
if err != nil {
glog.Errorln(err)
queryResult = new(QueryResult)
queryResult.Status = http.StatusInternalServerError
queryResult.Error = err.Error()
return queryResult
}
request.Header.Set("Content-Type", "application/json; charset=utf-8")
response, err := client.Do(request)
operation, query, err := createQueryRequest(param)
if err != nil {
glog.Errorln(err)
queryResult = new(QueryResult)
queryResult.Status = http.StatusInternalServerError
queryResult.Error = err.Error()
return queryResult
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
body, err := client.Search(query, config.Index)
if err != nil {
glog.Errorln(err)
queryResult = new(QueryResult)
......
package esclient
import (
"context"
"encoding/json"
"fmt"
v5 "kubesphere.io/kubesphere/pkg/simple/client/elasticsearch/versions/v5"
v6 "kubesphere.io/kubesphere/pkg/simple/client/elasticsearch/versions/v6"
v7 "kubesphere.io/kubesphere/pkg/simple/client/elasticsearch/versions/v7"
"strings"
)
const (
ElasticV5 = "5"
ElasticV6 = "6"
ElasticV7 = "7"
)
type Client interface {
// Perform Search API
Search(body []byte, indexPrefix string) ([]byte, error)
GetTotalHitCount(v interface{}) int64
}
func NewForConfig(cfg *Config) Client {
address := fmt.Sprintf("http://%s:%s", cfg.Host, cfg.Port)
switch cfg.VersionMajor {
case ElasticV5:
return v5.New(address)
case ElasticV6:
return v6.New(address)
case ElasticV7:
return v7.New(address)
default:
return nil
}
}
func detectVersionMajor(cfg *Config) error {
// Info APIs are backward compatible with versions of v5.x, v6.x and v7.x
address := fmt.Sprintf("http://%s:%s", cfg.Host, cfg.Port)
es := v6.New(address)
res, err := es.Client.Info(
es.Client.Info.WithContext(context.Background()),
)
if err != nil {
return err
}
defer res.Body.Close()
var b map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&b); err != nil {
return err
}
if res.IsError() {
// Print the response status and error information.
return fmt.Errorf("[%s] %s: %s",
res.Status(),
b["error"].(map[string]interface{})["type"],
b["error"].(map[string]interface{})["reason"],
)
}
// get the major version
version := fmt.Sprintf("%v", b["version"].(map[string]interface{})["number"])
cfg.VersionMajor = strings.Split(version, ".")[0]
return nil
}
package v5
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v5"
"io/ioutil"
)
type Elastic struct {
Client *elasticsearch.Client
}
func New(address string) Elastic {
client, _ := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{address},
})
return Elastic{Client: client}
}
func (e Elastic) Search(body []byte, indexPrefix string) ([]byte, error) {
response, err := e.Client.Search(
e.Client.Search.WithContext(context.Background()),
e.Client.Search.WithIndex(fmt.Sprintf("%s*", indexPrefix)),
e.Client.Search.WithBody(bytes.NewBuffer(body)),
)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&e); err != nil {
return nil, err
} else {
// Print the response status and error information.
return nil, fmt.Errorf("[%s] %s: %s",
response.Status(),
e["error"].(map[string]interface{})["type"],
e["error"].(map[string]interface{})["reason"],
)
}
}
return ioutil.ReadAll(response.Body)
}
func (e Elastic) GetTotalHitCount(v interface{}) int64 {
return int64(v.(float64))
}
package v6
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v6"
"io/ioutil"
)
type Elastic struct {
Client *elasticsearch.Client
}
func New(address string) Elastic {
client, _ := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{address},
})
return Elastic{Client: client}
}
func (e Elastic) Search(body []byte, indexPrefix string) ([]byte, error) {
response, err := e.Client.Search(
e.Client.Search.WithContext(context.Background()),
e.Client.Search.WithIndex(fmt.Sprintf("%s*", indexPrefix)),
e.Client.Search.WithBody(bytes.NewBuffer(body)),
)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&e); err != nil {
return nil, err
} else {
// Print the response status and error information.
return nil, fmt.Errorf("[%s] %s: %s",
response.Status(),
e["error"].(map[string]interface{})["type"],
e["error"].(map[string]interface{})["reason"],
)
}
}
return ioutil.ReadAll(response.Body)
}
func (e Elastic) GetTotalHitCount(v interface{}) int64 {
return int64(v.(float64))
}
package v7
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v7"
"io/ioutil"
)
type Elastic struct {
Client *elasticsearch.Client
}
func New(address string) Elastic {
client, _ := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{address},
})
return Elastic{Client: client}
}
func (e Elastic) Search(body []byte, indexPrefix string) ([]byte, error) {
response, err := e.Client.Search(
e.Client.Search.WithContext(context.Background()),
e.Client.Search.WithIndex(fmt.Sprintf("%s*", indexPrefix)),
e.Client.Search.WithTrackTotalHits(true),
e.Client.Search.WithBody(bytes.NewBuffer(body)),
)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&e); err != nil {
return nil, err
} else {
// Print the response status and error information.
return nil, fmt.Errorf("[%s] %s: %s",
response.Status(),
e["error"].(map[string]interface{})["type"],
e["error"].(map[string]interface{})["reason"],
)
}
}
return ioutil.ReadAll(response.Body)
}
func (e Elastic) GetTotalHitCount(v interface{}) int64 {
return int64(v.(map[string]interface{})["value"].(float64))
}
comment: off
coverage:
status:
patch: off
ignore:
- "esapi/api.*.go"
dist: xenial
language: go
services:
- docker
branches:
only:
- master
- travis
install: true
matrix:
fast_finish: true
allow_failures:
- os: windows
include:
- name: Unit Tests | Linux, go:stable, gomod=on
os: linux
go: stable
env: GO111MODULE=on TEST_SUITE=unit
script:
- go mod verify
- go build -v ./...
- make lint
- gotestsum --format=short-verbose --junitfile=/tmp/unit-junit.xml -- -coverprofile=/tmp/unit.cov -tags='unit' -timeout=1h -v ./...
after_script:
- test -f /tmp/unit.cov && bash <(curl -s https://codecov.io/bash) -f /tmp/unit.cov
- name: Unit Tests | Linux, go:stable, gomod=off
os: linux
go: stable
env: GO111MODULE=off TEST_SUITE=unit
before_install:
- go get -u golang.org/x/lint/golint
- go get -u gotest.tools/gotestsum
install:
- go get -v ./...
script:
- go build -v ./...
- make lint
- gotestsum --format=short-verbose --junitfile=/tmp/unit-junit.xml -- -tags='unit' -timeout=1h -v ./...
- name: Unit Tests | OS X, go:stable, gomod=on
os: osx
go: stable
env: GO111MODULE=on TEST_SUITE=unit
script:
- go mod verify
- go build -v ./...
- gotestsum --format=short-verbose --junitfile=/tmp/unit-junit.xml -- --tags='unit' --timeout=1h -v ./...
- name: Unit Tests | Windows, go:stable, gomod=on
os: windows
go: stable
env: GO111MODULE=on TEST_SUITE=unit
script:
- go mod verify
- go build -v ./...
- gotestsum --format=short-verbose --junitfile=/tmp/unit-junit.xml -- -tags='unit' -timeout=1h -v ./...
- name: Unit Tests | Linux, go:master, gomod=on
os: linux
go: master
env: GO111MODULE=on TEST_SUITE=unit
script:
- go mod verify
- go build -v ./...
- make lint
- gotestsum --format=short-verbose --junitfile=/tmp/unit-junit.xml -- -tags='unit' -timeout=1h -v ./...
- name: Unit Tests | Docker/Linux, golang:1-alpine
os: linux
env: TEST_SUITE=unit
before_install: true
script:
- grep 'FROM' Dockerfile
- docker build --file Dockerfile --tag elastic/go-elasticsearch .
- echo $(($(docker image inspect -f '{{.Size}}' elastic/go-elasticsearch)/(1000*1000)))MB
- docker run -ti elastic/go-elasticsearch make lint
- docker run -ti elastic/go-elasticsearch make test
- name: Integration Tests | Linux, go:stable
os: linux
go: stable
env: GO111MODULE=on TEST_SUITE=integration-client
before_script:
- docker pull docker.elastic.co/elasticsearch/elasticsearch-oss:7.0.0-SNAPSHOT
- docker network inspect elasticsearch > /dev/null || docker network create elasticsearch;
- |
docker run \
--name es-integration-client \
--network elasticsearch \
--env "cluster.name=es-integration-client" \
--env "discovery.type=single-node" \
--env "bootstrap.memory_lock=true" \
--env "cluster.routing.allocation.disk.threshold_enabled=false" \
--env ES_JAVA_OPTS="-Xms1g -Xmx1g" \
--volume es-integration-client-data:/usr/share/elasticsearch/data \
--publish 9200:9200 \
--ulimit nofile=65536:65536 \
--ulimit memlock=-1:-1 \
--detach \
--rm \
docker.elastic.co/elasticsearch/elasticsearch-oss:7.0.0-SNAPSHOT
- docker run --network elasticsearch --rm appropriate/curl --max-time 120 --retry 120 --retry-delay 1 --retry-connrefused --show-error --silent http://es-integration-client:9200
script:
- gotestsum --format=short-verbose --junitfile=/tmp/integration-report.xml -- -race -cover -coverprofile=/tmp/integration-client.cov -tags='integration' -timeout=1h github.com/elastic/go-elasticsearch
after_script:
- test -f /tmp/integration-client.cov && bash <(curl -s https://codecov.io/bash) -f /tmp/integration-client.cov
- name: Integration Tests, API | Linux, go:stable
os: linux
go: stable
env: GO111MODULE=on TEST_SUITE=integration-api
before_script:
- docker pull docker.elastic.co/elasticsearch/elasticsearch-oss:7.0.0-SNAPSHOT
- docker network inspect elasticsearch > /dev/null || docker network create elasticsearch;
- |
docker run \
--name es-integration-api \
--network elasticsearch \
--env "cluster.name=es-integration-api" \
--env "discovery.type=single-node" \
--env "bootstrap.memory_lock=true" \
--env "cluster.routing.allocation.disk.threshold_enabled=false" \
--env "node.attr.testattr=test" \
--env "path.repo=/tmp" \
--env "repositories.url.allowed_urls=http://snapshot.test*" \
--env ES_JAVA_OPTS="-Xms1g -Xmx1g" \
--volume es-integration-api-data:/usr/share/elasticsearch/data \
--publish 9200:9200 \
--ulimit nofile=65536:65536 \
--ulimit memlock=-1:-1 \
--detach \
--rm \
docker.elastic.co/elasticsearch/elasticsearch-oss:7.0.0-SNAPSHOT
- docker run --network elasticsearch --rm appropriate/curl --max-time 120 --retry 120 --retry-delay 1 --retry-connrefused --show-error --silent http://es-integration-api:9200
script:
- curl -s http://localhost:9200 | jq -r '.version.build_hash' > .elasticsearch_build_hash && cat .elasticsearch_build_hash
# ------ Download Elasticsearch -----------------------------------------------------------
- echo -e "\e[33;1mDownload Elasticsearch Git source @ $(cat .elasticsearch_build_hash)\e[0m" && echo -en 'travis_fold:start:script.dl_es_src\\r'
- echo https://github.com/elastic/elasticsearch/archive/$(cat .elasticsearch_build_hash).zip
- |
curl -sSL --retry 3 -o elasticsearch-$(cat .elasticsearch_build_hash).zip https://github.com/elastic/elasticsearch/archive/$(cat .elasticsearch_build_hash).zip && \
unzip -q -o elasticsearch-$(cat .elasticsearch_build_hash).zip '*.properties' '*.json' '*.yml' -d /tmp && \
mv /tmp/elasticsearch-$(cat .elasticsearch_build_hash)* /tmp/elasticsearch
- echo -en 'travis_fold:end:script.dl_es_src'
# ------ Generate API registry ------------------------------------------------------------
- echo -e "\e[33;1mGenerate API registry\e[0m" && echo -en 'travis_fold:start:script.gen_api_reg\\r\n'
- cd ${TRAVIS_HOME}/gopath/src/github.com/elastic/go-elasticsearch/internal/cmd/generate && ELASTICSEARCH_BUILD_HASH=$(cat ../../../.elasticsearch_build_hash) PACKAGE_PATH=${TRAVIS_HOME}/gopath/src/github.com/elastic/go-elasticsearch/esapi go generate -v ./...
- echo -en 'travis_fold:end:script.gen_api_reg'
# ------ Generate Go test files -----------------------------------------------------------
- echo -e "\e[33;1mGenerate Go test files\e[0m" && echo -en 'travis_fold:start:script.gen_test_files\\r'
- cd ${TRAVIS_HOME}/gopath/src/github.com/elastic/go-elasticsearch/internal/cmd/generate && ELASTICSEARCH_BUILD_HASH=$(cat ../../../.elasticsearch_build_hash) go run main.go apitests --input '/tmp/elasticsearch/rest-api-spec/src/main/resources/rest-api-spec/test/**/*.yml' --output=../../../esapi/test
- echo -en 'travis_fold:end:script.gen_test_files'
# ------ Run tests -----------------------------------------------------------------------
- cd ${TRAVIS_HOME}/gopath/src/github.com/elastic/go-elasticsearch/esapi/test && time gotestsum --format=short-verbose --junitfile=/tmp/integration-api-report.xml -- -coverpkg=github.com/elastic/go-elasticsearch/esapi -coverprofile=/tmp/integration-api.cov -tags='integration' -timeout=1h ./...
after_script:
- test -f /tmp/integration-api.cov && bash <(curl -s https://codecov.io/bash) -f /tmp/integration-api.cov
before_install:
- GO111MODULE=off go get -u golang.org/x/lint/golint
- GO111MODULE=off go get -u gotest.tools/gotestsum
script: echo "TODO > test $TEST_SUITE ($TRAVIS_OS_NAME)"
notifications:
email: true
# $ docker build --file Dockerfile --tag elastic/go-elasticsearch .
#
# $ docker run -it --network elasticsearch --volume $PWD/tmp:/tmp:rw --rm elastic/go-elasticsearch gotestsum --format=short-verbose --junitfile=/tmp/integration-junit.xml -- --cover --coverprofile=/tmp/integration-coverage.out --tags='integration' -v ./...
#
ARG VERSION=1-alpine
FROM golang:${VERSION}
RUN apk add --no-cache --quiet make curl git jq unzip tree && \
go get -u golang.org/x/lint/golint && \
curl -sSL --retry 3 --retry-connrefused https://github.com/gotestyourself/gotestsum/releases/download/v0.3.2/gotestsum_0.3.2_linux_amd64.tar.gz | tar -xz -C /usr/local/bin gotestsum
VOLUME ["/tmp"]
ENV CGO_ENABLED=0
ENV TERM xterm-256color
WORKDIR /go-elasticsearch
COPY . .
RUN go mod download && go mod vendor && \
cd internal/cmd/generate && go mod download && go mod vendor
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Elasticsearch BV
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
##@ Test
test-unit: ## Run unit tests
@echo "\033[2m→ Running unit tests...\033[0m"
ifdef race
$(eval testunitargs += "-race")
endif
$(eval testunitargs += "-cover" "-coverprofile=tmp/unit.cov" "./...")
@mkdir -p tmp
@if which gotestsum > /dev/null 2>&1 ; then \
echo "gotestsum --format=short-verbose --junitfile=tmp/unit-report.xml --" $(testunitargs); \
gotestsum --format=short-verbose --junitfile=tmp/unit-report.xml -- $(testunitargs); \
else \
echo "go test -v" $(testunitargs); \
go test -v $(testunitargs); \
fi;
test: test-unit
test-integ: ## Run integration tests
@echo "\033[2m→ Running integration tests...\033[0m"
$(eval testintegtags += "integration")
ifdef multinode
$(eval testintegtags += "multinode")
endif
ifdef race
$(eval testintegargs += "-race")
endif
$(eval testintegargs += "-cover" "-coverprofile=tmp/integration-client.cov" "-tags='$(testintegtags)'" "-timeout=1h")
@mkdir -p tmp
@if which gotestsum > /dev/null 2>&1 ; then \
echo "gotestsum --format=short-verbose --junitfile=tmp/integration-report.xml --" $(testintegargs); \
gotestsum --format=short-verbose --junitfile=tmp/integration-report.xml -- $(testintegargs) "."; \
gotestsum --format=short-verbose --junitfile=tmp/integration-report.xml -- $(testintegargs) "./estransport" "./esapi" "./esutil"; \
else \
echo "go test -v" $(testintegargs) "."; \
go test -v $(testintegargs) "./estransport" "./esapi" "./esutil"; \
fi;
test-api: ## Run generated API integration tests
@mkdir -p tmp
ifdef race
$(eval testapiargs += "-race")
endif
$(eval testapiargs += "-cover" "-coverpkg=github.com/elastic/go-elasticsearch/v5/esapi" "-coverprofile=$(PWD)/tmp/integration-api.cov" "-tags='integration'" "-timeout=1h")
ifdef flavor
else
$(eval flavor='core')
endif
@echo "\033[2m→ Running API integration tests for [$(flavor)]...\033[0m"
ifeq ($(flavor), xpack)
@{ \
export ELASTICSEARCH_URL='https://elastic:elastic@localhost:9200' && \
if which gotestsum > /dev/null 2>&1 ; then \
cd esapi/test && \
gotestsum --format=short-verbose --junitfile=$(PWD)/tmp/integration-api-report.xml -- $(testapiargs) $(PWD)/esapi/test/xpack/*_test.go && \
gotestsum --format=short-verbose --junitfile=$(PWD)/tmp/integration-api-report.xml -- $(testapiargs) $(PWD)/esapi/test/xpack/ml/*_test.go && \
gotestsum --format=short-verbose --junitfile=$(PWD)/tmp/integration-api-report.xml -- $(testapiargs) $(PWD)/esapi/test/xpack/ml-crud/*_test.go; \
else \
echo "go test -v" $(testapiargs); \
cd esapi/test && \
go test -v $(testapiargs) $(PWD)/esapi/test/xpack/*_test.go && \
go test -v $(testapiargs) $(PWD)/esapi/test/xpack/ml/*_test.go && \
go test -v $(testapiargs) $(PWD)/esapi/test/xpack/ml-crud/*_test.go; \
fi; \
}
else
$(eval testapiargs += $(PWD)/esapi/test/*_test.go)
@{ \
if which gotestsum > /dev/null 2>&1 ; then \
cd esapi/test && gotestsum --format=short-verbose --junitfile=$(PWD)/tmp/integration-api-report.xml -- $(testapiargs); \
else \
echo "go test -v" $(testapiargs); \
cd esapi/test && go test -v $(testapiargs); \
fi; \
}
endif
test-bench: ## Run benchmarks
@echo "\033[2m→ Running benchmarks...\033[0m"
go test -run=none -bench=. -benchmem ./...
test-examples: ## Execute the _examples
@echo "\033[2m→ Testing the examples...\033[0m"
@{ \
set -e ; \
for f in _examples/*.go; do \
echo "\033[2m────────────────────────────────────────────────────────────────────────────────"; \
echo "\033[1m$$f\033[0m"; \
echo "\033[2m────────────────────────────────────────────────────────────────────────────────\033[0m"; \
(go run $$f && true) || \
( \
echo "\033[31m────────────────────────────────────────────────────────────────────────────────\033[0m"; \
echo "\033[31;1m⨯ ERROR\033[0m"; \
false; \
); \
done; \
\
for f in _examples/*/; do \
echo "\033[2m────────────────────────────────────────────────────────────────────────────────\033[0m"; \
echo "\033[1m$$f\033[0m"; \
echo "\033[2m────────────────────────────────────────────────────────────────────────────────\033[0m"; \
(cd $$f && make test && true) || \
( \
echo "\033[31m────────────────────────────────────────────────────────────────────────────────\033[0m"; \
echo "\033[31;1m⨯ ERROR\033[0m"; \
false; \
); \
done; \
echo "\033[32m────────────────────────────────────────────────────────────────────────────────\033[0m"; \
\
echo "\033[32;1mSUCCESS\033[0m"; \
}
test-coverage: ## Generate test coverage report
@echo "\033[2m→ Generating test coverage report...\033[0m"
@go tool cover -html=tmp/unit.cov -o tmp/coverage.html
@go tool cover -func=tmp/unit.cov | 'grep' -v 'esapi/api\.' | sed 's/github.com\/elastic\/go-elasticsearch\///g'
@echo "--------------------------------------------------------------------------------\nopen tmp/coverage.html\n"
##@ Development
lint: ## Run lint on the package
@echo "\033[2m→ Running lint...\033[0m"
go vet github.com/elastic/go-elasticsearch/...
go list github.com/elastic/go-elasticsearch/... | 'grep' -v internal | xargs golint -set_exit_status
apidiff: ## Display API incompabilities
@if ! command -v apidiff > /dev/null; then \
echo "\033[31;1mERROR: apidiff not installed\033[0m"; \
echo "go get -u github.com/go-modules-by-example/apidiff"; \
echo "\033[2m→ https://github.com/go-modules-by-example/index/blob/master/019_apidiff/README.md\033[0m\n"; \
false; \
fi;
@rm -rf tmp/apidiff-OLD tmp/apidiff-NEW
@git clone --quiet --local .git/ tmp/apidiff-OLD
@mkdir -p tmp/apidiff-NEW
@tar -c --exclude .git --exclude tmp --exclude cmd . | tar -x -C tmp/apidiff-NEW
@echo "\033[2m→ Running apidiff...\033[0m"
@echo "tmp/apidiff-OLD/esapi tmp/apidiff-NEW/esapi"
@{ \
set -e ; \
output=$$(apidiff tmp/apidiff-OLD/esapi tmp/apidiff-NEW/esapi); \
echo "\n$$output\n"; \
if echo $$output | grep -i -e 'incompatible' - > /dev/null 2>&1; then \
echo "\n\033[31;1mFAILURE\033[0m\n"; \
false; \
else \
echo "\033[32;1mSUCCESS\033[0m"; \
fi; \
}
backport: ## Backport one or more commits from master into version branches
ifeq ($(origin commits), undefined)
@echo "Missing commit(s), exiting..."
@exit 2
endif
ifndef branches
$(eval branches_list = '7.x' '6.x' '5.x')
else
$(eval branches_list = $(shell echo $(branches) | tr ',' ' ') )
endif
$(eval commits_list = $(shell echo $(commits) | tr ',' ' '))
@echo "\033[2m→ Backporting commits [$(commits)]\033[0m"
@{ \
set -e -o pipefail; \
for commit in $(commits_list); do \
git show --pretty='%h | %s' --no-patch $$commit; \
done; \
echo ""; \
for branch in $(branches_list); do \
echo "\033[2m→ $$branch\033[0m"; \
git checkout $$branch; \
for commit in $(commits_list); do \
git cherry-pick -x $$commit; \
done; \
git status --short --branch; \
echo ""; \
done; \
echo "\033[2m→ Push updates to Github:\033[0m"; \
for branch in $(branches_list); do \
echo "git push --verbose origin $$branch"; \
done; \
}
release: ## Release a new version to Github
ifndef version
@echo "Missing version argument, exiting..."
@exit 2
endif
ifeq ($(version), "")
@echo "Empty version argument, exiting..."
@exit 2
endif
@echo "\033[2m→ Creating version $(version)...\033[0m"
@{ \
cp internal/version/version.go internal/version/version.go.OLD && \
cat internal/version/version.go.OLD | sed -e 's/Client = ".*"/Client = "$(version)"/' > internal/version/version.go && \
rm internal/version/version.go.OLD && \
go vet internal/version/version.go && \
go fmt internal/version/version.go && \
git diff --color-words internal/version/version.go | tail -n 1; \
}
@{ \
echo "\033[2m→ Commit and create Git tag? (y/n): \033[0m\c"; \
read continue; \
if [[ $$continue == "y" ]]; then \
git add internal/version/version.go && \
git commit --no-status --quiet --message "Release $(version)" && \
git tag --annotate v$(version) --message 'Release $(version)'; \
echo "\033[2m→ Push `git show --pretty='%h (%s)' --no-patch HEAD` to Github:\033[0m\n"; \
echo "\033[1m git push origin v$(version)\033[0m\n"; \
else \
echo "Aborting..."; \
exit 1; \
fi; \
}
godoc: ## Display documentation for the package
@echo "\033[2m→ Generating documentation...\033[0m"
@echo "open http://localhost:6060/pkg/github.com/elastic/go-elasticsearch/\n"
mkdir -p /tmp/tmpgoroot/doc
rm -rf /tmp/tmpgopath/src/github.com/elastic/go-elasticsearch
mkdir -p /tmp/tmpgopath/src/github.com/elastic/go-elasticsearch
tar -c --exclude='.git' --exclude='tmp' . | tar -x -C /tmp/tmpgopath/src/github.com/elastic/go-elasticsearch
GOROOT=/tmp/tmpgoroot/ GOPATH=/tmp/tmpgopath/ godoc -http=localhost:6060 -play
cluster: ## Launch an Elasticsearch cluster with Docker
$(eval version ?= "elasticsearch:5.6.15")
ifeq ($(origin nodes), undefined)
$(eval nodes = 1)
endif
@echo "\033[2m→ Launching" $(nodes) "node(s) of" $(version) "...\033[0m"
ifeq ($(shell test $(nodes) && test $(nodes) -gt 1; echo $$?),0)
$(eval detached ?= "true")
else
$(eval detached ?= "false")
endif
@docker network inspect elasticsearch > /dev/null 2>&1 || docker network create elasticsearch;
@{ \
for n in `seq 1 $(nodes)`; do \
if [[ -z "$$port" ]]; then \
hostport=$$((9199+$$n)); \
else \
hostport=$$port; \
fi; \
docker run \
--name "es$$n" \
--network elasticsearch \
--env "node.name=es$$n" \
--env "cluster.name=go-elasticsearch" \
--env "cluster.routing.allocation.disk.threshold_enabled=false" \
--env "discovery.zen.ping.unicast.hosts=es1" \
--env "bootstrap.memory_lock=true" \
--env "node.attr.testattr=test" \
--env "path.repo=/tmp" \
--env "repositories.url.allowed_urls=http://snapshot.test*" \
--env "xpack.security.enabled=false" \
--env "xpack.monitoring.enabled=false" \
--env "xpack.ml.enabled=false" \
--env ES_JAVA_OPTS="-Xms1g -Xmx1g" \
--volume `echo $(version) | tr -C "[:alnum:]" '-'`-node-$$n-data:/usr/share/elasticsearch/data \
--publish $$hostport:9200 \
--ulimit nofile=65536:65536 \
--ulimit memlock=-1:-1 \
--detach=$(detached) \
--rm \
docker.elastic.co/elasticsearch/$(version); \
done \
}
ifdef detached
@{ \
echo "\033[2m→ Waiting for the cluster...\033[0m"; \
docker run --network elasticsearch --rm appropriate/curl --max-time 120 --retry 120 --retry-delay 1 --retry-connrefused --show-error --silent http://es1:9200; \
output="\033[2m→ Cluster ready; to remove containers:"; \
output="$$output docker rm -f"; \
for n in `seq 1 $(nodes)`; do \
output="$$output es$$n"; \
done; \
echo "$$output\033[0m"; \
}
endif
cluster-update: ## Update the Docker image
$(eval version ?= "elasticsearch:5.6.15")
@echo "\033[2m→ Updating the Docker image...\033[0m"
@docker pull docker.elastic.co/elasticsearch/$(version);
cluster-clean: ## Remove unused Docker volumes and networks
@echo "\033[2m→ Cleaning up Docker assets...\033[0m"
docker volume prune --force
docker network prune --force
docker: ## Build the Docker image and run it
docker build --file Dockerfile --tag elastic/go-elasticsearch .
docker run -it --network elasticsearch --volume $(PWD)/tmp:/tmp:rw,delegated --rm elastic/go-elasticsearch
##@ Generator
gen-api: ## Generate the API package from the JSON specification
$(eval input ?= tmp/elasticsearch)
$(eval output ?= esapi)
ifdef debug
$(eval args += --debug)
endif
ifdef ELASTICSEARCH_VERSION
$(eval version = $(ELASTICSEARCH_VERSION))
else
$(eval version = $(shell cat "$(input)/buildSrc/version.properties" | grep 'elasticsearch' | cut -d '=' -f 2 | tr -d ' '))
endif
ifdef ELASTICSEARCH_BUILD_HASH
$(eval build_hash = $(ELASTICSEARCH_BUILD_HASH))
else
$(eval build_hash = $(shell git --git-dir='$(input)/.git' rev-parse --short HEAD))
endif
@echo "\033[2m→ Generating API package from specification ($(version):$(build_hash))...\033[0m"
@{ \
export ELASTICSEARCH_VERSION=$(version) && \
export ELASTICSEARCH_BUILD_HASH=$(build_hash) && \
cd internal/cmd/generate && \
go run main.go apisource --input '$(PWD)/$(input)/rest-api-spec/src/main/resources/rest-api-spec/api/*.json' --output '$(PWD)/$(output)' $(args) && \
go run main.go apistruct --output '$(PWD)/$(output)'; \
}
gen-tests: ## Generate the API tests from the YAML specification
$(eval input ?= tmp/elasticsearch)
$(eval output ?= esapi/test)
ifdef debug
$(eval args += --debug)
endif
ifdef ELASTICSEARCH_VERSION
$(eval version = $(ELASTICSEARCH_VERSION))
else
$(eval version = $(shell cat "$(input)/buildSrc/version.properties" | grep 'elasticsearch' | cut -d '=' -f 2 | tr -d ' '))
endif
ifdef ELASTICSEARCH_BUILD_HASH
$(eval build_hash = $(ELASTICSEARCH_BUILD_HASH))
else
$(eval build_hash = $(shell git --git-dir='$(input)/.git' rev-parse --short HEAD))
endif
@echo "\033[2m→ Generating API tests from specification ($(version):$(build_hash))...\033[0m"
@{ \
export ELASTICSEARCH_VERSION=$(version) && \
export ELASTICSEARCH_BUILD_HASH=$(build_hash) && \
rm -rf $(output)/*_test.go && \
rm -rf $(output)/xpack && \
cd internal/cmd/generate && \
go generate ./... && \
go run main.go apitests --input '$(PWD)/$(input)/rest-api-spec/src/main/resources/rest-api-spec/test/**/*.y*ml' --output '$(PWD)/$(output)' $(args); \
}
##@ Other
#------------------------------------------------------------------------------
help: ## Display help
@awk 'BEGIN {FS = ":.*##"; printf "Usage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
#------------- <https://suva.sh/posts/well-documented-makefiles> --------------
.DEFAULT_GOAL := help
.PHONY: help apidiff backport cluster cluster-clean cluster-update coverage docker examples gen-api gen-tests godoc lint release test test-api test-bench test-integ test-unit
# go-elasticsearch
The official Go client for [Elasticsearch](https://www.elastic.co/products/elasticsearch).
[![GoDoc](https://godoc.org/github.com/elastic/go-elasticsearch?status.svg)](http://godoc.org/github.com/elastic/go-elasticsearch)
[![Travis-CI](https://travis-ci.org/elastic/go-elasticsearch.svg?branch=master)](https://travis-ci.org/elastic/go-elasticsearch)
[![Go Report Card](https://goreportcard.com/badge/github.com/elastic/go-elasticsearch)](https://goreportcard.com/report/github.com/elastic/go-elasticsearch)
[![codecov.io](https://codecov.io/github/elastic/go-elasticsearch/coverage.svg?branch=master)](https://codecov.io/gh/elastic/go-elasticsearch?branch=master)
## Compatibility
The client major versions correspond to the compatible Elasticsearch major versions: to connect to Elasticsearch `7.x`, use a [`7.x`](https://github.com/elastic/go-elasticsearch/tree/7.x) version of the client, to connect to Elasticsearch `6.x`, use a [`6.x`](https://github.com/elastic/go-elasticsearch/tree/6.x) version of the client.
When using Go modules, include the version in the import path, and specify either an explicit version or a branch:
require github.com/elastic/go-elasticsearch/v7 7.x
require github.com/elastic/go-elasticsearch/v7 7.0.0
It's possible to use multiple versions of the client in a single project:
// go.mod
github.com/elastic/go-elasticsearch/v6 6.x
github.com/elastic/go-elasticsearch/v7 7.x
// main.go
import (
elasticsearch6 "github.com/elastic/go-elasticsearch/v6"
elasticsearch7 "github.com/elastic/go-elasticsearch/v7"
)
// ...
es6, _ := elasticsearch6.NewDefaultClient()
es7, _ := elasticsearch7.NewDefaultClient()
The `master` branch of the client is compatible with the current `master` branch of Elasticsearch.
<!-- ----------------------------------------------------------------------------------------------- -->
## Installation
Add the package to your `go.mod` file:
require github.com/elastic/go-elasticsearch/v5 5.x
Or, clone the repository:
git clone --branch 5.x https://github.com/elastic/go-elasticsearch.git $GOPATH/src/github.com/elastic/go-elasticsearch
A complete example:
```bash
mkdir my-elasticsearch-app && cd my-elasticsearch-app
cat > go.mod <<-END
module my-elasticsearch-app
require github.com/elastic/go-elasticsearch/v5 5.x
END
cat > main.go <<-END
package main
import (
"log"
"github.com/elastic/go-elasticsearch/v5"
)
func main() {
es, _ := elasticsearch.NewDefaultClient()
log.Println(elasticsearch.Version)
log.Println(es.Info())
}
END
go run main.go
```
<!-- ----------------------------------------------------------------------------------------------- -->
## Usage
The `elasticsearch` package ties together two separate packages for calling the Elasticsearch APIs and transferring data over HTTP: `esapi` and `estransport`, respectively.
Use the `elasticsearch.NewDefaultClient()` function to create the client with the default settings.
```golang
es, err := elasticsearch.NewDefaultClient()
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
res, err := es.Info()
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
log.Println(res)
// [200 OK] {
// "name" : "node-1",
// "cluster_name" : "go-elasticsearch"
// ...
```
When you export the `ELASTICSEARCH_URL` environment variable,
it will be used to set the cluster endpoint(s). Separate multiple adresses by a comma.
To set the cluster endpoint(s) programatically, pass them in the configuration object
to the `elasticsearch.NewClient()` function.
```golang
cfg := elasticsearch.Config{
Addresses: []string{
"http://localhost:9200",
"http://localhost:9201",
},
}
es, err := elasticsearch.NewClient(cfg)
// ...
```
To configure the HTTP settings, pass a [`http.Transport`](https://golang.org/pkg/net/http/#Transport)
object in the configuration object (the values are for illustrative purposes only).
```golang
cfg := elasticsearch.Config{
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Second,
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS11,
// ...
},
},
}
es, err := elasticsearch.NewClient(cfg)
// ...
```
See the [`_examples/configuration.go`](_examples/configuration.go) and
[`_examples/customization.go`](_examples/customization.go) files for
more examples of configuration and customization of the client.
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.
```golang
// $ go run _examples/main.go
package main
import (
"bytes"
"context"
"encoding/json"
"log"
"strconv"
"strings"
"sync"
"github.com/elastic/go-elasticsearch/v5"
"github.com/elastic/go-elasticsearch/v5/esapi"
)
func main() {
log.SetFlags(0)
var (
r map[string]interface{}
wg sync.WaitGroup
)
// Initialize a client with the default settings.
//
// An `ELASTICSEARCH_URL` environment variable will be used when exported.
//
es, err := elasticsearch.NewDefaultClient()
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
// 1. Get cluster info
//
res, err := es.Info()
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
// Check response status
if res.IsError() {
log.Fatalf("Error: %s", res.String())
}
// Deserialize the response into a map.
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
// Print client and server version numbers.
log.Printf("Client: %s", elasticsearch.Version)
log.Printf("Server: %s", r["version"].(map[string]interface{})["number"])
log.Println(strings.Repeat("~", 37))
// 2. Index documents concurrently
//
for i, title := range []string{"Test One", "Test Two"} {
wg.Add(1)
go func(i int, title string) {
defer wg.Done()
// Build the request body.
var b strings.Builder
b.WriteString(`{"title" : "`)
b.WriteString(title)
b.WriteString(`"}`)
// Set up the request object.
req := esapi.IndexRequest{
Index: "test",
DocumentType: "test",
DocumentID: strconv.Itoa(i + 1),
Body: strings.NewReader(b.String()),
Refresh: "true",
}
// Perform the request with the client.
res, err := req.Do(context.Background(), es)
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
if res.IsError() {
log.Printf("[%s] Error indexing document ID=%d", res.Status(), i+1)
} else {
// Deserialize the response into a map.
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
} else {
// Print the response status and indexed document version.
log.Printf("[%s] %s; version=%d", res.Status(), r["result"], int(r["_version"].(float64)))
}
}
}(i, title)
}
wg.Wait()
log.Println(strings.Repeat("-", 37))
// 3. Search for the indexed documents
//
// Build the request body.
var buf bytes.Buffer
query := map[string]interface{}{
"query": map[string]interface{}{
"match": map[string]interface{}{
"title": "test",
},
},
}
if err := json.NewEncoder(&buf).Encode(query); err != nil {
log.Fatalf("Error encoding query: %s", err)
}
// Perform the search request.
res, err = es.Search(
es.Search.WithContext(context.Background()),
es.Search.WithIndex("test"),
es.Search.WithBody(&buf),
es.Search.WithPretty(),
)
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
if res.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
} else {
// Print the response status and error information.
log.Fatalf("[%s] %s: %s",
res.Status(),
e["error"].(map[string]interface{})["type"],
e["error"].(map[string]interface{})["reason"],
)
}
}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
// Print the response status, number of results, and request duration.
log.Printf(
"[%s] %d hits; took: %dms",
res.Status(),
int(r["hits"].(map[string]interface{})["total"].(float64)),
int(r["took"].(float64)),
)
// Print the ID and document source for each hit.
for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
log.Printf(" * ID=%s, %s", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"])
}
log.Println(strings.Repeat("=", 37))
}
// Client: 5.6.0-SNAPSHOT
// Server: 5.6.15
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// [201 Created] updated; version=1
// [201 Created] updated; version=1
// -------------------------------------
// [200 OK] 2 hits; took: 5ms
// * ID=1, map[title:Test One]
// * ID=2, map[title:Test Two]
// =====================================
```
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
[package documentation](https://godoc.org/github.com/elastic/go-elasticsearch/esapi).
The `estransport` package handles the transfer of data to and from Elasticsearch. At the moment, the implementation is really minimal: it only round-robins across the configured cluster endpoints. In future, more features — retrying failed requests, ignoring certain status codes, auto-discovering nodes in the cluster, and so on — will be added.
<!-- ----------------------------------------------------------------------------------------------- -->
## Helpers
The `esutil` package provides convenience helpers for working with the client. At the moment, it provides the
`esutil.JSONReader()` helper function.
<!-- ----------------------------------------------------------------------------------------------- -->
## Examples
The **[`_examples`](./_examples)** folder contains a number of recipes and comprehensive examples to get you started with the client, including configuration and customization of the client, mocking the transport for unit tests, embedding the client in a custom type, building queries, performing requests, and parsing the responses.
<!-- ----------------------------------------------------------------------------------------------- -->
## License
(c) 2019 Elasticsearch. Licensed under the Apache License, Version 2.0.
/*
Package elasticsearch provides a Go client for Elasticsearch.
Create the client with the NewDefaultClient function:
elasticsearch.NewDefaultClient()
The ELASTICSEARCH_URL environment variable is used instead of the default URL, when set.
Use a comma to separate multiple URLs.
To configure the client, pass a Config object to the NewClient function:
cfg := elasticsearch.Config{
Addresses: []string{
"http://localhost:9200",
"http://localhost:9201",
},
Username: "foo",
Password: "bar",
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Second,
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS11,
},
},
}
elasticsearch.NewClient(cfg)
See the elasticsearch_integration_test.go file and the _examples folder for more information.
Call the Elasticsearch APIs by invoking the corresponding methods on the client:
res, err := es.Info()
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
log.Println(res)
See the github.com/elastic/go-elasticsearch/esapi package for more information and examples.
*/
package elasticsearch
package elasticsearch
import (
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"github.com/elastic/go-elasticsearch/v5/esapi"
"github.com/elastic/go-elasticsearch/v5/estransport"
"github.com/elastic/go-elasticsearch/v5/internal/version"
)
const (
defaultURL = "http://localhost:9200"
)
// Version returns the package version as a string.
//
const Version = version.Client
// Config represents the client configuration.
//
type Config struct {
Addresses []string // A list of Elasticsearch nodes to use.
Username string // Username for HTTP Basic Authentication.
Password string // Password for HTTP Basic Authentication.
Transport http.RoundTripper // The HTTP transport object.
Logger estransport.Logger // The logger object.
}
// Client represents the Elasticsearch client.
//
type Client struct {
*esapi.API // Embeds the API methods
Transport estransport.Interface
}
// NewDefaultClient creates a new client with default options.
//
// It will use http://localhost:9200 as the default address.
//
// It will use the ELASTICSEARCH_URL environment variable, if set,
// to configure the addresses; use a comma to separate multiple URLs.
//
func NewDefaultClient() (*Client, error) {
return NewClient(Config{})
}
// NewClient creates a new client with configuration from cfg.
//
// It will use http://localhost:9200 as the default address.
//
// It will use the ELASTICSEARCH_URL environment variable, if set,
// to configure the addresses; use a comma to separate multiple URLs.
//
// It's an error to set both cfg.Addresses and the ELASTICSEARCH_URL
// environment variable.
//
func NewClient(cfg Config) (*Client, error) {
envAddrs := addrsFromEnvironment()
if len(envAddrs) > 0 && len(cfg.Addresses) > 0 {
return nil, errors.New("cannot create client: both ELASTICSEARCH_URL and Addresses are set")
}
addrs := append(envAddrs, cfg.Addresses...)
urls, err := addrsToURLs(addrs)
if err != nil {
return nil, fmt.Errorf("cannot create client: %s", err)
}
if len(urls) == 0 {
u, _ := url.Parse(defaultURL) // errcheck exclude
urls = append(urls, u)
}
tp := estransport.New(estransport.Config{
URLs: urls,
Username: cfg.Username,
Password: cfg.Password,
Transport: cfg.Transport,
Logger: cfg.Logger,
})
return &Client{Transport: tp, API: esapi.New(tp)}, nil
}
// Perform delegates to Transport to execute a request and return a response.
//
func (c *Client) Perform(req *http.Request) (*http.Response, error) {
return c.Transport.Perform(req)
}
// addrsFromEnvironment returns a list of addresses by splitting
// the ELASTICSEARCH_URL environment variable with comma, or an empty list.
//
func addrsFromEnvironment() []string {
var addrs []string
if envURLs, ok := os.LookupEnv("ELASTICSEARCH_URL"); ok && envURLs != "" {
list := strings.Split(envURLs, ",")
for _, u := range list {
addrs = append(addrs, strings.TrimSpace(u))
}
}
return addrs
}
// addrsToURLs creates a list of url.URL structures from url list.
//
func addrsToURLs(addrs []string) ([]*url.URL, error) {
var urls []*url.URL
for _, addr := range addrs {
u, err := url.Parse(strings.TrimRight(addr, "/"))
if err != nil {
return nil, fmt.Errorf("cannot parse url: %v", err)
}
urls = append(urls, u)
}
return urls, nil
}
// Code generated from specification version 5.6.15 (fe7575a32e2): DO NOT EDIT
package esapi
// API contains the Elasticsearch APIs
//
type API struct {
Cat *Cat
Cluster *Cluster
Indices *Indices
Ingest *Ingest
Nodes *Nodes
Remote *Remote
Snapshot *Snapshot
Tasks *Tasks
Bulk Bulk
ClearScroll ClearScroll
CountPercolate CountPercolate
Count Count
Create Create
DeleteByQuery DeleteByQuery
DeleteByQueryRethrottle DeleteByQueryRethrottle
Delete Delete
DeleteScript DeleteScript
DeleteTemplate DeleteTemplate
Exists Exists
ExistsSource ExistsSource
Explain Explain
FieldCaps FieldCaps
FieldStats FieldStats
Get Get
GetScript GetScript
GetSource GetSource
GetTemplate GetTemplate
Index Index
Info Info
Mget Mget
Mpercolate Mpercolate
Msearch Msearch
MsearchTemplate MsearchTemplate
Mtermvectors Mtermvectors
Percolate Percolate
Ping Ping
PutScript PutScript
PutTemplate PutTemplate
RankEval RankEval
Reindex Reindex
ReindexRethrottle ReindexRethrottle
RenderSearchTemplate RenderSearchTemplate
ScriptsPainlessExecute ScriptsPainlessExecute
Scroll Scroll
Search Search
SearchShards SearchShards
SearchTemplate SearchTemplate
Suggest Suggest
Termvectors Termvectors
UpdateByQuery UpdateByQuery
UpdateByQueryRethrottle UpdateByQueryRethrottle
Update Update
}
// Cat contains the Cat APIs
type Cat struct {
Aliases CatAliases
Allocation CatAllocation
Count CatCount
Fielddata CatFielddata
Health CatHealth
Help CatHelp
Indices CatIndices
Master CatMaster
Nodeattrs CatNodeattrs
Nodes CatNodes
PendingTasks CatPendingTasks
Plugins CatPlugins
Recovery CatRecovery
Repositories CatRepositories
Segments CatSegments
Shards CatShards
Snapshots CatSnapshots
Tasks CatTasks
Templates CatTemplates
ThreadPool CatThreadPool
}
// Cluster contains the Cluster APIs
type Cluster struct {
AllocationExplain ClusterAllocationExplain
GetSettings ClusterGetSettings
Health ClusterHealth
PendingTasks ClusterPendingTasks
PutSettings ClusterPutSettings
RemoteInfo ClusterRemoteInfo
Reroute ClusterReroute
State ClusterState
Stats ClusterStats
}
// Indices contains the Indices APIs
type Indices struct {
Analyze IndicesAnalyze
ClearCache IndicesClearCache
Close IndicesClose
Create IndicesCreate
DeleteAlias IndicesDeleteAlias
Delete IndicesDelete
DeleteTemplate IndicesDeleteTemplate
ExistsAlias IndicesExistsAlias
ExistsDocumentType IndicesExistsDocumentType
Exists IndicesExists
ExistsTemplate IndicesExistsTemplate
Flush IndicesFlush
FlushSynced IndicesFlushSynced
Forcemerge IndicesForcemerge
GetAlias IndicesGetAlias
GetFieldMapping IndicesGetFieldMapping
GetMapping IndicesGetMapping
Get IndicesGet
GetSettings IndicesGetSettings
GetTemplate IndicesGetTemplate
GetUpgrade IndicesGetUpgrade
Open IndicesOpen
PutAlias IndicesPutAlias
PutMapping IndicesPutMapping
PutSettings IndicesPutSettings
PutTemplate IndicesPutTemplate
Recovery IndicesRecovery
Refresh IndicesRefresh
Rollover IndicesRollover
Segments IndicesSegments
ShardStores IndicesShardStores
Shrink IndicesShrink
Split IndicesSplit
Stats IndicesStats
UpdateAliases IndicesUpdateAliases
Upgrade IndicesUpgrade
ValidateQuery IndicesValidateQuery
}
// Ingest contains the Ingest APIs
type Ingest struct {
DeletePipeline IngestDeletePipeline
GetPipeline IngestGetPipeline
ProcessorGrok IngestProcessorGrok
PutPipeline IngestPutPipeline
Simulate IngestSimulate
}
// Nodes contains the Nodes APIs
type Nodes struct {
HotThreads NodesHotThreads
Info NodesInfo
ReloadSecureSettings NodesReloadSecureSettings
Stats NodesStats
Usage NodesUsage
}
// Remote contains the Remote APIs
type Remote struct {
}
// Snapshot contains the Snapshot APIs
type Snapshot struct {
CreateRepository SnapshotCreateRepository
Create SnapshotCreate
DeleteRepository SnapshotDeleteRepository
Delete SnapshotDelete
GetRepository SnapshotGetRepository
Get SnapshotGet
Restore SnapshotRestore
Status SnapshotStatus
VerifyRepository SnapshotVerifyRepository
}
// Tasks contains the Tasks APIs
type Tasks struct {
Cancel TasksCancel
Get TasksGet
List TasksList
}
// New creates new API
//
func New(t Transport) *API {
return &API{
Bulk: newBulkFunc(t),
ClearScroll: newClearScrollFunc(t),
CountPercolate: newCountPercolateFunc(t),
Count: newCountFunc(t),
Create: newCreateFunc(t),
DeleteByQuery: newDeleteByQueryFunc(t),
DeleteByQueryRethrottle: newDeleteByQueryRethrottleFunc(t),
Delete: newDeleteFunc(t),
DeleteScript: newDeleteScriptFunc(t),
DeleteTemplate: newDeleteTemplateFunc(t),
Exists: newExistsFunc(t),
ExistsSource: newExistsSourceFunc(t),
Explain: newExplainFunc(t),
FieldCaps: newFieldCapsFunc(t),
FieldStats: newFieldStatsFunc(t),
Get: newGetFunc(t),
GetScript: newGetScriptFunc(t),
GetSource: newGetSourceFunc(t),
GetTemplate: newGetTemplateFunc(t),
Index: newIndexFunc(t),
Info: newInfoFunc(t),
Mget: newMgetFunc(t),
Mpercolate: newMpercolateFunc(t),
Msearch: newMsearchFunc(t),
MsearchTemplate: newMsearchTemplateFunc(t),
Mtermvectors: newMtermvectorsFunc(t),
Percolate: newPercolateFunc(t),
Ping: newPingFunc(t),
PutScript: newPutScriptFunc(t),
PutTemplate: newPutTemplateFunc(t),
RankEval: newRankEvalFunc(t),
Reindex: newReindexFunc(t),
ReindexRethrottle: newReindexRethrottleFunc(t),
RenderSearchTemplate: newRenderSearchTemplateFunc(t),
ScriptsPainlessExecute: newScriptsPainlessExecuteFunc(t),
Scroll: newScrollFunc(t),
Search: newSearchFunc(t),
SearchShards: newSearchShardsFunc(t),
SearchTemplate: newSearchTemplateFunc(t),
Suggest: newSuggestFunc(t),
Termvectors: newTermvectorsFunc(t),
UpdateByQuery: newUpdateByQueryFunc(t),
UpdateByQueryRethrottle: newUpdateByQueryRethrottleFunc(t),
Update: newUpdateFunc(t),
Cat: &Cat{
Aliases: newCatAliasesFunc(t),
Allocation: newCatAllocationFunc(t),
Count: newCatCountFunc(t),
Fielddata: newCatFielddataFunc(t),
Health: newCatHealthFunc(t),
Help: newCatHelpFunc(t),
Indices: newCatIndicesFunc(t),
Master: newCatMasterFunc(t),
Nodeattrs: newCatNodeattrsFunc(t),
Nodes: newCatNodesFunc(t),
PendingTasks: newCatPendingTasksFunc(t),
Plugins: newCatPluginsFunc(t),
Recovery: newCatRecoveryFunc(t),
Repositories: newCatRepositoriesFunc(t),
Segments: newCatSegmentsFunc(t),
Shards: newCatShardsFunc(t),
Snapshots: newCatSnapshotsFunc(t),
Tasks: newCatTasksFunc(t),
Templates: newCatTemplatesFunc(t),
ThreadPool: newCatThreadPoolFunc(t),
},
Cluster: &Cluster{
AllocationExplain: newClusterAllocationExplainFunc(t),
GetSettings: newClusterGetSettingsFunc(t),
Health: newClusterHealthFunc(t),
PendingTasks: newClusterPendingTasksFunc(t),
PutSettings: newClusterPutSettingsFunc(t),
RemoteInfo: newClusterRemoteInfoFunc(t),
Reroute: newClusterRerouteFunc(t),
State: newClusterStateFunc(t),
Stats: newClusterStatsFunc(t),
},
Indices: &Indices{
Analyze: newIndicesAnalyzeFunc(t),
ClearCache: newIndicesClearCacheFunc(t),
Close: newIndicesCloseFunc(t),
Create: newIndicesCreateFunc(t),
DeleteAlias: newIndicesDeleteAliasFunc(t),
Delete: newIndicesDeleteFunc(t),
DeleteTemplate: newIndicesDeleteTemplateFunc(t),
ExistsAlias: newIndicesExistsAliasFunc(t),
ExistsDocumentType: newIndicesExistsDocumentTypeFunc(t),
Exists: newIndicesExistsFunc(t),
ExistsTemplate: newIndicesExistsTemplateFunc(t),
Flush: newIndicesFlushFunc(t),
FlushSynced: newIndicesFlushSyncedFunc(t),
Forcemerge: newIndicesForcemergeFunc(t),
GetAlias: newIndicesGetAliasFunc(t),
GetFieldMapping: newIndicesGetFieldMappingFunc(t),
GetMapping: newIndicesGetMappingFunc(t),
Get: newIndicesGetFunc(t),
GetSettings: newIndicesGetSettingsFunc(t),
GetTemplate: newIndicesGetTemplateFunc(t),
GetUpgrade: newIndicesGetUpgradeFunc(t),
Open: newIndicesOpenFunc(t),
PutAlias: newIndicesPutAliasFunc(t),
PutMapping: newIndicesPutMappingFunc(t),
PutSettings: newIndicesPutSettingsFunc(t),
PutTemplate: newIndicesPutTemplateFunc(t),
Recovery: newIndicesRecoveryFunc(t),
Refresh: newIndicesRefreshFunc(t),
Rollover: newIndicesRolloverFunc(t),
Segments: newIndicesSegmentsFunc(t),
ShardStores: newIndicesShardStoresFunc(t),
Shrink: newIndicesShrinkFunc(t),
Split: newIndicesSplitFunc(t),
Stats: newIndicesStatsFunc(t),
UpdateAliases: newIndicesUpdateAliasesFunc(t),
Upgrade: newIndicesUpgradeFunc(t),
ValidateQuery: newIndicesValidateQueryFunc(t),
},
Ingest: &Ingest{
DeletePipeline: newIngestDeletePipelineFunc(t),
GetPipeline: newIngestGetPipelineFunc(t),
ProcessorGrok: newIngestProcessorGrokFunc(t),
PutPipeline: newIngestPutPipelineFunc(t),
Simulate: newIngestSimulateFunc(t),
},
Nodes: &Nodes{
HotThreads: newNodesHotThreadsFunc(t),
Info: newNodesInfoFunc(t),
ReloadSecureSettings: newNodesReloadSecureSettingsFunc(t),
Stats: newNodesStatsFunc(t),
Usage: newNodesUsageFunc(t),
},
Remote: &Remote{},
Snapshot: &Snapshot{
CreateRepository: newSnapshotCreateRepositoryFunc(t),
Create: newSnapshotCreateFunc(t),
DeleteRepository: newSnapshotDeleteRepositoryFunc(t),
Delete: newSnapshotDeleteFunc(t),
GetRepository: newSnapshotGetRepositoryFunc(t),
Get: newSnapshotGetFunc(t),
Restore: newSnapshotRestoreFunc(t),
Status: newSnapshotStatusFunc(t),
VerifyRepository: newSnapshotVerifyRepositoryFunc(t),
},
Tasks: &Tasks{
Cancel: newTasksCancelFunc(t),
Get: newTasksGetFunc(t),
List: newTasksListFunc(t),
},
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"io"
"net/http"
"strings"
"time"
)
func newBulkFunc(t Transport) Bulk {
return func(body io.Reader, o ...func(*BulkRequest)) (*Response, error) {
var r = BulkRequest{Body: body}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// Bulk allows to perform multiple index/update/delete operations in a single request.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/docs-bulk.html.
//
type Bulk func(body io.Reader, o ...func(*BulkRequest)) (*Response, error)
// BulkRequest configures the Bulk API request.
//
type BulkRequest struct {
Index string
DocumentType string
Body io.Reader
Fields []string
Pipeline string
Refresh string
Routing string
Source []string
SourceExclude []string
SourceInclude []string
Timeout time.Duration
WaitForActiveShards string
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r BulkRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "POST"
path.Grow(1 + len(r.Index) + 1 + len(r.DocumentType) + 1 + len("_bulk"))
if r.Index != "" {
path.WriteString("/")
path.WriteString(r.Index)
}
if r.DocumentType != "" {
path.WriteString("/")
path.WriteString(r.DocumentType)
}
path.WriteString("/")
path.WriteString("_bulk")
params = make(map[string]string)
if len(r.Fields) > 0 {
params["fields"] = strings.Join(r.Fields, ",")
}
if r.Pipeline != "" {
params["pipeline"] = r.Pipeline
}
if r.Refresh != "" {
params["refresh"] = r.Refresh
}
if r.Routing != "" {
params["routing"] = r.Routing
}
if len(r.Source) > 0 {
params["_source"] = strings.Join(r.Source, ",")
}
if len(r.SourceExclude) > 0 {
params["_source_exclude"] = strings.Join(r.SourceExclude, ",")
}
if len(r.SourceInclude) > 0 {
params["_source_include"] = strings.Join(r.SourceInclude, ",")
}
if r.Timeout != 0 {
params["timeout"] = formatDuration(r.Timeout)
}
if r.DocumentType != "" {
params["type"] = r.DocumentType
}
if r.WaitForActiveShards != "" {
params["wait_for_active_shards"] = r.WaitForActiveShards
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), r.Body)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if r.Body != nil {
req.Header[headerContentType] = headerContentTypeJSON
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f Bulk) WithContext(v context.Context) func(*BulkRequest) {
return func(r *BulkRequest) {
r.ctx = v
}
}
// WithIndex - default index for items which don't provide one.
//
func (f Bulk) WithIndex(v string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Index = v
}
}
// WithDocumentType - default document type for items which don't provide one.
//
func (f Bulk) WithDocumentType(v string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.DocumentType = v
}
}
// WithFields - default comma-separated list of fields to return in the response for updates, can be overridden on each sub-request.
//
func (f Bulk) WithFields(v ...string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Fields = v
}
}
// WithPipeline - the pipeline ID to preprocess incoming documents with.
//
func (f Bulk) WithPipeline(v string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Pipeline = v
}
}
// WithRefresh - if `true` then refresh the effected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes..
//
func (f Bulk) WithRefresh(v string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Refresh = v
}
}
// WithRouting - specific routing value.
//
func (f Bulk) WithRouting(v string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Routing = v
}
}
// WithSource - true or false to return the _source field or not, or default list of fields to return, can be overridden on each sub-request.
//
func (f Bulk) WithSource(v ...string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Source = v
}
}
// WithSourceExclude - default list of fields to exclude from the returned _source field, can be overridden on each sub-request.
//
func (f Bulk) WithSourceExclude(v ...string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.SourceExclude = v
}
}
// WithSourceInclude - default list of fields to extract and return from the _source field, can be overridden on each sub-request.
//
func (f Bulk) WithSourceInclude(v ...string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.SourceInclude = v
}
}
// WithTimeout - explicit operation timeout.
//
func (f Bulk) WithTimeout(v time.Duration) func(*BulkRequest) {
return func(r *BulkRequest) {
r.Timeout = v
}
}
// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the bulk operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1).
//
func (f Bulk) WithWaitForActiveShards(v string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.WaitForActiveShards = v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f Bulk) WithPretty() func(*BulkRequest) {
return func(r *BulkRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f Bulk) WithHuman() func(*BulkRequest) {
return func(r *BulkRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f Bulk) WithErrorTrace() func(*BulkRequest) {
return func(r *BulkRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f Bulk) WithFilterPath(v ...string) func(*BulkRequest) {
return func(r *BulkRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f Bulk) WithHeader(h map[string]string) func(*BulkRequest) {
return func(r *BulkRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatAliasesFunc(t Transport) CatAliases {
return func(o ...func(*CatAliasesRequest)) (*Response, error) {
var r = CatAliasesRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatAliases shows information about currently configured aliases to indices including filter and routing infos.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-alias.html.
//
type CatAliases func(o ...func(*CatAliasesRequest)) (*Response, error)
// CatAliasesRequest configures the Cat Aliases API request.
//
type CatAliasesRequest struct {
Name []string
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatAliasesRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(1 + len("_cat") + 1 + len("aliases") + 1 + len(strings.Join(r.Name, ",")))
path.WriteString("/")
path.WriteString("_cat")
path.WriteString("/")
path.WriteString("aliases")
if len(r.Name) > 0 {
path.WriteString("/")
path.WriteString(strings.Join(r.Name, ","))
}
params = make(map[string]string)
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatAliases) WithContext(v context.Context) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.ctx = v
}
}
// WithName - a list of alias names to return.
//
func (f CatAliases) WithName(v ...string) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.Name = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatAliases) WithFormat(v string) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatAliases) WithH(v ...string) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatAliases) WithHelp(v bool) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatAliases) WithLocal(v bool) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatAliases) WithMasterTimeout(v time.Duration) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatAliases) WithS(v ...string) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatAliases) WithV(v bool) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatAliases) WithPretty() func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatAliases) WithHuman() func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatAliases) WithErrorTrace() func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatAliases) WithFilterPath(v ...string) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatAliases) WithHeader(h map[string]string) func(*CatAliasesRequest) {
return func(r *CatAliasesRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatAllocationFunc(t Transport) CatAllocation {
return func(o ...func(*CatAllocationRequest)) (*Response, error) {
var r = CatAllocationRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatAllocation provides a snapshot of how many shards are allocated to each data node and how much disk space they are using.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-allocation.html.
//
type CatAllocation func(o ...func(*CatAllocationRequest)) (*Response, error)
// CatAllocationRequest configures the Cat Allocation API request.
//
type CatAllocationRequest struct {
NodeID []string
Bytes string
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatAllocationRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(1 + len("_cat") + 1 + len("allocation") + 1 + len(strings.Join(r.NodeID, ",")))
path.WriteString("/")
path.WriteString("_cat")
path.WriteString("/")
path.WriteString("allocation")
if len(r.NodeID) > 0 {
path.WriteString("/")
path.WriteString(strings.Join(r.NodeID, ","))
}
params = make(map[string]string)
if r.Bytes != "" {
params["bytes"] = r.Bytes
}
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatAllocation) WithContext(v context.Context) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.ctx = v
}
}
// WithNodeID - a list of node ids or names to limit the returned information.
//
func (f CatAllocation) WithNodeID(v ...string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.NodeID = v
}
}
// WithBytes - the unit in which to display byte values.
//
func (f CatAllocation) WithBytes(v string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.Bytes = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatAllocation) WithFormat(v string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatAllocation) WithH(v ...string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatAllocation) WithHelp(v bool) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatAllocation) WithLocal(v bool) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatAllocation) WithMasterTimeout(v time.Duration) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatAllocation) WithS(v ...string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatAllocation) WithV(v bool) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatAllocation) WithPretty() func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatAllocation) WithHuman() func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatAllocation) WithErrorTrace() func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatAllocation) WithFilterPath(v ...string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatAllocation) WithHeader(h map[string]string) func(*CatAllocationRequest) {
return func(r *CatAllocationRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatCountFunc(t Transport) CatCount {
return func(o ...func(*CatCountRequest)) (*Response, error) {
var r = CatCountRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatCount provides quick access to the document count of the entire cluster, or individual indices.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-count.html.
//
type CatCount func(o ...func(*CatCountRequest)) (*Response, error)
// CatCountRequest configures the Cat Count API request.
//
type CatCountRequest struct {
Index []string
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatCountRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(1 + len("_cat") + 1 + len("count") + 1 + len(strings.Join(r.Index, ",")))
path.WriteString("/")
path.WriteString("_cat")
path.WriteString("/")
path.WriteString("count")
if len(r.Index) > 0 {
path.WriteString("/")
path.WriteString(strings.Join(r.Index, ","))
}
params = make(map[string]string)
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatCount) WithContext(v context.Context) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.ctx = v
}
}
// WithIndex - a list of index names to limit the returned information.
//
func (f CatCount) WithIndex(v ...string) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.Index = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatCount) WithFormat(v string) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatCount) WithH(v ...string) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatCount) WithHelp(v bool) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatCount) WithLocal(v bool) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatCount) WithMasterTimeout(v time.Duration) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatCount) WithS(v ...string) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatCount) WithV(v bool) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatCount) WithPretty() func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatCount) WithHuman() func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatCount) WithErrorTrace() func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatCount) WithFilterPath(v ...string) func(*CatCountRequest) {
return func(r *CatCountRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatCount) WithHeader(h map[string]string) func(*CatCountRequest) {
return func(r *CatCountRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatFielddataFunc(t Transport) CatFielddata {
return func(o ...func(*CatFielddataRequest)) (*Response, error) {
var r = CatFielddataRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatFielddata shows how much heap memory is currently being used by fielddata on every data node in the cluster.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-fielddata.html.
//
type CatFielddata func(o ...func(*CatFielddataRequest)) (*Response, error)
// CatFielddataRequest configures the Cat Fielddata API request.
//
type CatFielddataRequest struct {
Fields []string
Bytes string
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatFielddataRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(1 + len("_cat") + 1 + len("fielddata") + 1 + len(strings.Join(r.Fields, ",")))
path.WriteString("/")
path.WriteString("_cat")
path.WriteString("/")
path.WriteString("fielddata")
if len(r.Fields) > 0 {
path.WriteString("/")
path.WriteString(strings.Join(r.Fields, ","))
}
params = make(map[string]string)
if r.Bytes != "" {
params["bytes"] = r.Bytes
}
if len(r.Fields) > 0 {
params["fields"] = strings.Join(r.Fields, ",")
}
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatFielddata) WithContext(v context.Context) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.ctx = v
}
}
// WithFields - a list of fields to return the fielddata size.
//
func (f CatFielddata) WithFields(v ...string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Fields = v
}
}
// WithBytes - the unit in which to display byte values.
//
func (f CatFielddata) WithBytes(v string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Bytes = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatFielddata) WithFormat(v string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatFielddata) WithH(v ...string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatFielddata) WithHelp(v bool) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatFielddata) WithLocal(v bool) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatFielddata) WithMasterTimeout(v time.Duration) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatFielddata) WithS(v ...string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatFielddata) WithV(v bool) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatFielddata) WithPretty() func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatFielddata) WithHuman() func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatFielddata) WithErrorTrace() func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatFielddata) WithFilterPath(v ...string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatFielddata) WithHeader(h map[string]string) func(*CatFielddataRequest) {
return func(r *CatFielddataRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatHealthFunc(t Transport) CatHealth {
return func(o ...func(*CatHealthRequest)) (*Response, error) {
var r = CatHealthRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatHealth returns a concise representation of the cluster health.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-health.html.
//
type CatHealth func(o ...func(*CatHealthRequest)) (*Response, error)
// CatHealthRequest configures the Cat Health API request.
//
type CatHealthRequest struct {
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
Ts *bool
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatHealthRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(len("/_cat/health"))
path.WriteString("/_cat/health")
params = make(map[string]string)
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.Ts != nil {
params["ts"] = strconv.FormatBool(*r.Ts)
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatHealth) WithContext(v context.Context) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.ctx = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatHealth) WithFormat(v string) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatHealth) WithH(v ...string) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatHealth) WithHelp(v bool) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatHealth) WithLocal(v bool) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatHealth) WithMasterTimeout(v time.Duration) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatHealth) WithS(v ...string) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.S = v
}
}
// WithTs - set to false to disable timestamping.
//
func (f CatHealth) WithTs(v bool) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.Ts = &v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatHealth) WithV(v bool) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatHealth) WithPretty() func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatHealth) WithHuman() func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatHealth) WithErrorTrace() func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatHealth) WithFilterPath(v ...string) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatHealth) WithHeader(h map[string]string) func(*CatHealthRequest) {
return func(r *CatHealthRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
)
func newCatHelpFunc(t Transport) CatHelp {
return func(o ...func(*CatHelpRequest)) (*Response, error) {
var r = CatHelpRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatHelp returns help for the Cat APIs.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat.html.
//
type CatHelp func(o ...func(*CatHelpRequest)) (*Response, error)
// CatHelpRequest configures the Cat Help API request.
//
type CatHelpRequest struct {
Help *bool
S []string
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatHelpRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(len("/_cat"))
path.WriteString("/_cat")
params = make(map[string]string)
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatHelp) WithContext(v context.Context) func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.ctx = v
}
}
// WithHelp - return help information.
//
func (f CatHelp) WithHelp(v bool) func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.Help = &v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatHelp) WithS(v ...string) func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.S = v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatHelp) WithPretty() func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatHelp) WithHuman() func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatHelp) WithErrorTrace() func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatHelp) WithFilterPath(v ...string) func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatHelp) WithHeader(h map[string]string) func(*CatHelpRequest) {
return func(r *CatHelpRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatIndicesFunc(t Transport) CatIndices {
return func(o ...func(*CatIndicesRequest)) (*Response, error) {
var r = CatIndicesRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatIndices returns information about indices: number of primaries and replicas, document counts, disk size, ...
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-indices.html.
//
type CatIndices func(o ...func(*CatIndicesRequest)) (*Response, error)
// CatIndicesRequest configures the Cat Indices API request.
//
type CatIndicesRequest struct {
Index []string
Bytes string
Format string
H []string
Health string
Help *bool
Local *bool
MasterTimeout time.Duration
Pri *bool
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatIndicesRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(1 + len("_cat") + 1 + len("indices") + 1 + len(strings.Join(r.Index, ",")))
path.WriteString("/")
path.WriteString("_cat")
path.WriteString("/")
path.WriteString("indices")
if len(r.Index) > 0 {
path.WriteString("/")
path.WriteString(strings.Join(r.Index, ","))
}
params = make(map[string]string)
if r.Bytes != "" {
params["bytes"] = r.Bytes
}
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Health != "" {
params["health"] = r.Health
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if r.Pri != nil {
params["pri"] = strconv.FormatBool(*r.Pri)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatIndices) WithContext(v context.Context) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.ctx = v
}
}
// WithIndex - a list of index names to limit the returned information.
//
func (f CatIndices) WithIndex(v ...string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Index = v
}
}
// WithBytes - the unit in which to display byte values.
//
func (f CatIndices) WithBytes(v string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Bytes = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatIndices) WithFormat(v string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatIndices) WithH(v ...string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.H = v
}
}
// WithHealth - a health status ("green", "yellow", or "red" to filter only indices matching the specified health status.
//
func (f CatIndices) WithHealth(v string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Health = v
}
}
// WithHelp - return help information.
//
func (f CatIndices) WithHelp(v bool) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatIndices) WithLocal(v bool) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatIndices) WithMasterTimeout(v time.Duration) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.MasterTimeout = v
}
}
// WithPri - set to true to return stats only for primary shards.
//
func (f CatIndices) WithPri(v bool) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Pri = &v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatIndices) WithS(v ...string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatIndices) WithV(v bool) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatIndices) WithPretty() func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatIndices) WithHuman() func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatIndices) WithErrorTrace() func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatIndices) WithFilterPath(v ...string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatIndices) WithHeader(h map[string]string) func(*CatIndicesRequest) {
return func(r *CatIndicesRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatMasterFunc(t Transport) CatMaster {
return func(o ...func(*CatMasterRequest)) (*Response, error) {
var r = CatMasterRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatMaster returns information about the master node.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-master.html.
//
type CatMaster func(o ...func(*CatMasterRequest)) (*Response, error)
// CatMasterRequest configures the Cat Master API request.
//
type CatMasterRequest struct {
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatMasterRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(len("/_cat/master"))
path.WriteString("/_cat/master")
params = make(map[string]string)
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatMaster) WithContext(v context.Context) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.ctx = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatMaster) WithFormat(v string) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatMaster) WithH(v ...string) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatMaster) WithHelp(v bool) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatMaster) WithLocal(v bool) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatMaster) WithMasterTimeout(v time.Duration) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatMaster) WithS(v ...string) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatMaster) WithV(v bool) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatMaster) WithPretty() func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatMaster) WithHuman() func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatMaster) WithErrorTrace() func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatMaster) WithFilterPath(v ...string) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatMaster) WithHeader(h map[string]string) func(*CatMasterRequest) {
return func(r *CatMasterRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strconv"
"strings"
"time"
)
func newCatNodeattrsFunc(t Transport) CatNodeattrs {
return func(o ...func(*CatNodeattrsRequest)) (*Response, error) {
var r = CatNodeattrsRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// CatNodeattrs returns information about custom node attributes.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cat-nodeattrs.html.
//
type CatNodeattrs func(o ...func(*CatNodeattrsRequest)) (*Response, error)
// CatNodeattrsRequest configures the Cat Nodeattrs API request.
//
type CatNodeattrsRequest struct {
Format string
H []string
Help *bool
Local *bool
MasterTimeout time.Duration
S []string
V *bool
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r CatNodeattrsRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(len("/_cat/nodeattrs"))
path.WriteString("/_cat/nodeattrs")
params = make(map[string]string)
if r.Format != "" {
params["format"] = r.Format
}
if len(r.H) > 0 {
params["h"] = strings.Join(r.H, ",")
}
if r.Help != nil {
params["help"] = strconv.FormatBool(*r.Help)
}
if r.Local != nil {
params["local"] = strconv.FormatBool(*r.Local)
}
if r.MasterTimeout != 0 {
params["master_timeout"] = formatDuration(r.MasterTimeout)
}
if len(r.S) > 0 {
params["s"] = strings.Join(r.S, ",")
}
if r.V != nil {
params["v"] = strconv.FormatBool(*r.V)
}
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f CatNodeattrs) WithContext(v context.Context) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.ctx = v
}
}
// WithFormat - a short version of the accept header, e.g. json, yaml.
//
func (f CatNodeattrs) WithFormat(v string) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.Format = v
}
}
// WithH - comma-separated list of column names to display.
//
func (f CatNodeattrs) WithH(v ...string) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.H = v
}
}
// WithHelp - return help information.
//
func (f CatNodeattrs) WithHelp(v bool) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.Help = &v
}
}
// WithLocal - return local information, do not retrieve the state from master node (default: false).
//
func (f CatNodeattrs) WithLocal(v bool) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.Local = &v
}
}
// WithMasterTimeout - explicit operation timeout for connection to master node.
//
func (f CatNodeattrs) WithMasterTimeout(v time.Duration) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.MasterTimeout = v
}
}
// WithS - comma-separated list of column names or column aliases to sort by.
//
func (f CatNodeattrs) WithS(v ...string) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.S = v
}
}
// WithV - verbose mode. display column headers.
//
func (f CatNodeattrs) WithV(v bool) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.V = &v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f CatNodeattrs) WithPretty() func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f CatNodeattrs) WithHuman() func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f CatNodeattrs) WithErrorTrace() func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f CatNodeattrs) WithFilterPath(v ...string) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f CatNodeattrs) WithHeader(h map[string]string) func(*CatNodeattrsRequest) {
return func(r *CatNodeattrsRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
// Code generated from specification version 5.6.15: DO NOT EDIT
package esapi
import (
"context"
"net/http"
"strings"
)
func newClusterRemoteInfoFunc(t Transport) ClusterRemoteInfo {
return func(o ...func(*ClusterRemoteInfoRequest)) (*Response, error) {
var r = ClusterRemoteInfoRequest{}
for _, f := range o {
f(&r)
}
return r.Do(r.ctx, t)
}
}
// ----- API Definition -------------------------------------------------------
// ClusterRemoteInfo returns the information about configured remote clusters.
//
// See full documentation at http://www.elastic.co/guide/en/elasticsearch/reference/5.x/cluster-remote-info.html.
//
type ClusterRemoteInfo func(o ...func(*ClusterRemoteInfoRequest)) (*Response, error)
// ClusterRemoteInfoRequest configures the Cluster Remote Info API request.
//
type ClusterRemoteInfoRequest struct {
Pretty bool
Human bool
ErrorTrace bool
FilterPath []string
Header http.Header
ctx context.Context
}
// Do executes the request and returns response or error.
//
func (r ClusterRemoteInfoRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
var (
method string
path strings.Builder
params map[string]string
)
method = "GET"
path.Grow(len("/_remote/info"))
path.WriteString("/_remote/info")
params = make(map[string]string)
if r.Pretty {
params["pretty"] = "true"
}
if r.Human {
params["human"] = "true"
}
if r.ErrorTrace {
params["error_trace"] = "true"
}
if len(r.FilterPath) > 0 {
params["filter_path"] = strings.Join(r.FilterPath, ",")
}
req, _ := newRequest(method, path.String(), nil)
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
}
if len(r.Header) > 0 {
if len(req.Header) == 0 {
req.Header = r.Header
} else {
for k, vv := range r.Header {
for _, v := range vv {
req.Header.Add(k, v)
}
}
}
}
if ctx != nil {
req = req.WithContext(ctx)
}
res, err := transport.Perform(req)
if err != nil {
return nil, err
}
response := Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return &response, nil
}
// WithContext sets the request context.
//
func (f ClusterRemoteInfo) WithContext(v context.Context) func(*ClusterRemoteInfoRequest) {
return func(r *ClusterRemoteInfoRequest) {
r.ctx = v
}
}
// WithPretty makes the response body pretty-printed.
//
func (f ClusterRemoteInfo) WithPretty() func(*ClusterRemoteInfoRequest) {
return func(r *ClusterRemoteInfoRequest) {
r.Pretty = true
}
}
// WithHuman makes statistical values human-readable.
//
func (f ClusterRemoteInfo) WithHuman() func(*ClusterRemoteInfoRequest) {
return func(r *ClusterRemoteInfoRequest) {
r.Human = true
}
}
// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f ClusterRemoteInfo) WithErrorTrace() func(*ClusterRemoteInfoRequest) {
return func(r *ClusterRemoteInfoRequest) {
r.ErrorTrace = true
}
}
// WithFilterPath filters the properties of the response body.
//
func (f ClusterRemoteInfo) WithFilterPath(v ...string) func(*ClusterRemoteInfoRequest) {
return func(r *ClusterRemoteInfoRequest) {
r.FilterPath = v
}
}
// WithHeader adds the headers to the HTTP request.
//
func (f ClusterRemoteInfo) WithHeader(h map[string]string) func(*ClusterRemoteInfoRequest) {
return func(r *ClusterRemoteInfoRequest) {
if r.Header == nil {
r.Header = make(http.Header)
}
for k, v := range h {
r.Header.Add(k, v)
}
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册