pax_global_header00006660000000000000000000000064136116132600014511gustar00rootroot0000000000000052 comment=988a59d6272c0c14026fa406f268f2827c07d1d2 elasticsearch-ruby-6.8.1/000077500000000000000000000000001361161326000153165ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/.ci/000077500000000000000000000000001361161326000157675ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/.ci/.dockerignore000066400000000000000000000000431361161326000204400ustar00rootroot00000000000000tmp/* **/Gemfile.lock Gemfile.lock elasticsearch-ruby-6.8.1/.ci/Dockerfile000066400000000000000000000005041361161326000177600ustar00rootroot00000000000000ARG RUBY_TEST_VERSION=2.6 FROM ruby:${RUBY_TEST_VERSION} ENV GEM_HOME="/usr/local/bundle" ENV PATH $GEM_HOME/bin:$GEM_HOME/gems/bin:$PATH ENV QUIET=true ENV CI=true WORKDIR /usr/src/app COPY . . RUN gem update --system RUN gem install bundler RUN bundle install RUN bundle exec rake bundle:clean RUN rake bundle:install elasticsearch-ruby-6.8.1/.ci/certs/000077500000000000000000000000001361161326000171075ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/.ci/certs/ca.crt000077500000000000000000000022601361161326000202070ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDSTCCAjGgAwIBAgIUIwN+0zglsexRKwE1RGHvlCcmrdwwDQYJKoZIhvcNAQEL BQAwNDEyMDAGA1UEAxMpRWxhc3RpYyBDZXJ0aWZpY2F0ZSBUb29sIEF1dG9nZW5l cmF0ZWQgQ0EwHhcNMTkwMjEzMDcyMjQwWhcNMjIwMjEyMDcyMjQwWjA0MTIwMAYD VQQDEylFbGFzdGljIENlcnRpZmljYXRlIFRvb2wgQXV0b2dlbmVyYXRlZCBDQTCC ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANILs0JO0e7x29zeVx21qalK XKdX+AMlGJPH75wWO/Jq6YHtxt1wYIg762krOBXfG6JsFSOIwIv5VrzGGRGjSPt9 OXQyXrDDiQvsBT3rpzLNdDs7KMl2tZswwv7w9ujgud0cYnS1MOpn81rfPc73DvMg xuhplofDx6fn3++PjVRU2FNiIVWyEoaxRjCeGPMBubKZYaYbQA6vYM4Z+ByG727B AyAER3t7xmvYti/EoO2hv2HQk5zgcj/Oq3AJKhnt8LH8fnfm3TnYNM1htvXqhN05 vsvhvm2PHfnA5qLlSr/3W0aI/U/PqfsFDCgyRV097sMIaKkmavb0Ue7aQ7lgtp0C AwEAAaNTMFEwHQYDVR0OBBYEFDRKlCMowWR1rwxE0d1lTEQe5O71MB8GA1UdIwQY MBaAFDRKlCMowWR1rwxE0d1lTEQe5O71MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI hvcNAQELBQADggEBAKbCJ95EBpeuvF70KEt6QU70k/SH1NRvM9YzKryV0D975Jvu HOSm9HgSTULeAUFZIa4oYyf3QUfVoI+2T/aQrfXA3gfrJWsHURkyNmiHOFAbYHqi xA6i249G2GTEjc1+le/M2N2CcDKAmurW6vSGK4upXQbPd6KmnhHREX74zkWjnOa+ +tibbSSOCT4Tmja2DbBxAPuivU9IB1g/hIUmbYQqKffQrBJA0658tz6w63a/Q7xN pCvvbSgiMZ6qcVIcJkBT2IooYie+ax45pQECHthgIUcQAzfmIfqlU0Qfl8rDgAmn 0c1o6HQjKGU2aVGgSRuaaiHaSZjbPIZVS51sOoI= -----END CERTIFICATE----- elasticsearch-ruby-6.8.1/.ci/certs/testnode.crt000077500000000000000000000021731361161326000214540ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDIjCCAgqgAwIBAgIUI4QU6jA1dYSCbdIA6oAb2TBEluowDQYJKoZIhvcNAQEL BQAwNDEyMDAGA1UEAxMpRWxhc3RpYyBDZXJ0aWZpY2F0ZSBUb29sIEF1dG9nZW5l cmF0ZWQgQ0EwHhcNMTkwMjEzMDcyMzEzWhcNMjIwMjEyMDcyMzEzWjATMREwDwYD VQQDEwhpbnN0YW5jZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJeT yOy6EAScZxrULKjHePciiz38grivCrhFFV+dThaRCcl3DhDzb9Eny5q5iEw3WvLQ Rqmf01jncNIhaocTt66VqveXaMubbE8O0LcG6e4kpFO+JtnVF8JTARTc+ux/1uD6 hO1VG/HItM7WQrQxh4hfB2u1AX2YQtoqEtXXEC+UHWfl4QzuzXjBnKCkO/L9/6Tf yNFQWXxKnIiTs8Xm9sEhhSCBJPlLTQu+MX4vR2Uwj5XZmflDUr+ZTenl9qYxL6b3 SWhh/qEl4GAj1+tS7ZZOxE0237mUh3IIFYSWSaMm8K2m/BYHkLNWL5B1dMic0lsv osSoYrQuCef4HQMCitsCAwEAAaNNMEswHQYDVR0OBBYEFFMg4l1GLW8lYbwASY+r YeWYRzIiMB8GA1UdIwQYMBaAFDRKlCMowWR1rwxE0d1lTEQe5O71MAkGA1UdEwQC MAAwDQYJKoZIhvcNAQELBQADggEBAEQrgh1xALpumQTzsjxFRGque/vlKTgRs5Kh xtgapr6wjIbdq7dagee+4yNOKzS5lGVXCgwrJlHESv9qY0uumT/33vK2uduJ7NAd fR2ZzyBnhMX+mkYhmGrGYCTUMUIwOIQYa4Evis4W+LHmCIDG03l7gLHfdIBe9VMO pDZum8f6ng0MM49s8/rXODNYKw8kFyUhnfChqMi/2yggb1uUIfKlJJIchkgYjE13 zuC+fjo029Pq1jeMIdxugLf/7I/8NiW1Yj9aCXevUXG1qzHFEuKAinBXYOZO/vWS LaEqOhwrzNynwgGpYAr7Rfgv4AflltYIIav4PZT03P7fbyAAf8s= -----END CERTIFICATE----- elasticsearch-ruby-6.8.1/.ci/certs/testnode.key000077500000000000000000000032171361161326000214540ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAl5PI7LoQBJxnGtQsqMd49yKLPfyCuK8KuEUVX51OFpEJyXcO EPNv0SfLmrmITDda8tBGqZ/TWOdw0iFqhxO3rpWq95doy5tsTw7Qtwbp7iSkU74m 2dUXwlMBFNz67H/W4PqE7VUb8ci0ztZCtDGHiF8Ha7UBfZhC2ioS1dcQL5QdZ+Xh DO7NeMGcoKQ78v3/pN/I0VBZfEqciJOzxeb2wSGFIIEk+UtNC74xfi9HZTCPldmZ +UNSv5lN6eX2pjEvpvdJaGH+oSXgYCPX61Ltlk7ETTbfuZSHcggVhJZJoybwrab8 FgeQs1YvkHV0yJzSWy+ixKhitC4J5/gdAwKK2wIDAQABAoIBAQCRFTJna/xy/WUu 59FLR4qAOj8++JgCwACpue4oU7/vl6nffSYokWoAr2+RzG4qTX2vFi3cpA8+dGCn sLZvTi8tWzKGxBTZdg2oakzaMzLr74SeZ052iCGyrZJGbvF6Ny7srr1XEXSq6+os ZCb6pMHOhO7saBdiKMAsY8MdjTl/33AduuE6ztqv+L92xTr2g4QlbT1KvWlEgppU k4Gy7zdETkPBTSH/17ZwyGJoJICIAhbL4IpmOM4dPIg8nFkVPPpy6p0z4uGjtgnK nreZ2EKMzCafBaHn7A77gpi0OrQdl6pe0fsGqv/323YjCJPbwwl5TsoNq44DzwiX 3M7XiVJxAoGBAOCne56vdN4uZmCgLVGT2JSUNVPOu4bfjrxWH6cslzrPT2Zhp3lO M4axZ3gmcervV252YEZXntXDHHCSfrECllRN1WFD63XmyQ/CkhuvZkkeRHfzL1TE EdqHOTqs4sRETZ7+RITFC81DZQkWWOKeyXMjyPBqd7RnThQHijB1c8Y5AoGBAKy6 CVKBx+zz5crVD0tz4UhOmz1wRNN0CL0l+FXRuFSgbzMIvwpfiqe25crgeLHe2M2/ TogdWbjZ2nUZQTzoRsSkQ6cKHpj+G/gWurp/UcHHXFVwgLSPF7c3KHDtiYq7Vqw0 bvmhM03LI6+ZIPRV7hLBr7WP7UmpAiREMF7tTnmzAoGBAIkx3w3WywFQxtblmyeB qbd7F2IaE23XoxyjX+tBEQ4qQqwcoSE0v8TXHIBEwjceeX+NLVhn9ClJYVniLRq+ oL3VVqVyzB4RleJZCc98e3PV1yyFx/b1Uo3pHOsXX9lKeTjKwV9v0rhFGzPEgP3M yOvXA8TG0FnM6OLUg/D6GX0JAoGAMuHS4TVOGeV3ahr9mHKYiN5vKNgrzka+VEod L9rJ/FQOrfADpyCiDen5I5ygsXU+VM3oanyK88NpcVlxOGoMft0M+OYoQVWKE7lO ZKYhBX6fGqQ7pfUJPXXIOgwfmni5fZ0sm+j63g3bg10OsiumKGxaQJgXhL1+3gQg Y7ZwibUCgYEAlZoFFvkMLjpOSaHk1z5ZZnt19X0QUIultBwkumSqMPm+Ks7+uDrx thGUCoz4ecr/ci4bIUY7mB+zfAbqnBOMxreJqCRbAIuRypo1IlWkTp8DywoDOfMW NfzjVmzJ7EJu44nGmVAi1jw4Pbseivvi1ujMCoPgaE8I1uSh144bwN8= -----END RSA PRIVATE KEY----- elasticsearch-ruby-6.8.1/.ci/docker/000077500000000000000000000000001361161326000172365ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/.ci/docker/run-client000066400000000000000000000025301361161326000212410ustar00rootroot00000000000000#!/usr/bin/env bash # # Runs the client tests via Docker with the expectation that the required # environment variables have already been exported before running this script. # # The required environment variables include: # # - $ELASTICSEARCH_VERSION # # run elasticsearch docker run \ --rm \ --env "node.attr.testattr=test" \ --env "path.repo=/tmp" \ --env "repositories.url.allowed_urls=http://snapshot.*" \ --env "http.port=9200" \ --env "discovery.zen.minimum_master_nodes=2" \ --env "discovery.zen.ping.unicast.hosts=elasticsearch" \ --network=esnet \ --name=elasticsearch \ --detach \ docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION} # run elasticsearch-2 docker run \ --rm \ --env "node.attr.testattr=test" \ --env "path.repo=/tmp" \ --env "repositories.url.allowed_urls=http://snapshot.*" \ --env "http.port=9201" \ --env "discovery.zen.minimum_master_nodes=2" \ --env "discovery.zen.ping.unicast.hosts=elasticsearch" \ --network=esnet \ --name=elasticsearch-2 \ --detach \ docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION} # run the client tests docker run \ --network=esnet \ --env "TEST_ES_SERVER=http://elasticsearch:9200" \ --volume $repo:/usr/src/app \ --name elasticsearch-ruby \ --rm \ elastic/elasticsearch-ruby \ bundle exec rake test:client elasticsearch-ruby-6.8.1/.ci/docker/run-rest_api000066400000000000000000000015661361161326000216010ustar00rootroot00000000000000#!/usr/bin/env bash # # Runs the client tests via Docker with the expectation that the required # environment variables have already been exported before running this script. # # The required environment variables include: # # - $ELASTICSEARCH_VERSION # # run elasticsearch docker run \ --rm \ --env "node.attr.testattr=test" \ --env "path.repo=/tmp" \ --env "repositories.url.allowed_urls=http://snapshot.*" \ --env "http.port=9200" \ --env "discovery.zen.ping.unicast.hosts=elasticsearch" \ --network=esnet \ --name=elasticsearch \ --detach \ docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION} # run the client tests docker run \ --network=esnet \ --env "TEST_ES_SERVER=http://elasticsearch:9200" \ --volume $repo:/usr/src/app \ --name elasticsearch-ruby \ --rm \ elastic/elasticsearch-ruby \ bundle exec rake test:rest_api elasticsearch-ruby-6.8.1/.ci/docker/run-security000066400000000000000000000040151361161326000216320ustar00rootroot00000000000000#!/usr/bin/env bash # # Runs the client tests via Docker with the expectation that the required # environment variables have already been exported before running this script. # # The required environment variables include: # # - $ELASTICSEARCH_VERSION # repo=$(pwd) testnodecrt="/.ci/certs/testnode.crt" testnodekey="/.ci/certs/testnode.key" cacrt="/.ci/certs/ca.crt" docker run \ --rm \ --env "node.attr.testattr=test" \ --env "path.repo=/tmp" \ --env "repositories.url.allowed_urls=http://snapshot.*" \ --env "discovery.type=single-node" \ --env "ES_JAVA_OPTS=-Xms1g -Xmx1g" \ --env "ELASTIC_PASSWORD=changeme" \ --env "xpack.security.enabled=true" \ --env "xpack.license.self_generated.type=trial" \ --env "xpack.security.http.ssl.enabled=true" \ --env "xpack.security.http.ssl.verification_mode=certificate" \ --env "xpack.security.http.ssl.key=certs/testnode.key" \ --env "xpack.security.http.ssl.certificate=certs/testnode.crt" \ --env "xpack.security.http.ssl.certificate_authorities=certs/ca.crt" \ --env "xpack.security.transport.ssl.enabled=true" \ --env "xpack.security.transport.ssl.key=certs/testnode.key" \ --env "xpack.security.transport.ssl.certificate=certs/testnode.crt" \ --env "xpack.security.transport.ssl.certificate_authorities=certs/ca.crt" \ --volume "$repo$testnodecrt:/usr/share/elasticsearch/config/certs/testnode.crt" \ --volume "$repo$testnodekey:/usr/share/elasticsearch/config/certs/testnode.key" \ --volume "$repo$cacrt:/usr/share/elasticsearch/config/certs/ca.crt" \ --network=esnet \ --name=elasticsearch \ --detach \ docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION} # run the client tests docker run \ --network=esnet \ --env "TEST_ES_SERVER=elasticsearch:9200" \ --env "ELASTIC_PASSWORD=changeme" \ --env "ELASTIC_USER=elastic" \ --env "TEST_SUITE=security" \ --env "SINGLE_TEST=${SINGLE_TEST}" \ --volume $repo:/usr/src/app \ --name elasticsearch-ruby \ --rm \ elastic/elasticsearch-ruby \ bundle exec rake test:security elasticsearch-ruby-6.8.1/.ci/jobs/000077500000000000000000000000001361161326000167245ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/.ci/jobs/defaults.yml000066400000000000000000000027551361161326000212670ustar00rootroot00000000000000--- ##### GLOBAL METADATA - meta: cluster: clients-ci ##### JOB DEFAULTS - job: project-type: matrix logrotate: daysToKeep: 30 numToKeep: 100 properties: - github: url: https://github.com/elastic/elasticsearch-ruby/ - inject: properties-content: HOME=$JENKINS_HOME concurrent: true node: flyweight scm: - git: name: origin credentials-id: f6c7695a-671e-4f4f-a331-acdce44ff9ba reference-repo: /var/lib/jenkins/.git-references/elasticsearch-ruby.git branches: - ${branch_specifier} url: git@github.com:elastic/elasticsearch-ruby.git wipe-workspace: 'True' triggers: - github - timed: '@daily' axes: - axis: type: slave name: label values: - linux - axis: type: yaml filename: .ci/test-matrix.yml name: ELASTICSEARCH_VERSION - axis: type: yaml filename: .ci/test-matrix.yml name: RUBY_TEST_VERSION - axis: type: yaml filename: .ci/test-matrix.yml name: TEST_SUITE yaml-strategy: exclude-key: exclude filename: .ci/test-matrix.yml wrappers: - ansicolor - timeout: type: absolute timeout: 120 fail: true - timestamps - workspace-cleanup builders: - shell: |- #!/usr/local/bin/runbld .ci/run-tests publishers: - email: recipients: infra-root+build@elastic.co elasticsearch-ruby-6.8.1/.ci/jobs/elastic+elasticsearch-ruby+6.x.yml000066400000000000000000000006031361161326000252660ustar00rootroot00000000000000--- - job: name: elastic+elasticsearch-ruby+6.x display-name: 'elastic / elasticsearch-ruby # 6.x' description: Testing the elasticsearch-ruby 6.x branch. parameters: - string: name: branch_specifier default: refs/heads/6.x description: the Git branch specifier to build (<branchName>, <tagName>, <commitId>, etc.) elasticsearch-ruby-6.8.1/.ci/jobs/elastic+elasticsearch-ruby+master.yml000066400000000000000000000006171361161326000261530ustar00rootroot00000000000000--- - job: name: elastic+elasticsearch-ruby+master display-name: 'elastic / elasticsearch-ruby # master' description: Testing the elasticsearch-ruby master branch. parameters: - string: name: branch_specifier default: refs/heads/master description: the Git branch specifier to build (<branchName>, <tagName>, <commitId>, etc.) elasticsearch-ruby-6.8.1/.ci/jobs/elastic+elasticsearch-ruby+pull-request.yml000066400000000000000000000010501361161326000273120ustar00rootroot00000000000000--- - job: name: elastic+elasticsearch-ruby+pull-request display-name: 'elastic / elasticsearch-ruby # pull-request' description: Testing of elasticsearch-ruby pull requests. scm: - git: branches: - ${ghprbActualCommit} refspec: +refs/pull/*:refs/remotes/origin/pr/* triggers: - github-pull-request: org-list: - elastic allow-whitelist-orgs-as-admins: true github-hooks: true status-context: clients-ci cancel-builds-on-update: true publishers: [] elasticsearch-ruby-6.8.1/.ci/run-tests000077500000000000000000000022221361161326000176570ustar00rootroot00000000000000#!/usr/bin/env bash # # Runs the client tests via Docker with the expectation that the required # environment variables have already been exported before running this script. # # The required environment variables include: # # - $TEST_SUITE # set -eo pipefail export RUBY_TEST_VERSION=${RUBY_TEST_VERSION:-2.6.5} export ELASTICSEARCH_VERSION=${ELASTICSEARCH_VERSION:-6.8.6} export SINGLE_TEST=${SINGLE_TEST} set +x export VAULT_TOKEN=$(vault write -field=token auth/approle/login role_id="$VAULT_ROLE_ID" secret_id="$VAULT_SECRET_ID") unset VAULT_ROLE_ID VAULT_SECRET_ID VAULT_TOKEN set -x function cleanup { docker container rm --force --volumes elasticsearch > /dev/null 2>&1 || true docker container rm --force --volumes elasticsearch-2 > /dev/null 2>&1 || true docker container rm --force --volumes elasticsearch-ruby > /dev/null 2>&1 || true docker network rm esnet > /dev/null } trap cleanup EXIT # create network and volume docker network create esnet # create client image docker build \ --file .ci/Dockerfile \ --tag elastic/elasticsearch-ruby \ --build-arg RUBY_TEST_VERSION=${RUBY_TEST_VERSION} \ . sh .ci/docker/run-${TEST_SUITE} elasticsearch-ruby-6.8.1/.ci/run-tests-security000066400000000000000000000040531361161326000215250ustar00rootroot00000000000000#!/usr/bin/env bash # # Runs the client tests via Docker with the expectation that the required # environment variables have already been exported before running this script. # # The required environment variables include: # # - $ELASTICSEARCH_VERSION # - $RUBY_TEST_VERSION # - $TEST_SUITE # repo=$(pwd) testnodecrt="/.ci/certs/testnode.crt" testnodekey="/.ci/certs/testnode.key" cacrt="/.ci/certs/ca.crt" docker run \ --rm \ --env "node.attr.testattr=test" \ --env "path.repo=/tmp" \ --env "repositories.url.allowed_urls=http://snapshot.*" \ --env "discovery.type=single-node" \ --env "ES_JAVA_OPTS=-Xms1g -Xmx1g" \ --env "ELASTIC_PASSWORD=changeme" \ --env "xpack.security.enabled=true" \ --env "xpack.license.self_generated.type=trial" \ --env "xpack.security.http.ssl.enabled=true" \ --env "xpack.security.http.ssl.verification_mode=certificate" \ --env "xpack.security.http.ssl.key=certs/testnode.key" \ --env "xpack.security.http.ssl.certificate=certs/testnode.crt" \ --env "xpack.security.http.ssl.certificate_authorities=certs/ca.crt" \ --env "xpack.security.transport.ssl.enabled=true" \ --env "xpack.security.transport.ssl.key=certs/testnode.key" \ --env "xpack.security.transport.ssl.certificate=certs/testnode.crt" \ --env "xpack.security.transport.ssl.certificate_authorities=certs/ca.crt" \ --volume "$repo$testnodecrt:/usr/share/elasticsearch/config/certs/testnode.crt" \ --volume "$repo$testnodekey:/usr/share/elasticsearch/config/certs/testnode.key" \ --volume "$repo$cacrt:/usr/share/elasticsearch/config/certs/ca.crt" \ --network=esnet \ --name=elasticsearch \ --detach \ docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION} # run the client tests docker run \ --network=esnet \ --env "TEST_ES_SERVER=elasticsearch:9200" \ --env "ELASTIC_PASSWORD=changeme" \ --env "ELASTIC_USER=elastic" \ --env "CODECOV_TOKEN" \ --env "TEST_SUITE=security" \ --volume $repo:/usr/src/app \ --name elasticsearch-ruby \ --rm \ elastic/elasticsearch-ruby \ bundle exec rake test:security elasticsearch-ruby-6.8.1/.ci/test-matrix.yml000066400000000000000000000002261361161326000207730ustar00rootroot00000000000000--- ELASTICSEARCH_VERSION: - 6.8-SNAPSHOT RUBY_TEST_VERSION: - 2.7.0 - 2.6.5 - 2.5.7 - 2.4.9 TEST_SUITE: - rest_api - client - security exclude: ~ elasticsearch-ruby-6.8.1/.gitignore000066400000000000000000000001741361161326000173100ustar00rootroot00000000000000.config .yardoc _yardoc coverage **/test/reports/ **/test/html_reports/ doc/ rdoc/ tmp Gemfile.lock .DS_Store *.log .idea/* elasticsearch-ruby-6.8.1/.travis.yml000066400000000000000000000035301361161326000174300ustar00rootroot00000000000000# ----------------------------------------------------------------------- # Configuration file for https://travis-ci.org/elastic/elasticsearch-ruby # ----------------------------------------------------------------------- dist: trusty sudo: required language: ruby branches: only: - master - 6.x - 5.x env: global: - TEST_ES_SERVER=http://localhost:9250 - ELASTICSEARCH_VERSION=6.7.0 matrix: include: - rvm: ruby-head jdk: oraclejdk8 env: TEST_SUITE=unit - rvm: 2.3.8 jdk: oraclejdk8 env: TEST_SUITE=unit - rvm: 2.4.9 jdk: oraclejdk8 env: TEST_SUITE=unit - rvm: 2.5.7 jdk: oraclejdk8 env: TEST_SUITE=unit - rvm: 2.6.5 jdk: oraclejdk8 env: TEST_SUITE=unit - rvm: jruby-9.2.9.0 jdk: oraclejdk8 env: TEST_SUITE=unit - rvm: 2.6.5 jdk: oraclejdk8 env: QUIET=y TEST_SUITE=integration allow_failures: - rvm: ruby-head jdk: oraclejdk8 env: TEST_SUITE=unit before_install: - ls $PWD - pkill -9 -f elasticsearch || true - gem update --system - gem --version - gem update bundler -q - bundle version - bundle install - bundle exec rake setup - bundle exec rake elasticsearch:update - curl -sS https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${ELASTICSEARCH_VERSION}.tar.gz | tar xz -C /tmp - /tmp/elasticsearch-${ELASTICSEARCH_VERSION}/bin/elasticsearch-keystore create - > [[ -n "$TEST_SUITE" ]] && [[ "$TEST_SUITE" == "integration" ]] && TEST_CLUSTER_COMMAND=/tmp/elasticsearch-6.7.0/bin/elasticsearch bundle exec rake -I elasticsearch-extensions/lib test:cluster:start && curl http://localhost:9250/_cluster/health?level=shards || true install: - rake bundle:clean - rake bundle:install script: - rake test:$TEST_SUITE notifications: disable: true elasticsearch-ruby-6.8.1/CHANGELOG.md000066400000000000000000000604531361161326000171370ustar00rootroot00000000000000## 6.8.1 * Lock the version of Faraday: Faraday 1.0 was released with breaking changes. Thank you @taylorthurlow :+1: (#752) * Add support for Ruby 2.7 * 6.x releases are now tested in the latests Ruby versions: 2.4.9, 2.5.7, 2.6.5 and 2.7.0 * Fix bad range value error ## 6.8.0 * Supports Elasticsearch 6 up to v6.8.0 ## 6.3.1 ### API * Add delete_template back * Add field_stats back * Add get_template back * Add indices/delete_mapping back * Add indices/delete_warmer back * Add indices/get_aliases back * Add indices/get_warmer back * Add indices/optimize back * Add indices/put_warmer back * Add indices/seal back * Add indices/snapshot_index back * Add indices/status back * Add list_benchmarks back * Add mpercolate back * Add nodes/shutdown back * Add percolate back * Add put_template back * Add remote/info back * Add search_exists back * Add suggest back * Add mlt back ## 6.3.0 ### API * Update bulk method * Generate code with params registry * Update cat.aliases method * Update cat.allocation method * Update cat.count method * Update cat.fielddata method * Update cat.health method * Update cat.help method * Update cat.indices method * Update cat API methods * Update clear_scroll API * Update cluster API endpoint methods * Update top-level API endpoint methods * Update all methods based on rest-api-spec * Fix minor issues with API methods * Add unfreeze and freeze endpoints back * Fix missing params for cat APIs * Add support for node_id in cluster/stats * Reference current version, not master * Keep create method as-is * Reference current version, not master for ingest/plugins * Account for indices.create/20_mix_typeless_typeful not cleaning up after itself * Add missing params ### XPACK * Update API for 6.7.0 * Updates to support 6.7.0 * Blacklist individual tests, not entire files * Sometimes the SINGLE_TEST env variable is the empty string * Fix logic for checking if a verison should be skipped ## 6.2.0 ### Client * Assert that connection count is at least previous count when reloaded * Don't mutate user-defined options upon initialization of client * Only dup options if they are passed in * Convert client tests to rspec for 6.x * Redacted password if host info is printed in error message * Adds tests for not including password in logged error message * The redacted string change will be in 6.1.1 * Add more tests for different ways to specify client host argument * Do not duplicate connections in connection pool after rebuild (#591) ### API * Update split indices method and test * Port api/actions tests to rspec (#543) * Account for escape_utils not being available for JRuby * Convert cat API tests to rspec (#547) * Convert cluster API tests to rspec (#548) * Convert indices tests to rspec (#549) * Fix documentation of #indices.analyze * Avoid instantiating an array of valid params for each request, each time it is called (#550) * Skip tests with 'default_shards' in features (#558) * Convert snapshot, ingest, tasks, nodes api tests to rspec (#563) * Update documentation for msearch * Remove reference to deprecated format option for _analyze endpoint * Correct endpoints used for get and put search template * Fix minor typo * Note that a non-empty body argument is required for the bulk api * Support ignore_throttled option on search API ### DSL * Convert aggregations/pipeline tests to rspec (#564) * Convert aggregations tests to rspec (#566) * Convert filters tests to rspec (#568) * Fix bug in applying no_match_filter to indices filter * Fix integration tests for join field syntax * Update test for current elasticsearch version * Include type in index document operation in test * minor: fix spacing * Convert queries tests to rspec (#569) * spec directory structure should mirror code directory structure * Ensure that filters are registered when called on bool queries (#609) * Apply PR 572 to 6.x branch * Ensure that specs are running as part of integration tests * Revert previous commit; spec tests are running as part of unit tests ## EXT:6.2.0 * Remove gem dependency on 'oj' gem and instead warn if LoadError * Remove gem dependency on 'patron' gem and instead warn if LoadError * Make ruby-prof a gem development dependency * Fix jar regex determining elasticsearch version (#557) * Added, that determining version from .jar file is more defensive ## XPACK:6.2.0 * Add ruby-prof as a development dependency * Handle multiple roles passed to get_role_mapping * Minor updates to xpack api methods (#586) * Rewrite xpack rest api yaml test handler (#585) * Set up docker files for running security (Platinum) tests on Jenkins (#606) * Run Platinum rest api tests on 6.6.1 (#615) * Fix mistake in testing version range so test can be skipped * Support freeze and unfreeze APIs * Adjust rollup get_jobs endpoint * Improve error handling in spec_helper and action execution * Revert commit cd6b88deccdd7ad128364c0dc0d7c3326d650730 * Fix skip test logic ## 6.1.0 ### X-Pack * Added the `elasticsearch-xpack` source code into the repository ## 6.0.3 ### API * Update the Reindex API to support :slices * Update the "Delete By Query" API to support :slices * Added the `wait_for_no_initializing_shards` option for "Cluster Health" API * Added the `wait_for_active_shards` option for the "Indices Open" API * Added the "Indices Split" API ## EXT:6.0.3 * Add elasticsearch-extensions homepage to Gemspec ## 6.0.2 ### Client * Allow passing request headers in `perform_request` ### API * Allow passing headers in `perform_request` * Set application/x-ndjson content type on Bulk and Msearch requests ## 6.0.1 * Updated the compatibility table for 6.x ### API * Added the "Cluster Remote Info" API * Speed up `Elasticsearch::API::Utils.__listify` * Speed up `Elasticsearch::API::Utils.__pathify` * Use "String#strip" and "String.empty?" in `Utils.__pathify` * Updated the inline documentation for using scripts in the "Update" API * Updated the "Scroll" API inline example with passing the scroll ID in the body * Marked the `percolate` method as deprecated and added an example for current percolator * Fixed, that `Utils.__report_unsupported_parameters` and `Utils.__report_unsupported_method` use `Kernel.warn` so they can be suppressed * Fixed the "greedy" regex in the `Utils.__rescue_from_not_found` method * Fixed the incorrect `create` method ### Client * Fixed, that trailing slash is removed from URL in `Client#__extract_hosts` ## 6.0.0 Elasticsearch 6.0 compatibility. ### API * Added missing arguments to the "Exists" API * Added missing parameters to the "Indices Clear Cache" API * Added missing parameters to the "Indices Delete" API * Added missing parameters to the "Multi Search" API * Added missing parameters to the "Search" API * Added missing parameters to the "Search" API * Added requirement for the `id` argument for the "Create" API * Added support for additional parameters to the "Cluster State" API * Added support for additional parameters to the "Rollover" API * Added the "Remote Info" API * Added the "verbose" parameter to the "Get Snapshot" API * Aded the "Get Task" API * Changed, that the YAML test content is not printed unless `DEBUG` is set * Fixed a failing unit test for the "Create Document" API * Fixed handling of parameters in the "Rollover" API * Fixed incorrect handling of `catch` clauses in the YAML tests runner * Fixed incorrect handling of node ID in the "Nodes Stats" API * Fixed incorrect URL parameter in "Indices Flush" unit test * Fixed the failing unit tests for "Scroll" APIs * Fixes for the "Scroll" API * Updated and improved the YAML test runner ### Client * Added default value 'application/json' for the 'Content-Type' header * Added escaping of username and password in URL * Added proper handling of headers in client options to the Manticore adapter * Don't block waiting for body on HEAD requests * Fixed double logging of failed responses * Fixed incorrect test behaviour when the `QUIET` environment variable is set * Fixed the bug with `nil` value of `retry_on_status` * Fixed the incorrect paths and Typhoeus configuration in the benchmark tests * Fixed the integration tests for client * Fixed typo in default port handling during `__build_connections` * Swallow logging of exceptions when the `ignore` is specified ## EXT:0.0.27 * Allow passing the Elasticsearch version to the Test::Cluster extension * Improved the profiling extension * Added that the timeout in `__determine_version` is configurable and increased the default value * Improved the integration test for the `Test::Cluster` extension * Improved the test infrastructure * Added the Elasticsearch start command for the 6.x version to the test/cluster extension * Added the "oj" and "patron" Rubygem to the list of runtime dependencies ## DSL:0.1.5 * Added support for the ["Exists" Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html) * Added missing `like` and `unlike` options to the ["More Like This" Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html) * Added missing `time_zone` option to the ["Query String" Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html) * Added missing `inner_hits` option to the [Nested Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html) * Allow calling the `filter` method for the [Bool Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html) multiple times * Added missing `minimum_should_match`, `prefix_length`, `max_expansions`, `fuzzy_rewrite`, `analyzer`, `lenient`, `zero_terms_query` and `cutoff_frequency` options to the [Match Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html) * Added missing `minimum_should_match` and `boost` options to the [Bool Query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html) * Refactored the [Aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html) collection into its own `AggregationsCollection` class ## EXT:0.0.23 * Fixed removing the data directory for Elasticsearch 5 and 6 in the test cluster * Added, that Elasticsearch process is properly killed when determining version * Updated the test cluster class to be compatible Elasticsearch 6.x * Added `the max_local_storage_nodes` setting to the start command arguments for Elasticsearch 5.x * Improved the documentation and error messsages for the test cluster * Updated the "Reindex" extension for Elasticsearch 5.x ## DSL:0.1.4 * Added correct implementation of `Sort#empty?` * Added the `filter` method to the Bool query * Added the pipeline aggregations * Allowed access to calling context from search block ## EXT:0.0.22 * Refactored and significantly improved the "Reindex" extension * Refactored and improved the `Extensions::Test::Cluster` extension ## 1.0.18 * Fixed the incorrect Rake dependency on Ruby 1.8 and updated the Rake dependency to 11.1 * Simplified the main README and added the information about the DSL and Watcher libraries ### API * Added `ignore: 404` to integration test setup blocks * Added options to the "Indices Get" and "Indices Flush Synced" APIs * Added the "Cat Tasks", "Cluster Stats", "Explain allocation", "Ingest", "Reindex" and "Update By Query" APIs * Added the `:terminate_after` parameter to the "Search" API * Added the `:timeout` option to the Nodes "Hot Threads", "Info" and "Stats" APIs * Added the `:timeout` parameter to the Nodes "Hot Threads", "Info" and "Stats" APIs * Added the `:verbose` option to the "Indices Segments" API and fixed formatting * Added the `explain` option to the "Analyze" API * Added the `filter` parameter for the "Indices Analyze" API * Added the `group_by` option to the "Tasks List" API * Added the `include_defaults` option to the "Get Cluster Settings" API * Added the `include_defaults` parameter to the "Indices" APIs * Added the `preserve_existing` option to the "Indices Put Settings" API * Added the `request_cache` parameter to the "Search" API * Added the `retry_failed` option to the "Cluster Reroute" API * Added the `size` parameter to the "Cat Thread Pool" API * Added the `update_all_types` parameter to "Indices Create" and "Indices Put Mapping" APIs * Added the parameters for ingest nodes into the "Bulk" and "Index" APIs * Fixes and improvements of handling the API method parameters * Changed, that the "Ping" API returns false also on connection errors (server "not reachable") * Added a `Utils.__report_unsupported_method` and `Utils.__report_unsupported_parameters` methods ### Client * Fixed, that the clients tries to deserialize an empty body * Fixed, that dead connections have not been removed during reloading, leading to leaks ## EXT:0.0.21 * Improved the documentation for the "Backup" extension and added it to the main README * Added the information about the "Reindex" extension to the README * Added a reindex extension * Improved the `Elasticsearch::Extensions::Test::Cluster` extension ## 1.0.17 ### Client * Fixed, that existing connections are not re-initialized during reloading ("sniffing") ## 1.0.16 * Added notes about ES 2.x compatibility * Fixes and updates to the Travis CI configuration * Updated the `elasticsearch:build` Rake task ### API * Added the ability to set a custom JSON serializer * Added, that`fields` and `fielddata_fields` in the Search API are not escaped * Fixed the incorrect handling of `:data` keys in the Utils#__bulkify method * Added fixes to suppress warnings in the verbose mode * Added support for new Cat API calls ### Client * Added, that username and password is automatically escaped in the URL * Changed, that the password is replaced with `*` characters in the log * Bumped the "manticore" gem dependency to 0.5 * Improved the thread-safety of reloading connections * Improved the Manticore HTTP client * Fixed, that connections are reloaded _before_ getting a connection * Added a better interface for configuring global HTTP settings such as protocol or authentication ## DSL:0.1.3 * Changed, that `global` aggregation takes a block * Updated the README example to work with Elasticsearch 2.x * Improved the documentation and integration tests for inner (nested) aggregaation * Added the option method `field` and `script` to the "stats" aggregation ## EXT:0.0.20 * Fixed the implementation of keeping the test cluster data and state around between restarts ## 1.0.15 * Updated the Travis CI configuration ### API * Added `bytes` as a valid parameter to "Shards" and "Segments" Cat API * Added support for the `local` argument in the "Get Warmer" API * Added support for `fields` argument in the "Get Field Mapping" API * Fixed an error in the YAML runner handling of ENV['TEST_CLUSTER_PARAMS'] * Validate and extract params from indices.get_warmer arguments ### Client * Added the option to configure the Faraday adapter using a block and the relevant documentation * Added information about configuring the client for the Amazon Elasticsearch Service * Added the `retry_on_status` option to retry on specific HTTP response statuses * Changed, that transports can close connections during `__rebuild_connections` * Added, that the Manticore adapter closes connections during reload ("sniffing") ## 1.0.14 * Clarified version support of Elasticsearch * Improved the `elasticsearch:build` Rake task to work with branch names ### API * Added support for the `:ignore` option to the "Snapshot and Restore" API * Added support for the `:ignore` option to the Status API * Added the "Cat Nodeattrs" API * Added the "fields" parameter to the Bulk API * Added the "Render Search Template" API * Added the "Shard Stores" API * Added, that document ID is URL-escaped when percolating an existing document * Allow passing TEST_CLUSTER_PARAMS to the test cluster * Define the path to core REST tests dynamically based on Elasticsearch version * Fixed example in "Get Warmer" API * Fixed incorrect documentation and link in the "Clear Cache" API * Fixed integration tests for the "Snapshot and Restore" API * Fixed the incorrect path in "Field Stats" API and added support for the `body` argument * Fixed, that `type` is not added both to path and URL parameters in the Bulk API * Updated the examples in README and documentation (facets -> aggregations) ### Client * Added an argument to control clearing out the testing cluster * Fixed, that reloading connections works with SSL, authentication and proxy/Shield * Highlight the need to set `retry_on_failure` option with multiple hosts in documentation ## DSL:0.1.2 * Added fuzziness option to the "Match" query * Added the `format` option to range filter and query * Added, that `*args` are passed to the Options initializer ## EXT:0.0.19 * Added `es.path.repo` to the testing cluster * Added `path_logs` option to test cluster * Added the `testattr` attribute to the testing cluster * Changed the default network host for the testing cluster to "localhost", to enable new "multicast" ## 1.0.13 ### Client * Added, that connection reloading supports Elasticsearch 2.0 output * Improved thread safety in parts of connection handling code ## DSL:1.0.1 * Added additional option methods to the "Multi Match" query ## 1.0.12 ### API * Fixed a regression when rescuing NotFound errors ## 1.0.11 * Fixed incorrect Hash syntax for Ruby 1.8 in client.rb ## 1.0.10 ### Client * Cleaned up handling the `reload_connections` option for transport * Be more defensive when logging exception * Added, that the Manticore transport respects the `transport_options` argument * Added a top level `request_timeout` argument ### API * Added the "Indices Seal" API * Added unified/centralized `NotFound` error handling ### Watcher * Added the integration with Elasticsearch Watcher plugin ## 1.0.9 * Improved the `elasticsearch::build` task in the main Rakefile * Merged the 'elasticsearch-dsl' gem into the main repository ### Client * Changed the argument compatibility check in `__extract_hosts()` from `respond_to?` to `is_a?` * Document the DEFAULT_MAX_RETRIES value for `retry_on_failure` * Leave only Typhoeus as the primary example of automatically detected & used HTTP library in README * Make sure the `connections` object is an instance of Collection * Prevent mutating the parameter passed to __extract_hosts() method * Removed the `ipv4` resolve mode setting in the Curb adapter * Update Manticore to utilize new SSL settings * Updated the Curb integration test to not fail on older Elasticsearch versions ### API * Added `_source_transform` to the list of permitted parameters * Added extra valid arguments to "Count" and "Validate Query" APIs * Improved and extended the YAML integration test suite runner * Added extra valida parameters to various APIs * Added the "Cat Plugins", "Field Stats" and "Search Exists" APIs * Changed, that `:body` parameter is preferred in the "Scroll" and "Clear Scroll" APIs * Changed, that predicate method variants are used in RDoc code examples * Fixed spelling mistakes in the documentation ### DSL * Added the `elasticsearch-dsl` gem ## 1.0.8 * Fixed incorrect dependency specification in the "elasticsearch" wrapper gem ## EXT:0.0.18 * Removed the deprecated options for launching the test cluster * Added removing the data folder for `cluster_name` to make sure the testing cluster starts green * Make sure the `cluster_name` argument is not empty/dangerous in test cluster launcher * Changed, that test cluster is stopped with `INT` rather than `KILL` signal ## 1.0.7 ### Client * Fixed, that the Curb transport passes the `selector_class` option * Added handling the `::Curl::Err::TimeoutError` exception for Curb transport * Reworded information about authentication and added example for using SSL certificates * Added information about the `ELASTICSEARCH_URL` environment variable to the README * Allow passing multiple URLs separated by a comma to the client * Fixed an error where passing `host: { ... }` resulted in error in Client#__extract_hosts ### API * Fixed incorrect escaping of multiple indices in the "Put Alias" API * Changed the "Scroll" and "Clear Scroll" APIs to send `scroll_id` in the body * Updated and fixed the `termvectors` API * Added the `query_cache` URL parameter to the Search API * Changed frequently used strings into constants * Removed the "activesupport" development dependency to prevent test error on Ruby 1.8 * Added the "Cat Segments" API * Updated the code and documentation for the "Cluster State" API * Fixed incorrect examples for the "Percolate" API * Added a `Elasticsearch::API.settings` method for accessing module settings * Added a `Elasticsearch::API.settings[:skip_parameter_validation]` setting support into `__validate_and_extract_params` * Added `master_timeout` parameters to the "Template Exists" and "Get Template" APIs * Fixed incorrect encoding of Array parameters * Added support for the `metric` parameter in the "Nodes Info" API * Added the skip features to the YAML test runner (stash_in_path,requires_replica) * Fixed the Ruby 1.8-incompatible syntax in the "Nodes Info" API * Added question mark versions for predicate methods * Added, that `indices.delete` accepts the `:ignore` parameter ### Various * Changed the way elasticsearch/elasticsearch repository is embedded * Added the `setup` Rake task * Added chapter about development to the READMEs * Added the "test-unit" gem for Ruby 2.2 * Fixed the `elasticsearch:build` Rake task ## EXT:0.0.17 ### Extensions * Improved the aesthetics and robustness of the `Test::Cluster#__print_cluster_info` method * Removed the dependency on the "Backup" gem (using mocks in tests) ## EXT:0.0.16 ### Extensions * Disabled `allocation.disk.threshold_enabled` in the testing cluster to prevent tests failing due to low disk space * Increased the default logging level for the testing cluster to `DEBUG` * Added basic integration with the Backup gem * Changed, that `wait_for_green` timeout is configurable with an environment variable ## 1.0.6 ### Client * Added Manticore transport for JRuby platforms * Fixed, that `ServerError` inherits from `Transport::Error` * Fix problems with gems on JRuby * Added the `send_get_body_as` setting ### API * Added the "Verify Snapshot" API * Added the "Upgrade Index" API * Added support for the `realtime` parameter to the Term Vectors APIs * Fixed `delete_by_query` example in documentation * Added the support for `metric` URL parameter to the "Reroute" API * Added the "Get Indices Info" API * Added support for versioning for the "Put Script" and "Delete Script" APIs ### Extensions * Added, that `wait_for_green` timeout for test cluster is configurable with environment variable ### Various * Added Ruby 2.0.0 and updated 2.1 build specification in the Travis configuration ## 1.0.5 ### Client * Added support for automatically connecting to cluster set in the ELASTICSEARCH_URL environment variable * Improved documentation ### API * Added the `flat_settings` and `local` parameters to the "Get Template" API ## 1.0.4 ### Client * Updated the parameters list for APIs (percolate, put index) * Updated the "Indices Stats" API * Improved the `__extract_parts` utility method ### API * Fixed incorrect instructions for automatically using Typhoeus as the Faraday adapter * Fixed, that the Faraday adapter didn't return a correct object * Added, that the response body is automatically force-encoded to UTF-8 ## 1.0.3 [SKIP] ## 1.0.2 * Improved the `elasticsearch:build` Rake task ### API * Added more examples into the documentation * Added missing parameters to the "Search" API * Added the `force` option to the "Optimize" API * Added support for `version` and `version_type` parameters in the "Get Document" API * Added the "Cat Fielddata", "Recovery", "Search Shards", "Search Template", "Snapshot Status" APIs * Added the `human` parameter to COMMON_QUERY_PARAMS * Updated the "Index Stats" API to the current implementation ### Transport * Added, that error requests are properly logged and traced * Fixed an error where exception was raised too late for error responses ### Extensions * Enabled the "Benchmark" API on the testing cluster * Enabled dynamic scripting by default in the test cluster ----- ## 1.0.1 * Updated 0.90/1.0 compatibility notice * Many improvements for the continuous integration (Travis, Jenkins) * Improved documentation ### API * Added the "explain" parameter for `cluster.reroute` ### Transport * Added auto-detection for Faraday adapter from loaded Rubygems ### Extensions * Improved the documentation for `Elasticsearch::Extensions::Test::Cluster` elasticsearch-ruby-6.8.1/CONTRIBUTING.md000066400000000000000000000022531361161326000175510ustar00rootroot00000000000000The process for contributing to any of the [Elasticsearch](https://github.com/elasticsearch) repositories is similar: 1. It is best to do your work in a separate Git branch. This makes it easier to synchronise your changes with [`rebase`](http://mislav.uniqpath.com/2013/02/merge-vs-rebase/). 2. Make sure your changes don't break any existing tests, and that you add tests for both bugfixes and new functionality. Examine the coverage report generated by running `COVERAGE=true rake test:all`. 3. **Sign the contributor license agreement.** Please make sure you have signed the [Contributor License Agreement](http://www.elasticsearch.org/contributor-agreement/). We are not asking you to assign copyright to us, but to give us the right to distribute your code without restriction. We ask this of all contributors in order to assure our users of the origin and continuing existence of the code. You only need to sign the CLA once. 4. Submit a pull request. Push your local changes to your forked copy of the repository and submit a pull request. In the pull request, describe what your changes do and mention the number of the issue where discussion has taken place, eg “Closes #123″. elasticsearch-ruby-6.8.1/Gemfile000066400000000000000000000016421361161326000166140ustar00rootroot00000000000000source 'https://rubygems.org' gem 'elasticsearch-api', :path => File.expand_path("../elasticsearch-api", __FILE__), :require => false gem 'elasticsearch-transport', :path => File.expand_path("../elasticsearch-transport", __FILE__), :require => false gem 'elasticsearch-extensions', :path => File.expand_path("../elasticsearch-extensions", __FILE__), :require => false gem 'elasticsearch', :path => File.expand_path("../elasticsearch", __FILE__), :require => false gem "rake" gem "pry" gem "ansi" gem "shoulda-context" gem "mocha" gem "turn" gem "yard" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' gem "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) gem "require-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) gem "simplecov" gem "simplecov-rcov" gem "cane" end if defined?(RUBY_VERSION) && RUBY_VERSION > '2.2' gem "test-unit", '~> 2' end elasticsearch-ruby-6.8.1/README.md000066400000000000000000000141661361161326000166050ustar00rootroot00000000000000# Elasticsearch This repository contains Ruby integrations for [Elasticsearch](https://www.elastic.co/products/elasticsearch): * a client for connecting to an Elasticsearch cluster, * a Ruby API for the Elasticsearch's REST API, * various extensions and utilities. For integration with Ruby models and Rails applications, see the **[elasticsearch-rails](https://github.com/elasticsearch/elasticsearch-rails)** project. ## Compatibility The Elasticsearch client is compatible with Ruby 1.9 and higher. Other libraries in this repository might require a more recent Ruby version. The client's API is compatible with Elasticsearch's API versions from 0.90 till current, just use a release matching major version of Elasticsearch. | Gem Version | | Elasticsearch | |:-------------:|:-:| :-----------: | | 0.90 | → | 0.90 | | 1.x | → | 1.x | | 2.x | → | 2.x | | 5.x | → | 5.x | | 6.x | → | 6.x | | master | → | master | ## Installation Install the `elasticsearch` package from [Rubygems](https://rubygems.org/gems/elasticsearch): gem install elasticsearch To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git' or install it from a source code checkout: git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch bundle install rake install ## Usage The [`elasticsearch`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch) library is a wrapper for two separate libraries: * [`elasticsearch-transport`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-transport), which provides a low-level Ruby client for connecting to an [Elasticsearch](https://www.elastic.co/products/elasticsearch) cluster * [`elasticsearch-api`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-api), which provides a Ruby API for the Elasticsearch RESTful API ```ruby require 'elasticsearch' client = Elasticsearch::Client.new log: true client.transport.reload_connections! client.cluster.health client.search q: 'test' # etc. ``` Both of these libraries are extensively documented. **Please read the [`elasticsearch-transport`](http://rubydoc.info/gems/elasticsearch-transport) and the [`elasticsearch-api`](http://rubydoc.info/gems/elasticsearch-api) documentation carefully.** _Keep in mind, that for optimal performance, you should use a HTTP library which supports persistent ("keep-alive") connections, e.g. [Patron](https://github.com/toland/patron) or [Typhoeus](https://github.com/typhoeus/typhoeus)._ These libraries are not dependencies of the elasticsearch gems, so be sure to define a dependency in your own application. This repository contains these additional Ruby libraries: * [`elasticsearch-extensions`](https://github.com/elastic/elasticsearch-ruby/tree/master/elasticsearch-extensions), which provides a set of extensions to the base library, * [`elasticsearch-dsl`](https://github.com/elastic/elasticsearch-ruby/tree/master/elasticsearch-dsl), which provides a Ruby API for the [Elasticsearch Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html), * [`elasticsearch-xpack`](https://github.com/elastic/elasticsearch-ruby/tree/master/elasticsearch-xpack), which provides Ruby API for the [_X-Pack_](https://www.elastic.co/products/x-pack) APIs. Please see their respective READMEs for information and documentation. ## Development [![Build Status](https://travis-ci.org/elastic/elasticsearch-ruby.svg?branch=master)](https://travis-ci.org/elastic/elasticsearch-ruby) [![Code Climate](https://codeclimate.com/github/elastic/elasticsearch-ruby/badges/gpa.svg)](https://codeclimate.com/github/elastic/elasticsearch-ruby) To work on the code, clone and bootstrap the project first: ``` git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/ rake setup rake bundle ``` This will clone the Elasticsearch repository into the project, and run `bundle install` in all subprojects. To run tests, you need to start a testing cluster on port 9250, or provide a different one in the `TEST_CLUSTER_PORT` environment variable. There's a Rake task to start the testing cluster: ``` rake test:cluster:start ``` You can configure the port, path to the startup script, number of nodes, and other settings with environment variables: ``` TEST_CLUSTER_COMMAND=./tmp/builds/elasticsearch-2.0.0-SNAPSHOT/bin/elasticsearch \ TEST_CLUSTER_PORT=9250 \ TEST_CLUSTER_NODES=2 \ TEST_CLUSTER_NAME=my_cluster \ TEST_CLUSTER_PARAMS='-Xms500m -Xmx500m -D es.index.store.type=niofs' \ TEST_CLUSTER_TIMEOUT=120 \ rake test:cluster:start ``` To run tests against unreleased Elasticsearch versions, you can use the `rake elasticsearch:build` Rake task to build Elasticsearch from the cloned source (use `rake elasticsearch:update` to update the repository): **Note:** If you have gems from the `elasticsearch` family installed system-wide, and want to use development ones, prepend the command with `bundle exec`. ``` rake elasticsearch:build ``` You can pass a branch name (tag, commit, ...) as the Rake task variable: ``` rake elasticsearch:build[origin/1.x] ``` To run all the tests in all the subprojects, use the Rake task: ``` time rake test:all ``` ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/Rakefile000066400000000000000000000156471361161326000170000ustar00rootroot00000000000000require 'pathname' import 'rake_tasks/elasticsearch_tasks.rake' import 'rake_tasks/test_tasks.rake' CURRENT_PATH = Pathname( File.expand_path('..', __FILE__) ) SUBPROJECTS = [ 'elasticsearch', 'elasticsearch-transport', 'elasticsearch-dsl', 'elasticsearch-api', 'elasticsearch-extensions', 'elasticsearch-xpack' ].freeze RELEASE_TOGETHER = [ 'elasticsearch', 'elasticsearch-transport', 'elasticsearch-api', 'elasticsearch-xpack' ].freeze CERT_DIR = ENV['CERT_DIR'] || '.ci/certs' def admin_client $admin_client ||= begin transport_options = {} test_suite = ENV['TEST_SUITE'].freeze if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] split_hosts = hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end host, port = split_hosts.first.split(':') end if test_suite == 'security' transport_options.merge!(:ssl => { verify: false, ca_path: CERT_DIR}) password = ENV['ELASTIC_PASSWORD'] user = ENV['ELASTIC_USER'] || 'elastic' url = "https://#{user}:#{password}@#{host}:#{port}" else url = "http://#{host || 'localhost'}:#{port || 9200}" end Elasticsearch::Client.new(host: url, transport_options: transport_options) end end task :default do system "rake --tasks" end desc "Display information about subprojects" task :subprojects do puts '-'*80 SUBPROJECTS.each do |project| commit = `git log --pretty=format:'%h %ar: %s' -1 #{project}` version = Gem::Specification::load(CURRENT_PATH.join(project, "#{project}.gemspec").to_s).version.to_s puts "#{version}".ljust(10) + "| \e[1m#{project.ljust(SUBPROJECTS.map {|s| s.length}.max)}\e[0m | #{commit[ 0..80]}..." end end desc "Alias for `bundle:install`" task :bundle => 'bundle:install' desc "Alias for `bundle:clean`" task :clean => 'bundle:clean' namespace :bundle do desc "Run `bundle install` in all subprojects" task :install, [ :projects ] do |t, args| SUBPROJECTS.each do |project| puts '-'*80 sh "cd #{CURRENT_PATH.join(project)} && unset BUNDLE_GEMFILE && bundle install" puts end end desc "Remove Gemfile.lock in all subprojects" task :clean do SUBPROJECTS.each do |project| sh "rm -f #{CURRENT_PATH.join(project)}/Gemfile.lock" end end end desc "Generate documentation for all subprojects" task :doc do SUBPROJECTS.each do |project| sh "cd #{CURRENT_PATH.join(project)} && rake doc" puts '-'*80 end end desc "Release all subprojects to Rubygems" task :release do RELEASE_TOGETHER.each do |project| next if project == 'elasticsearch-extensions' sh "cd #{CURRENT_PATH.join(project)} && rake release" puts '-'*80 end end desc <<-DESC Update Rubygems versions in version.rb and *.gemspec files Example: $ rake update_version[5.0.0,5.0.1] DESC task :update_version, :old, :new do |task, args| require 'ansi' puts "[!!!] Required argument [old] missing".ansi(:red) unless args[:old] puts "[!!!] Required argument [new] missing".ansi(:red) unless args[:new] files = Dir['**/**/version.rb','**/**/*.gemspec'] longest_line = files.map { |f| f.size }.max puts "\n", "= FILES ".ansi(:faint) + ('='*92).ansi(:faint), "\n" files.each do |file| begin File.open(file, 'r+') do |f| content = f.read if content.match Regexp.new(args[:old]) content.gsub! Regexp.new(args[:old]), args[:new] puts "+ [#{file}]".ansi(:green).ljust(longest_line+20) + " [#{args[:old]}] -> [#{args[:new]}]".ansi(:green,:bold) f.rewind f.write content else puts "- [#{file}]".ansi(:yellow).ljust(longest_line+20) + " -".ansi(:faint,:strike) end end rescue Exception => e puts "[!!!] #{e.class} : #{e.message}".ansi(:red,:bold) raise e end end puts "\n\n", "= CHANGELOG ".ansi(:faint) + ('='*88).ansi(:faint), "\n" log = `git --no-pager log --reverse --no-color --pretty='* %s' HEAD --not v#{args[:old]} elasticsearch*`.split("\n") puts log.join("\n") log_entries = {} log_entries[:client] = log.select { |l| l =~ /\[CLIENT\]/ } log_entries[:api] = log.select { |l| l =~ /\[API\]/ } log_entries[:dsl] = log.select { |l| l =~ /\[DSL\]/ } log_entries[:ext] = log.select { |l| l =~ /\[EXT\]/ } log_entries[:xpack] = log.select { |l| l =~ /\[XPACK\]/ } changelog = File.read(File.open('CHANGELOG.md', 'r')) changelog_update = '' if log.any? { |l| l =~ /CLIENT|API|DSL/ } changelog_update << "## #{args[:new]}\n\n" end unless log_entries[:client].empty? changelog_update << "### Client\n\n" changelog_update << log_entries[:client] .map { |l| l.gsub /\[CLIENT\] /, '' } .map { |l| "#{l}" } .join("\n") changelog_update << "\n\n" end unless log_entries[:api].empty? changelog_update << "### API\n\n" changelog_update << log_entries[:api] .map { |l| l.gsub /\[API\] /, '' } .map { |l| "#{l}" } .join("\n") changelog_update << "\n\n" end unless log_entries[:dsl].empty? changelog_update << "### DSL\n\n" changelog_update << log_entries[:dsl] .map { |l| l.gsub /\[DSL\] /, '' } .map { |l| "#{l}" } .join("\n") changelog_update << "\n\n" end unless log_entries[:client].empty? changelog_update << "### EXT:#{args[:new]}\n\n" changelog_update << log_entries[:ext] .map { |l| l.gsub /\[EXT\] /, '' } .map { |l| "#{l}" } .join("\n") changelog_update << "\n\n" end unless log_entries[:xpack].empty? changelog_update << "### XPACK\n\n" changelog_update << log_entries[:xpack] .map { |l| l.gsub /\[XPACK\] /, '' } .map { |l| "#{l}" } .join("\n") changelog_update << "\n\n" end File.open('CHANGELOG.md', 'w+') { |f| f.write changelog_update and f.write changelog } puts "\n\n", "= DIFF ".ansi(:faint) + ('='*93).ansi(:faint) diff = `git --no-pager diff --patch --word-diff=color --minimal elasticsearch*`.split("\n") puts diff .reject { |l| l =~ /^\e\[1mdiff \-\-git/ } .reject { |l| l =~ /^\e\[1mindex [a-z0-9]{7}/ } .reject { |l| l =~ /^\e\[1m\-\-\- i/ } .reject { |l| l =~ /^\e\[36m@@/ } .map { |l| l =~ /^\e\[1m\+\+\+ w/ ? "\n#{l} " + '-'*(104-l.size) : l } .join("\n") puts "\n\n", "= COMMIT ".ansi(:faint) + ('='*91).ansi(:faint), "\n" puts "git add CHANGELOG.md elasticsearch*", "git commit --verbose --message='Release #{args[:new]}' --edit", "rake release" "\n" end elasticsearch-ruby-6.8.1/elasticsearch-api/000077500000000000000000000000001361161326000206775ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/.gitignore000066400000000000000000000002321361161326000226640ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp elasticsearch-ruby-6.8.1/elasticsearch-api/Gemfile000066400000000000000000000013651361161326000221770ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-api.gemspec gemspec if File.exist? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-transport", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => true end if File.exist? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end group :development do gem 'rspec' gem 'pry-nav' end elasticsearch-ruby-6.8.1/elasticsearch-api/LICENSE.txt000066400000000000000000000010561361161326000225240ustar00rootroot00000000000000Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-api/README.md000066400000000000000000000146601361161326000221650ustar00rootroot00000000000000# Elasticsearch::API **This library is part of the [`elasticsearch-ruby`](https://github.com/elasticsearch/elasticsearch-ruby/) package; please refer to it, unless you want to use this library standalone.** ---- The `elasticsearch-api` library provides a Ruby implementation of the [Elasticsearch](http://elasticsearch.org) REST API. It does not provide an Elasticsearch client; see the [`elasticsearch-transport`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-transport) library. The library is compatible with Ruby 1.9 and higher. It is compatible with Elasticsearch's API versions from 0.90 till current, just use a release matching major version of Elasticsearch. | Ruby | | Elasticsearch | |:-------------:|:-:| :-----------: | | 0.90 | → | 0.90 | | 1.x | → | 1.x | | 2.x | → | 2.x | | 5.x | → | 5.x | | 6.x | → | 6.x | | master | → | master | ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch-api To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch-api', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git' or install it from a source code checkout: git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch-api bundle install rake install ## Usage The library is designed as a group of standalone Ruby modules, which can be mixed into a class providing connection to Elasticsearch -- an Elasticsearch client. ### Usage with the `elasticsearch` gem **When you use the client from the [`elasticsearch-ruby`](https://github.com/elasticsearch/elasticsearch-ruby/) package, the library modules have been already included**, so you just call the API methods: ```ruby require 'elasticsearch' client = Elasticsearch::Client.new log: true client.index index: 'myindex', type: 'mytype', id: 1, body: { title: 'Test' } # => {"_index"=>"myindex", ... "created"=>true} client.search index: 'myindex', body: { query: { match: { title: 'test' } } } # => {"took"=>2, ..., "hits"=>{"total":5, ...}} ``` Full documentation and examples are included as RDoc annotations in the source code and available online at . ### Usage with a custom client When you want to mix the library into your own client, it must conform to a following _contract_: * It responds to a `perform_request(method, path, params, body)` method, * the method returns an object with `status`, `body` and `headers` methods. A simple client could look like this: ```ruby require 'multi_json' require 'faraday' require 'elasticsearch/api' class MySimpleClient include Elasticsearch::API CONNECTION = ::Faraday::Connection.new url: 'http://localhost:9200' def perform_request(method, path, params, body) puts "--> #{method.upcase} #{path} #{params} #{body}" CONNECTION.run_request \ method.downcase.to_sym, path, ( body ? MultiJson.dump(body): nil ), {'Content-Type' => 'application/json'} end end client = MySimpleClient.new p client.cluster.health # --> GET _cluster/health {} # => "{"cluster_name":"elasticsearch" ... }" p client.index index: 'myindex', type: 'mytype', id: 'custom', body: { title: "Indexing from my client" } # --> PUT myindex/mytype/custom {} {:title=>"Indexing from my client"} # => "{"ok":true, ... }" ``` ### Using JSON Builders Instead of passing the `:body` argument as a Ruby _Hash_, you can pass it as a _String_, potentially taking advantage of JSON builders such as [JBuilder](https://github.com/rails/jbuilder) or [Jsonify](https://github.com/bsiggelkow/jsonify): ```ruby require 'jbuilder' query = Jbuilder.encode do |json| json.query do json.match do json.title do json.query 'test 1' json.operator 'and' end end end end client.search index: 'myindex', body: query # 2013-06-25 09:56:05 +0200: GET http://localhost:9200/myindex/_search [status:200, request:0.015s, query:0.011s] # 2013-06-25 09:56:05 +0200: > {"query":{"match":{"title":{"query":"test 1","operator":"and"}}}} # ... # => {"took"=>21, ..., "hits"=>{"total"=>1, "hits"=>[{ "_source"=>{"title"=>"Test 1", ...}}]}} ``` ### Using Hash Wrappers For a more comfortable access to response properties, you may wrap it in one of the _Hash_ "object access" wrappers, such as [`Hashie::Mash`](https://github.com/intridea/hashie): ```ruby require 'hashie' response = client.search index: 'myindex', body: { query: { match: { title: 'test' } }, aggregations: { tags: { terms: { field: 'tags' } } } } mash = Hashie::Mash.new response mash.hits.hits.first._source.title # => 'Test' mash.aggregations.tags.terms.first # => # ``` ### Using a Custom JSON Serializer The library uses the [MultiJson](https://rubygems.org/gems/multi_json/) gem by default, but allows you to set a custom JSON library, provided it uses the standard `load/dump` interface: ```ruby Elasticsearch::API.settings[:serializer] = JrJackson::Json Elasticsearch::API.serializer.dump({foo: 'bar'}) # => {"foo":"bar"} ``` ## Development To work on the code, clone and bootstrap the main repository first -- please see instructions in the main [README](../README.md#development). To run tests, launch a testing cluster -- again, see instructions in the main [README](../README.md#development) -- and use the Rake tasks: ``` time rake test:unit time rake test:integration ``` Unit tests have to use Ruby 1.8 compatible syntax, integration tests can use Ruby 2.x syntax and features. ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-api/Rakefile000066400000000000000000000120121361161326000223400ustar00rootroot00000000000000require "bundler/gem_tasks" def __current__ Pathname( File.expand_path('..', __FILE__) ) end def git_specs(command, options={}) sh "git --git-dir=#{__current__.join('../tmp/elasticsearch/.git')} --work-tree=#{__current__.join('../tmp/elasticsearch')} #{command}", options end task(:default) { system "rake --tasks" } task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' require 'rspec/core/rake_task' namespace :test do RSpec::Core::RakeTask.new(:spec) desc "Update the repository with YAML tests" task :update do git_specs "fetch origin --verbose", :verbose => true end desc "Wait for Elasticsearch to be in a green state" task :wait_for_green do sh '../scripts/wait-cluster.sh' end Rake::TestTask.new(:unit) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] test.deps = [ :spec ] # test.verbose = true # test.warning = true end desc "Run integration tests" task :integration => :wait_for_green do require 'elasticsearch' branches = `git --git-dir=#{__current__.join('../tmp/elasticsearch/.git')} --work-tree=#{__current__.join('../tmp/elasticsearch')} branch --no-color` current_branch = branches. split("\n"). select { |b| b =~ /^\*/ }. reject { |b| b =~ /no branch|detached/ }. map { |b| b.gsub(/^\*\s*/, '') }. first unless current_branch STDERR.puts "[!] Unable to determine current branch, defaulting to 'master'" current_branch = 'master' end # Define the task t = Rake::TestTask.new(:integration) do |test| test.deps = [ :wait_for_green ] test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/yaml_test_runner.rb", "test/integration/**/*_test.rb"] test.verbose = false test.warning = false end # Check if a test cluster is running begin url = ENV['TEST_CLUSTER_URL'] || ENV['TEST_ES_SERVER'] url = "http://localhost:#{ENV['TEST_CLUSTER_PORT'] || 9250}" unless url client = Elasticsearch::Client.new :url => url es_version_info = client.info['version'] build_hash = es_version_info['build_hash'] cluster_running = true rescue Faraday::Error::ConnectionFailed STDERR.puts "[!] Test cluster not running?" cluster_running = false end checkout_specs_version = ENV['TEST_NO_CHECKOUT'].nil? ? true : false checkout_build_hash = ENV['TEST_BUILD_REF'] || build_hash ENV['TEST_BUILD_REF'] = checkout_build_hash begin unless checkout_specs_version STDERR.puts '-'*80, "YAML tests: Not switching, TEST_NO_CHECKOUT=y", '-'*80 end if checkout_specs_version && !checkout_build_hash STDERR.puts "[!] Cannot determine checkout build hash -- server not running or TEST_BUILD_REF not specified" exit(1) end if checkout_specs_version && checkout_build_hash # Checkout the commit corresponding to the running server build, or passed TEST_BUILD_REF name = ENV['CI'] ? checkout_build_hash : "[\e[1m#{checkout_build_hash}\e[0m]" STDERR.puts '-'*80, "YAML tests: Switching to #{name} from #{current_branch}", '-'*80 git_specs "checkout #{checkout_build_hash} --force --quiet" end # Run the task args = [t.ruby_opts_string, t.run_code, t.file_list_string, t.option_list].join(' ') ruby args do |ok, status| if !ok && status.respond_to?(:signaled?) && status.signaled? raise SignalException.new(status.termsig) elsif !ok fail "Command failed with status (#{status.exitstatus}): " + "[ruby #{args}]" end end ensure git_specs "checkout #{current_branch} --force --quiet" if checkout_specs_version && current_branch end end desc "Run unit and integration tests" task :all do Rake::Task['test:unit'].invoke Rake::Task['test:integration'].invoke end namespace :cluster do desc "Start Elasticsearch nodes for tests" task :start do $LOAD_PATH << File.expand_path('../../elasticsearch-transport/lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start end desc "Stop Elasticsearch nodes for tests" task :stop do $LOAD_PATH << File.expand_path('../../elasticsearch-transport/lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.stop end end end # ----- Documentation tasks --------------------------------------------------- require 'yard' YARD::Rake::YardocTask.new(:doc) do |t| t.options = %w| --embed-mixins --markup=markdown | end # ----- Code analysis tasks --------------------------------------------------- if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'cane/rake_task' Cane::RakeTask.new(:quality) do |cane| cane.abc_max = 15 cane.no_style = true end end elasticsearch-ruby-6.8.1/elasticsearch-api/elasticsearch-api.gemspec000066400000000000000000000052651361161326000256350ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/api/version' Gem::Specification.new do |s| s.name = "elasticsearch-api" s.version = Elasticsearch::API::VERSION s.authors = ["Karel Minarik"] s.email = ["karel.minarik@elasticsearch.org"] s.summary = "Ruby API for Elasticsearch." s.homepage = "https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-api" s.license = "Apache-2.0" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] s.extra_rdoc_files = [ "README.md", "LICENSE.txt" ] s.rdoc_options = [ "--charset=UTF-8" ] s.required_ruby_version = '>= 1.9' s.add_dependency "multi_json" s.add_development_dependency "bundler" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "rake", "~> 11.1" else s.add_development_dependency "rake", "< 11.0" end s.add_development_dependency "elasticsearch" s.add_development_dependency "elasticsearch-transport" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "minitest", "~> 4.0" s.add_development_dependency "elasticsearch-extensions" end s.add_development_dependency "ansi" s.add_development_dependency "shoulda-context" s.add_development_dependency "mocha" s.add_development_dependency "turn" s.add_development_dependency "yard" s.add_development_dependency "pry" # Gems for testing integrations s.add_development_dependency "jsonify" s.add_development_dependency "hashie" # Prevent unit test failures on Ruby 1.8 if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_development_dependency "test-unit", '~> 2' s.add_development_dependency "json", '~> 1.8' end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) s.add_development_dependency "jbuilder" s.add_development_dependency "escape_utils" unless defined? JRUBY_VERSION s.add_development_dependency "simplecov" s.add_development_dependency "simplecov-rcov" s.add_development_dependency "cane" s.add_development_dependency "require-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) end if defined?(RUBY_VERSION) && RUBY_VERSION > '2.2' s.add_development_dependency "test-unit", '~> 2' end s.description = <<-DESC.gsub(/^ /, '') Ruby API for Elasticsearch. See the `elasticsearch` gem for full integration. DESC end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/000077500000000000000000000000001361161326000214455ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch-api.rb000066400000000000000000000000341361161326000253500ustar00rootroot00000000000000require 'elasticsearch/api' elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/000077500000000000000000000000001361161326000242575ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api.rb000066400000000000000000000044661361161326000253670ustar00rootroot00000000000000require "cgi" require "multi_json" require "elasticsearch/api/version" require "elasticsearch/api/namespace/common" require "elasticsearch/api/utils" require "elasticsearch/api/actions/params_registry" Dir[ File.expand_path('../api/actions/**/params_registry.rb', __FILE__) ].each { |f| require f } Dir[ File.expand_path('../api/actions/**/*.rb', __FILE__) ].each { |f| require f } Dir[ File.expand_path('../api/namespace/**/*.rb', __FILE__) ].each { |f| require f } module Elasticsearch module API DEFAULT_SERIALIZER = MultiJson COMMON_PARAMS = [ :ignore, # Client specific parameters :index, :type, :id, # :index/:type/:id :body, # Request body :node_id, # Cluster :name, # Alias, template, settings, warmer, ... :field # Get field mapping ] COMMON_QUERY_PARAMS = [ :ignore, # Client specific parameters :format, # Search, Cat, ... :pretty, # Pretty-print the response :human, # Return numeric values in human readable format :filter_path # Filter the JSON response ] HTTP_GET = 'GET'.freeze HTTP_HEAD = 'HEAD'.freeze HTTP_POST = 'POST'.freeze HTTP_PUT = 'PUT'.freeze HTTP_DELETE = 'DELETE'.freeze UNDERSCORE_SEARCH = '_search'.freeze UNDERSCORE_ALL = '_all'.freeze # Auto-include all namespaces in the receiver # def self.included(base) base.send :include, Elasticsearch::API::Common, Elasticsearch::API::Actions, Elasticsearch::API::Cluster, Elasticsearch::API::Nodes, Elasticsearch::API::Indices, Elasticsearch::API::Ingest, Elasticsearch::API::Snapshot, Elasticsearch::API::Tasks, Elasticsearch::API::Cat, Elasticsearch::API::Remote end # The serializer class # def self.serializer settings[:serializer] || DEFAULT_SERIALIZER end # Access the module settings # def self.settings @settings ||= {} end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/000077500000000000000000000000001361161326000250305ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/000077500000000000000000000000001361161326000264705ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/abort_benchmark.rb000066400000000000000000000011421361161326000321340ustar00rootroot00000000000000module Elasticsearch module API module Actions # Abort a running benchmark # # @example # # client.abort_benchmark name: 'my_benchmark' # # @option arguments [String] :name A benchmark name # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-benchmark.html # def abort_benchmark(arguments={}) method = HTTP_POST path = "_bench/abort/#{arguments[:name]}" params = {} body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/benchmark.rb000066400000000000000000000042431361161326000307520ustar00rootroot00000000000000module Elasticsearch module API module Actions # Run a single query, or a set of queries, and return statistics on their performance # # @example Return statistics for a single query # # client.benchmark body: { # name: 'my_benchmark', # competitors: [ # { # name: 'query_1', # requests: [ # { query: { match: { _all: 'a*' } } } # ] # } # ] # } # # @example Return statistics for a set of "competing" queries # # client.benchmark body: { # name: 'my_benchmark', # competitors: [ # { # name: 'query_a', # requests: [ # { query: { match: { _all: 'a*' } } } # ] # }, # { # name: 'query_b', # requests: [ # { query: { match: { _all: 'b*' } } } # ] # } # ] # } # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string # to perform the operation on all indices # @option arguments [String] :type The name of the document type # @option arguments [Hash] :body The search definition using the Query DSL # @option arguments [Boolean] :verbose Specify whether to return verbose statistics about each iteration # (default: false) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-benchmark.html # def benchmark(arguments={}) method = HTTP_PUT path = "_bench" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:benchmark, [ :verbose ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/bulk.rb000066400000000000000000000122651361161326000277600ustar00rootroot00000000000000module Elasticsearch module API module Actions # Perform multiple index, delete or update operations in a single request. # # Supports various different formats of the payload: Array of Strings, Header/Data pairs, # or the conveniency "combined" format where data is passed along with the header # in a single item in a custom `:data` key. # # @note The body argument is required and cannot be empty. # # @example Perform three operations in a single request, passing actions and data as an array of hashes # # client.bulk body: [ # { index: { _index: 'myindex', _type: 'mytype', _id: 1 } }, # { title: 'foo' }, # # { index: { _index: 'myindex', _type: 'mytype', _id: 2 } }, # { title: 'foo' }, # # { delete: { _index: 'myindex', _type: 'mytype', _id: 3 } } # ] # @example Perform three operations in a single request, passing data in the `:data` option # # client.bulk body: [ # { index: { _index: 'myindex', _type: 'mytype', _id: 1, data: { title: 'foo' } } }, # { update: { _index: 'myindex', _type: 'mytype', _id: 2, data: { doc: { title: 'foo' } } } }, # { delete: { _index: 'myindex', _type: 'mytype', _id: 3 } } # ] # # @example Perform a script-based bulk update, passing scripts in the `:data` option # # client.bulk body: [ # { update: { _index: 'myindex', _type: 'mytype', _id: 1, # data: { # script: "ctx._source.counter += value", # lang: 'js', # params: { value: 1 }, upsert: { counter: 0 } } # }}, # { update: { _index: 'myindex', _type: 'mytype', _id: 2, # data: { # script: "ctx._source.counter += value", # lang: 'js', # params: { value: 42 }, upsert: { counter: 0 } } # }} # # ] # # @option arguments [String] :index Default index for items which don't provide one # @option arguments [String] :type Default document type for items which don't provide one # @option arguments [Hash] :body The operation definition and data (action-data pairs), separated by newlines (*Required*) Note that this cannot be empty. # @option arguments [String] :wait_for_active_shards 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) # @option arguments [String] :refresh 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. (options: true, false, wait_for) # @option arguments [String] :routing Specific routing value # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [String] :type Default document type for items which don't provide one # @option arguments [List] :fields Default comma-separated list of fields to return in the response for updates, can be overridden on each sub-request # @option arguments [List] :_source True or false to return the _source field or not, or default list of fields to return, can be overridden on each sub-request # @option arguments [List] :_source_excludes Default list of fields to exclude from the returned _source field, can be overridden on each sub-request # @option arguments [List] :_source_includes Default list of fields to extract and return from the _source field, can be overridden on each sub-request # @option arguments [String] :pipeline The pipeline id to preprocess incoming documents with # # @return [Hash] Deserialized Elasticsearch response # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html # def bulk(arguments={}) arguments = arguments.clone type = arguments.delete(:type) method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(type), '_bulk' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] if body.is_a? Array payload = Utils.__bulkify(body) else payload = body end perform_request(method, path, params, payload, {"Content-Type" => "application/x-ndjson"}).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:bulk, [ :wait_for_active_shards, :refresh, :routing, :timeout, :type, :fields, :_source, :_source_excludes, :_source_includes, :pipeline ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/000077500000000000000000000000001361161326000272375ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/aliases.rb000066400000000000000000000052661361161326000312160ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Returns information about aliases, including associated routing values and filters. # # @example Display all aliases in the cluster # # puts client.cat.aliases # # @example Display indices for the 'year-2013' alias # # puts client.cat.aliases name: 'year-2013' # # @example Display header names in the output # # puts client.cat.aliases v: true # # @example Return only the 'alias' and 'index' columns # # puts client.cat.aliases h: ['alias', 'index'] # # @example Return only the 'alias' and 'index' columns, using short names # # puts client.cat.aliases h: 'a,i' # # @example Return the output sorted by the alias name # # puts client.cat.aliases s: 'alias' # # @example Return the information as Ruby objects # # client.cat.aliases format: 'json' # # @option arguments [List] :name A comma-separated list of alias names to return # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-aliases.html # def aliases(arguments={}) name = arguments.delete(:name) method = HTTP_GET path = Utils.__pathify '_cat/aliases', Utils.__listify(name) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:aliases, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/allocation.rb000066400000000000000000000054501361161326000317150ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return shard allocation information # # @example Display allocation for all nodes in the cluster # # puts client.cat.allocation # # @example Display allocation for node with name 'node-1' # # puts client.cat.allocation node_id: 'node-1' # # @example Display header names in the output # # puts client.cat.allocation v: true # # @example Display only specific columns in the output (see the `help` parameter) # # puts client.cat.allocation h: ['node', 'shards', 'disk.percent'] # # @example Display only specific columns in the output, using the short names # # puts client.cat.allocation h: 'n,s,dp' # # @example Return the information as Ruby objects # # client.cat.allocation format: 'json' # # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :bytes The unit in which to display byte values (options: b, k, kb, m, mb, g, gb, t, tb, p, pb) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-allocation.html # def allocation(arguments={}) node_id = arguments.delete(:node_id) method = HTTP_GET path = Utils.__pathify '_cat/allocation', Utils.__listify(node_id) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:allocation, [ :format, :bytes, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/count.rb000066400000000000000000000046551361161326000307260ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return document counts for the entire cluster or specific indices # # @example Display number of documents in the cluster # # puts client.cat.count # # @example Display number of documents in an index # # puts client.cat.count index: 'index-a' # # @example Display number of documents in a list of indices # # puts client.cat.count index: ['index-a', 'index-b'] # # @example Display header names in the output # # puts client.cat.count v: true # # @example Return the information as Ruby objects # # client.cat.count format: 'json' # # @option arguments [List] :index A comma-separated list of index names to limit the returned information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-count.html # def count(arguments={}) index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/count', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:count, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/fielddata.rb000066400000000000000000000043771361161326000315140ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return information about field data usage across the cluster # # @example Return the total size of field data # # client.cat.fielddata # # @example Return both the total size and size for specific fields # # client.cat.fielddata fields: 'title,body' # # @option arguments [List] :fields A comma-separated list of fields to return the fielddata size # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :bytes The unit in which to display byte values (options: b, k, kb, m, mb, g, gb, t, tb, p, pb) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # @option arguments [List] :fields A comma-separated list of fields to return in the output # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-fielddata.html # def fielddata(arguments={}) fields = arguments.delete(:fields) method = HTTP_GET path = Utils.__pathify "_cat/fielddata", Utils.__listify(fields) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:fielddata, [ :format, :bytes, :local, :master_timeout, :h, :help, :s, :v, :fields ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/health.rb000066400000000000000000000040571361161326000310370ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display a terse version of the {Elasticsearch::API::Cluster::Actions#health} API output # # @example Display cluster health # # puts client.cat.health # # @example Display header names in the output # # puts client.cat.health v: true # # @example Return the information as Ruby objects # # client.cat.health format: 'json' # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :ts Set to false to disable timestamping # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-health.html # def health(arguments={}) method = HTTP_GET path = "_cat/health" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:health, [ :format, :local, :master_timeout, :h, :help, :s, :ts, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/help.rb000066400000000000000000000016221361161326000305150ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Help information for the Cat API # # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat.html # def help(arguments={}) method = HTTP_GET path = "_cat" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:help, [ :help, :s ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/indices.rb000066400000000000000000000065141361161326000312100ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return the most important statistics about indices, across the cluster nodes # # Use the `help` parameter to display available statistics. # # @example Display information for all indices # # puts client.cat.indices # # @example Display information for a specific index # # puts client.cat.indices index: 'index-a' # # @example Display information for indices matching a pattern # # puts client.cat.indices index: 'index-*' # # @example Display header names in the output # # puts client.cat.indices v: true # # @example Display only specific columns in the output (see the `help` parameter) # # puts client.cat.indices h: ['index', 'docs.count', 'fielddata.memory_size', 'filter_cache.memory_size'] # # @example Display only specific columns in the output, using the short names # # puts client.cat.indices h: 'i,dc,ss,mt', v: true # # @example Return the information as Ruby objects # # client.cat.indices format: 'json' # # @option arguments [List] :index A comma-separated list of index names to limit the returned information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :bytes The unit in which to display byte values (options: b, k, m, g) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [String] :health A health status ("green", "yellow", or "red" to filter only indices matching the specified health status (options: green, yellow, red) # @option arguments [Boolean] :help Return help information # @option arguments [Boolean] :pri Set to true to return stats only for primary shards # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-indices.html # def indices(arguments={}) index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/indices', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:indices, [ :format, :bytes, :local, :master_timeout, :h, :health, :help, :pri, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/master.rb000066400000000000000000000035171361161326000310650ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display basic information about the master node # # @example # # puts client.cat.master # # @example Display header names in the output # # puts client.cat.master v: true # # @example Return the information as Ruby objects # # client.cat.master format: 'json' # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-master.html # def master(arguments={}) method = HTTP_GET path = "_cat/master" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:master, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/nodeattrs.rb000066400000000000000000000030001361161326000315600ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display custom node attributes # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cat-nodeattrs.html # def nodeattrs(arguments={}) method = 'GET' path = "_cat/nodeattrs" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:nodeattrs, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/nodes.rb000066400000000000000000000050561361161326000307020ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display information about cluster topology and nodes statistics # # @example Display basic information about nodes in the cluster (host, node name, memory usage, master, etc.) # # puts client.cat.nodes # # @example Display header names in the output # # puts client.cat.nodes v: true # # @example Display only specific columns in the output (see the `help` parameter) # # puts client.cat.nodes h: %w(name version jdk disk.avail heap.percent load merges.total_time), v: true # # @example Display only specific columns in the output, using the short names # # puts client.cat.nodes h: 'n,v,j,d,hp,l,mtt', v: true # # @example Return the information as Ruby objects # # client.cat.nodes format: 'json' # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :full_id Return the full node ID instead of the shortened version (default: false) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-nodes.html # def nodes(arguments={}) method = HTTP_GET path = "_cat/nodes" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h], :escape => false) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:nodes, [ :format, :full_id, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/params_registry.rb000066400000000000000000000022661361161326000330050ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/pending_tasks.rb000066400000000000000000000037531361161326000324250ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display the information from the {Cluster::Actions#pending_tasks} API in a tabular format # # @example # # puts client.cat.pending_tasks # # @example Display header names in the output # # puts client.cat.pending_tasks v: true # # @example Return the information as Ruby objects # # client.cat.pending_tasks format: 'json' # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-pending-tasks.html # def pending_tasks(arguments={}) method = HTTP_GET path = "_cat/pending_tasks" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:pending_tasks, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/plugins.rb000066400000000000000000000030041361161326000312420ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return information about installed plugins # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cat-plugins.html # def plugins(arguments={}) method = 'GET' path = "_cat/plugins" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:plugins, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/recovery.rb000066400000000000000000000054301361161326000314240ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display information about the recovery process (allocating shards) # # @example Display information for all indices # # puts client.cat.recovery # # @example Display information for a specific index # # puts client.cat.recovery index: 'index-a' # # @example Display information for indices matching a pattern # # puts client.cat.recovery index: 'index-*' # # @example Display header names in the output # # puts client.cat.recovery v: true # # @example Display only specific columns in the output (see the `help` parameter) # # puts client.cat.recovery h: ['node', 'index', 'shard', 'percent'] # # @example Display only specific columns in the output, using the short names # # puts client.cat.recovery h: 'n,i,s,per' # # @example Return the information as Ruby objects # # client.cat.recovery format: 'json' # # @option arguments [List] :index A comma-separated list of index names to limit the returned information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :bytes The unit in which to display byte values (options: b, k, kb, m, mb, g, gb, t, tb, p, pb) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-recovery.html # def recovery(arguments={}) index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/recovery', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:recovery, [ :format, :bytes, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/repositories.rb000066400000000000000000000033601361161326000323150ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Shows all repositories registered in a cluster # # @example Return list of repositories # # client.cat.repositories # # @example Return only id for each repository # # client.cat.repositories h: 'id' # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-repositories.html # def repositories(arguments={}) method = HTTP_GET path = "_cat/repositories" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:repositories, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/segments.rb000066400000000000000000000033241361161326000314130ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display information about the segments in the shards of an index # # @example Display information for all indices # # puts client.cat.segments # # @option arguments [List] :index A comma-separated list of index names to limit the returned information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :bytes The unit in which to display byte values (options: b, k, kb, m, mb, g, gb, t, tb, p, pb) # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-segments.html # def segments(arguments={}) method = 'GET' index = arguments.delete(:index) path = Utils.__pathify( '_cat/segments', Utils.__escape(index)) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:segments, [ :format, :bytes, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/shards.rb000066400000000000000000000060421361161326000310520ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display shard allocation across nodes # # @example Display information for all indices # # puts client.cat.shards # # @example Display information for a specific index # # puts client.cat.shards index: 'index-a' # # @example Display information for a list of indices # # puts client.cat.shards index: ['index-a', 'index-b'] # # @example Display header names in the output # # puts client.cat.shards v: true # # @example Display shard size in choice of units # # puts client.cat.shards bytes: 'b' # # @example Display only specific columns in the output (see the `help` parameter) # # puts client.cat.shards h: ['node', 'index', 'shard', 'prirep', 'docs', 'store', 'merges.total'] # # @example Display only specific columns in the output, using the short names # # puts client.cat.shards h: 'n,i,s,p,d,sto,mt' # # @example Return the information as Ruby objects # # client.cat.shards format: 'json' # # @option arguments [List] :index A comma-separated list of index names to limit the returned information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :bytes The unit in which to display byte values (options: b, k, kb, m, mb, g, gb, t, tb, p, pb) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-shards.html # def shards(arguments={}) index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/shards', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:shards, [ :format, :bytes, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/snapshots.rb000066400000000000000000000042321361161326000316070ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Shows all snapshots that belong to a specific repository # # @example Return snapshots for 'my_repository' # # client.cat.snapshots repository: 'my_repository' # # @example Return id, status and start_epoch for 'my_repository' # # client.cat.snapshots repository: 'my_repository', h: 'id,status,start_epoch' # # @option arguments [List] :repository Name of repository from which to fetch the snapshot information # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :ignore_unavailable Set to true to ignore unavailable snapshots # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-snapshots.html # def snapshots(arguments={}) raise ArgumentError, "Required argument 'repository' missing" if !arguments[:repository] && !arguments[:help] repository = arguments.delete(:repository) method = HTTP_GET path = Utils.__pathify "_cat/snapshots", Utils.__escape(repository) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:snapshots, [ :format, :ignore_unavailable, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/tasks.rb000066400000000000000000000035641361161326000307210ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return currently running tasks # # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [List] :actions A comma-separated list of actions that should be returned. Leave empty to return all. # @option arguments [Boolean] :detailed Return detailed task information (default: false) # @option arguments [Number] :parent_task Return tasks with specified parent task id. Set to -1 to return all. # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html # def tasks(arguments={}) method = 'GET' path = "_cat/tasks" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:tasks, [ :format, :node_id, :actions, :detailed, :parent_task, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/templates.rb000066400000000000000000000032751361161326000315710ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Returns information about existing templates # # @option arguments [String] :name A pattern that returned template names must match # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cat-templates.html # def templates(arguments={}) method = HTTP_GET name = arguments.delete(:name) path = Utils.__pathify( '_cat/templates', Utils.__escape(name)) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:templates, [ :format, :local, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cat/thread_pool.rb000066400000000000000000000052051361161326000320660ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display thread pool statistics across nodes (use the `help` parameter to display a list # of available thread pools) # # @example Display information about all thread pools across nodes # # puts client.cat.thread_pool # # @example Display header names in the output # # puts client.cat.thread_pool v: true # # @example Display information about the indexing thread pool # # puts client.cat.thread_pool h: %w(h ip index.active index.size index.queue index.rejected), v: true # # @example Display information about the indexing and search threads, using the short names # # puts client.cat.thread_pool h: 'host,ia,is,iq,ir,sa,ss,sq,sr', v: true # # @option arguments [List] :thread_pool_patterns A comma-separated list of regular-expressions to filter the thread pools in the output # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # @option arguments [String] :size The multiplier in which to display values (options: , k, m, g, t, p) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [List] :s Comma-separated list of column names or column aliases to sort by # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cat-thread-pool.html # def thread_pool(arguments={}) method = HTTP_GET path = "_cat/thread_pool" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:thread_pool, [ :format, :size, :local, :thread_pool_patterns, :master_timeout, :h, :help, :s, :v ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/clear_scroll.rb000066400000000000000000000022361361161326000314640ustar00rootroot00000000000000module Elasticsearch module API module Actions # Abort a particular scroll search and clear all the resources associated with it. # # @option arguments [List] :scroll_id A comma-separated list of scroll IDs to clear; # use `_all` clear all scroll search contexts # @option arguments [Hash] :body A comma-separated list of scroll IDs to clear if none was specified via the scroll_id parameter # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html#clear-scroll # def clear_scroll(arguments={}) raise ArgumentError, "Required argument 'scroll_id' missing" unless arguments[:scroll_id] method = HTTP_DELETE path = Utils.__pathify '_search/scroll', Utils.__listify(arguments.delete(:scroll_id)) params = {} body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:clear_scroll, [ ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/000077500000000000000000000000001361161326000301515ustar00rootroot00000000000000allocation_explain.rb000066400000000000000000000023611361161326000342660ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/clustermodule Elasticsearch module API module Cluster module Actions # Return the information about why a shard is or isn't allocated # # @option arguments [Hash] :body The index, shard, and primary flag to explain. Empty means 'explain the first unassigned shard' # @option arguments [Boolean] :include_yes_decisions Return 'YES' decisions in explanation (default: false) # @option arguments [Boolean] :include_disk_info Return information about disk usage and shard sizes (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-allocation-explain.html # def allocation_explain(arguments={}) method = 'GET' path = "_cluster/allocation/explain" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:allocation_explain, [ :include_yes_decisions, :include_disk_info ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/get_settings.rb000066400000000000000000000025431361161326000332010ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Get the cluster settings (previously set with {Cluster::Actions#put_settings}) # # @example Get cluster settings # # client.cluster.get_settings # # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :include_defaults Whether to return all default clusters setting. # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-update-settings/ # def get_settings(arguments={}) method = HTTP_GET path = "_cluster/settings" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_settings, [ :flat_settings, :master_timeout, :timeout, :include_defaults ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/health.rb000066400000000000000000000053301361161326000317440ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Returns information about cluster "health". # # @example Get the cluster health information # # client.cluster.health # # @example Block the request until the cluster is in the "yellow" state # # client.cluster.health wait_for_status: 'yellow' # # @option arguments [List] :index Limit the information returned to a specific index # @option arguments [String] :level Specify the level of detail for returned information (options: cluster, indices, shards) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [String] :wait_for_active_shards Wait until the specified number of shards is active # @option arguments [String] :wait_for_nodes Wait until the specified number of nodes is available # @option arguments [String] :wait_for_events Wait until all currently queued events with the given priority are processed (options: immediate, urgent, high, normal, low, languid) # @option arguments [Boolean] :wait_for_no_relocating_shards Whether to wait until there are no relocating shards in the cluster # @option arguments [Boolean] :wait_for_no_initializing_shards Whether to wait until there are no initializing shards in the cluster # @option arguments [String] :wait_for_status Wait until cluster is in a specific state (options: green, yellow, red) # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-health/ # def health(arguments={}) arguments = arguments.clone index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify "_cluster/health", Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:health, [ :level, :local, :master_timeout, :timeout, :wait_for_active_shards, :wait_for_nodes, :wait_for_events, :wait_for_no_relocating_shards, :wait_for_no_initializing_shards, :wait_for_status ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/params_registry.rb000066400000000000000000000022721361161326000337140ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/pending_tasks.rb000066400000000000000000000024251361161326000333320ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Returns a list of any cluster-level changes (e.g. create index, update mapping, allocate or fail shard) # which have not yet been executed and are queued up. # # @example Get a list of currently queued up tasks in the cluster # # client.cluster.pending_tasks # # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/cluster-pending.html # def pending_tasks(arguments={}) method = HTTP_GET path = "_cluster/pending_tasks" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:pending_tasks, [ :local, :master_timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/put_settings.rb000066400000000000000000000027031361161326000332300ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Update cluster settings. # # @example Disable shard allocation in the cluster until restart # # client.cluster.put_settings body: { transient: { 'cluster.routing.allocation.disable_allocation' => true } } # # @option arguments [Hash] :body The settings to be updated. Can be either `transient` or `persistent` (survives cluster restart). (*Required*) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-update-settings/ # def put_settings(arguments={}) method = HTTP_PUT path = "_cluster/settings" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] || {} perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_settings, [ :flat_settings, :master_timeout, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/remote_info.rb000066400000000000000000000013111361161326000330000ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Returns the configured remote cluster information # # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-remote-info.html # def remote_info(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_remote/info" params = {} body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:remote_info, [ ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/reroute.rb000066400000000000000000000046501361161326000321700ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Perform manual shard allocation in the cluster. # # Pass the operations you want to perform in the `:body` option. Use the `dry_run` option to # evaluate the result of operations without actually performing them. # # @example Move shard `0` of index `myindex` from node named _Node1_ to node named _Node2_ # # client.cluster.reroute body: { # commands: [ # { move: { index: 'myindex', shard: 0, from_node: 'Node1', to_node: 'Node2' } } # ] # } # # @note If you want to explicitly set the shard allocation to a certain node, you might # want to look at the `allocation.*` cluster settings. # # @option arguments [Hash] :body The definition of `commands` to perform (`move`, `cancel`, `allocate`) # @option arguments [Boolean] :dry_run Simulate the operation only and return the resulting state # @option arguments [Boolean] :explain Return an explanation of why the commands can or cannot be executed # @option arguments [Boolean] :retry_failed Retries allocation of shards that are blocked due to too many # subsequent allocation failures # @option arguments [List] :metric Limit the information returned to the specified metrics. Defaults to all # but metadata (options: _all, blocks, metadata, nodes, routing_table, master_node, version) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-reroute/ # def reroute(arguments={}) method = HTTP_POST path = "_cluster/reroute" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] || {} perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:reroute, [ :dry_run, :explain, :retry_failed, :metric, :master_timeout, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/state.rb000066400000000000000000000057351361161326000316300ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Get information about the cluster state (indices settings, allocations, etc) # # @example # # client.cluster.state # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform # the operation on all indices # @option arguments [List] :metric Limit the information returned to the specified metrics # (options: _all,blocks,metadata,nodes,routing_table,routing_nodes,master_node,version) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node # (default: false) # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Number] :wait_for_metadata_version Wait for the metadata version to be equal or greater # than the specified metadata version # @option arguments [Time] :wait_for_timeout The maximum time to wait for wait_for_metadata_version before # timing out # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves # into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed, none, all) # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-state/ # def state(arguments={}) arguments = arguments.clone index = arguments.delete(:index) metric = arguments.delete(:metric) method = HTTP_GET path = Utils.__pathify '_cluster/state', Utils.__listify(metric), Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) [:index_templates].each do |key| params[key] = Utils.__listify(params[key]) if params[key] end body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:state, [ :local, :master_timeout, :flat_settings, :wait_for_metadata_version, :wait_for_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/cluster/stats.rb000066400000000000000000000025721361161326000316420ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions # Returns statistical information about the cluster # # # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned # information; use `_local` to return information from the node you're connecting to, leave empty to get # information from all nodes # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-stats.html # def stats(arguments={}) method = 'GET' node_id = arguments.delete(:node_id) if node_id path = Utils.__pathify("_cluster/stats/nodes", node_id) else path = "_cluster/stats" end params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:stats, [ :flat_settings, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/count.rb000066400000000000000000000071611361161326000301520ustar00rootroot00000000000000module Elasticsearch module API module Actions # Get the number of documents for the cluster, index, type, or a query. # # @example Get the number of all documents in the cluster # # client.count # # @example Get the number of documents in a specified index # # client.count index: 'myindex' # # @example Get the number of documents matching a specific query # # index: 'my_index', body: { filtered: { filter: { terms: { foo: ['bar'] } } } } # # @option arguments [List] :index A comma-separated list of indices to restrict the results # @option arguments [List] :type A comma-separated list of types to restrict the results # @option arguments [Hash] :body A query to restrict the results specified with the Query DSL (optional) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :ignore_throttled Whether specified concrete, expanded or aliased indices should be ignored when throttled # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Number] :min_score Include only documents with a specific `_score` value in the result # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given in the query string # @option arguments [Boolean] :lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored # @option arguments [Number] :terminate_after The maximum count for each shard, upon reaching which the query execution will terminate early # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html # def count(arguments={}) method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_count' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:count, [ :ignore_unavailable, :ignore_throttled, :allow_no_indices, :expand_wildcards, :min_score, :preference, :routing, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :terminate_after ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/count_percolate.rb000066400000000000000000000102531361161326000322040ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return the number of queries matching a document. # # Percolator allows you to register queries and then evaluate a document against them: # the number of matching queries is returned in the response. # # @example Register query named "alert-1" for the "my-index" index # # client.index index: 'my-index', # type: '.percolator', # id: 'alert-1', # body: { query: { query_string: { query: 'foo' } } } # # @example Return the number of matching queries for a custom document # # client.count_percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo Bar" } } # # => { ..., total: 1} # # @example Return the number of matching queries for an existing document # # client.index index: 'my-index', type: 'my-type', id: '123', body: { title: "Foo Bar" } # # client.count_percolate index: 'my-index', type: 'my-type', id: '123' # # => { ..., total: 1} # # @option arguments [String] :index The index of the document being percolated. (*Required*) # @option arguments [String] :type The type of the document being percolated. (*Required*) # @option arguments [String] :id Fetch the document specified by index/type/id and # use it instead of the passed `doc` # @option arguments [Hash] :body The percolator request definition using the percolate DSL # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [String] :preference Specify the node or shard the operation should be performed on # (default: random) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are # open, closed or both. (options: open, closed) # @option arguments [String] :percolate_index The index to percolate the document into. Defaults to passed `index`. # @option arguments [String] :percolate_type The type to percolate document into. Defaults to passed `type`. # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-percolate.html # def count_percolate(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), arguments[:id], '_percolate/count' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:count_percolate, [ :routing, :preference, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_index, :percolate_type, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/create.rb000066400000000000000000000023471361161326000302660ustar00rootroot00000000000000module Elasticsearch module API module Actions # Create a new document. # # The API will create new document, if it doesn't exist yet -- in that case, it will return # a `409` error (`version_conflict_engine_exception`). # # You can leave out the `:id` parameter for the ID to be generated automatically # # @example Create a document with an ID # # client.create index: 'myindex', # type: 'doc', # id: '1', # body: { # title: 'Test 1' # } # # @example Create a document with an auto-generated ID # # client.create index: 'myindex', # type: 'doc', # body: { # title: 'Test 1' # } # # @option (see Actions#index) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#_automatic_id_generation # def create(arguments={}) if arguments[:id] index arguments.update :op_type => 'create' else index arguments end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/delete.rb000066400000000000000000000065631361161326000302710ustar00rootroot00000000000000module Elasticsearch module API module Actions # Delete a single document. # # @example Delete a document # # client.delete index: 'myindex', type: 'mytype', id: '1' # # @example Delete a document with specific routing # # client.delete index: 'myindex', type: 'mytype', id: '1', routing: 'abc123' # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (*Required*) # @option arguments [String] :wait_for_active_shards Sets the number of shard copies that must be active before # proceeding with the delete 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) # @option arguments [String] :parent ID of parent document # @option arguments [String] :refresh 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. (options: true, false, wait_for) # @option arguments [String] :routing Specific routing value # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Number] :if_seq_no only perform the delete operation if the last operation that has changed # the document has the specified sequence number # @option arguments [Number] :if_primary_term only perform the delete operation if the last operation that has # changed the document has the specified primary term # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type # (options: internal, external, external_gte, force) # # @see http://elasticsearch.org/guide/reference/api/delete/ # def delete(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_DELETE path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete, [ :wait_for_active_shards, :parent, :refresh, :routing, :timeout, :if_seq_no, :if_primary_term, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/delete_by_query.rb000066400000000000000000000152561361161326000322070ustar00rootroot00000000000000module Elasticsearch module API module Actions # Delete documents which match specified query. # # Provide the query either as a "query string" query in the `:q` argument, or using the Elasticsearch's # [Query DSL](http://www.elasticsearch.org/guide/reference/query-dsl/) in the `:body` argument. # # @example Deleting documents with a simple query # # client.delete_by_query index: 'myindex', q: 'title:test' # # @example Deleting documents using the Query DSL # # client.delete_by_query index: 'myindex', body: { query: { term: { published: false } } } # # @option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices (*Required*) # @option arguments [List] :type A comma-separated list of document types to search; leave empty to perform the operation on all types # @option arguments [Hash] :body The search definition using the Query DSL (*Required*) # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given in the query string # @option arguments [Number] :from Starting offset (default: 0) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :conflicts What to do when the delete by query hits version conflicts? (options: abort, proceed) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [Time] :scroll Specify how long a consistent view of the index should be maintained for scrolled search # @option arguments [String] :search_type Search operation type (options: query_then_fetch, dfs_query_then_fetch) # @option arguments [Time] :search_timeout Explicit timeout for each search request. Defaults to no timeout. # @option arguments [Number] :size Number of hits to return (default: 10) # @option arguments [List] :sort A comma-separated list of : pairs # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [Number] :terminate_after The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. # @option arguments [List] :stats Specific 'tag' of the request for logging and statistical purposes # @option arguments [Boolean] :version Specify whether to return document version as part of a hit # @option arguments [Boolean] :request_cache Specify if request cache should be used for this request or not, defaults to index level setting # @option arguments [Boolean] :refresh Should the effected indexes be refreshed? # @option arguments [Time] :timeout Time each individual bulk request should wait for shards that are unavailable. # @option arguments [String] :wait_for_active_shards Sets the number of shard copies that must be active before proceeding with the delete by query 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) # @option arguments [Number] :scroll_size Size on the scroll request powering the delete by query # @option arguments [Boolean] :wait_for_completion Should the request should block until the delete by query is complete. # @option arguments [Number] :requests_per_second The throttle for this request in sub-requests per second. -1 means no throttle. # @option arguments [Number] :slices The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html # def delete_by_query(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '/_delete_by_query' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_by_query, [ :analyzer, :analyze_wildcard, :default_operator, :df, :from, :ignore_unavailable, :allow_no_indices, :conflicts, :expand_wildcards, :lenient, :preference, :q, :routing, :scroll, :search_type, :search_timeout, :size, :sort, :_source, :_source_excludes, :_source_includes, :terminate_after, :stats, :version, :request_cache, :refresh, :timeout, :wait_for_active_shards, :scroll_size, :wait_for_completion, :requests_per_second, :slices ].freeze) end end end delete_by_query_rethrottle.rb000066400000000000000000000023251361161326000343750ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actionsmodule Elasticsearch module API module Actions # The value of requests_per_second can be changed on a running delete by query using the _rethrottle API # # @option arguments [String] :task_id The task id to rethrottle (*Required*) # @option arguments [Number] :requests_per_second The throttle to set on this request in floating sub-requests per second. -1 means set no throttle. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html # def delete_by_query_rethrottle(arguments={}) raise ArgumentError, "Required argument 'task_id' missing" unless arguments[:task_id] method = Elasticsearch::API::HTTP_POST path = "_delete_by_query/#{arguments[:task_id]}/_rethrottle" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_by_query_rethrottle, [ :requests_per_second ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/delete_script.rb000066400000000000000000000021571361161326000316500ustar00rootroot00000000000000module Elasticsearch module API module Actions # Remove an indexed script from Elasticsearch # # @option arguments [String] :id Script ID (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html # def delete_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_DELETE path = "_scripts/#{arguments.has_key?(:lang) ? "#{arguments.delete(:lang)}/" : ''}#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_script, [ :timeout, :master_timeout ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/delete_template.rb000066400000000000000000000010321361161326000321460ustar00rootroot00000000000000module Elasticsearch module API module Actions # Retrieve an indexed template from Elasticsearch # # @option arguments [String] :id Template ID # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html # def delete_template(arguments={}) method = HTTP_DELETE path = "_search/template/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/exists.rb000066400000000000000000000056641361161326000303470ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return true if the specified document exists, false otherwise. # # @example # # client.exists? index: 'myindex', type: 'mytype', id: '1' # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (use `_all` to fetch the first document matching the ID across all types) (*Required*) # @option arguments [List] :stored_fields A comma-separated list of stored fields to return in the response # @option arguments [String] :parent The ID of the parent document # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode # @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation # @option arguments [String] :routing Specific routing value # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://elasticsearch.org/guide/reference/api/get/ # def exists(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] arguments[:type] ||= UNDERSCORE_ALL method = HTTP_HEAD path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists?, :exists # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:exists, [ :stored_fields, :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_excludes, :_source_includes, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/exists_source.rb000066400000000000000000000051441361161326000317200ustar00rootroot00000000000000module Elasticsearch module API module Actions # The get API allows to get a typed JSON document from the index based on its id. # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document; use `_all` to fetch the first document matching the ID across all types (*Required*) # @option arguments [String] :parent The ID of the parent document # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode # @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation # @option arguments [String] :routing Specific routing value # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html # def exists_source(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = Elasticsearch::API::HTTP_HEAD path = "#{arguments[:index]}/#{arguments[:type]}/#{arguments[:id]}/_source" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:exists_source, [ :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_excludes, :_source_includes, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/explain.rb000066400000000000000000000073161361161326000304640ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return information if and how well a document matches a query. # # The returned information contains a `_score` and its explanation, if the document matches the query. # # @example Passing the query in the Lucene query syntax as the `:q` URL parameter # # client.explain index: 'myindex', type: 'mytype', id: '1', q: 'test' # # @example Passing the query in the Query DSL as the request `:body` # # client.explain index: 'myindex', type: 'mytype', id: '1', # body: { query: { match: { title: 'test' } } } # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (*Required*) # @option arguments [Hash] :body The query definition using the Query DSL # @option arguments [Boolean] :analyze_wildcard Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false) # @option arguments [String] :analyzer The analyzer for the query string query # @option arguments [String] :default_operator The default operator for query string query (AND or OR) (options: AND, OR) # @option arguments [String] :df The default field for query string query (default: _all) # @option arguments [List] :stored_fields A comma-separated list of stored fields to return in the response # @option arguments [Boolean] :lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored # @option arguments [String] :parent The ID of the parent document # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [String] :routing Specific routing value # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @see http://elasticsearch.org/guide/reference/api/explain/ # def explain(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_explain' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:explain, [ :analyze_wildcard, :analyzer, :default_operator, :df, :stored_fields, :lenient, :parent, :preference, :q, :routing, :_source, :_source_excludes, :_source_includes ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/field_caps.rb000066400000000000000000000037061361161326000311140ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return the capabilities of fields among multiple indices # # @example # client.field_caps fields: '*' # # => { "fields" => "t"=>{"text"=>{"type"=>"text", "searchable"=>true, "aggregatable"=>false}} ... # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Hash] :body Field json objects containing an array of field names # @option arguments [List] :fields A comma-separated list of field names # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html # def field_caps(arguments={}) raise ArgumentError, "Required argument 'fields' missing" unless arguments[:fields] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_field_caps' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:field_caps, [ :fields, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/field_stats.rb000066400000000000000000000035321361161326000313210ustar00rootroot00000000000000module Elasticsearch module API module Actions # Returns statistical information about a field without executing a search. # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [List] :fields A comma-separated list of fields for to get field statistics for (min value, max value, and more) # @option arguments [String] :level Defines if field stats should be returned on a per index level or on a cluster wide level (options: indices, cluster) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/master/search-field-stats.html # def field_stats(arguments={}) method = 'GET' path = Utils.__pathify Utils.__escape(arguments[:index]), "_field_stats" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:field_stats, [ :fields, :level, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/get.rb000066400000000000000000000066431361161326000276050ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return a specified document. # # The response contains full document, as stored in Elasticsearch, incl. `_source`, `_version`, etc. # # @example Get a document # # client.get index: 'myindex', type: 'mytype', id: '1' # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (use `_all` to fetch the first document matching the ID across all types) (*Required*) # @option arguments [List] :stored_fields A comma-separated list of stored fields to return in the response # @option arguments [String] :parent The ID of the parent document # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode # @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation # @option arguments [String] :routing Specific routing value # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [List] :_source_exclude A list of fields to exclude from the returned _source field # @option arguments [List] :_source_include A list of fields to extract and return from the _source field # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://elasticsearch.org/guide/reference/api/get/ # def get(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] arguments[:type] ||= UNDERSCORE_ALL method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil params[:fields] = Utils.__listify(params[:fields]) if params[:fields] if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get, [ :stored_fields, :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_excludes, :_source_includes, :_source_exclude, :_source_include, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/get_script.rb000066400000000000000000000016761361161326000311720ustar00rootroot00000000000000module Elasticsearch module API module Actions # Retrieve an indexed script from Elasticsearch # # @option arguments [String] :id Script ID (*Required*) # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html # def get_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_GET path = "_scripts/#{arguments.has_key?(:lang) ? "#{arguments.delete(:lang)}/" : ''}#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_script, [ :master_timeout ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/get_source.rb000066400000000000000000000057741361161326000311710ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return a specified document's `_source`. # # The response contains just the original document, as passed to Elasticsearch during indexing. # # @example Get a document `_source` # # client.get_source index: 'myindex', type: 'mytype', id: '1' # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document; use `_all` to fetch the first document matching the ID across all types (*Required*) # @option arguments [String] :parent The ID of the parent document # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode # @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation # @option arguments [String] :routing Specific routing value # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://elasticsearch.org/guide/reference/api/get/ # # @since 0.90.1 # def get_source(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] arguments[:type] ||= UNDERSCORE_ALL method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_source' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil params[:fields] = Utils.__listify(params[:fields]) if params[:fields] Utils.__rescue_from_not_found do perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_source, [ :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_excludes, :_source_includes, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/get_template.rb000066400000000000000000000015271361161326000314740ustar00rootroot00000000000000module Elasticsearch module API module Actions # Retrieve an indexed script from Elasticsearch # # @option arguments [String] :id Template ID (*Required*) # @option arguments [Hash] :body The document # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html # def get_template(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_GET path = "_scripts/#{arguments[:id]}" params = {} body = arguments[:body] if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/index.rb000066400000000000000000000127071361161326000301330ustar00rootroot00000000000000module Elasticsearch module API module Actions # Create or update a document. # # The `index` API will either _create_ a new document, or _update_ an existing one, when a document `:id` # is passed. When creating a document, an ID will be auto-generated, when it's not passed as an argument. # # You can specifically enforce the _create_ operation by setting the `op_type` argument to `create`, or # by using the {Actions#create} method. # # Optimistic concurrency control is performed, when the `version` argument is specified. By default, # no version checks are performed. # # By default, the document will be available for {Actions#get} immediately, for {Actions#search} only # after an index refresh operation has been performed (either automatically or manually). # # @example Create or update a document `myindex/mytype/1` # # client.index index: 'myindex', # type: 'mytype', # id: '1', # body: { # title: 'Test 1', # tags: ['y', 'z'], # published: true, # published_at: Time.now.utc.iso8601, # counter: 1 # } # # @example Refresh the index after the operation (useful e.g. in integration tests) # # client.index index: 'myindex', type: 'mytype', id: '1', body: { title: 'TEST' }, refresh: true # client.search index: 'myindex', q: 'title:test' # # @example Create a document with a specific expiration time (TTL) # # # Decrease the default housekeeping interval first: # client.cluster.put_settings body: { transient: { 'indices.ttl.interval' => '1s' } } # # # Enable the `_ttl` property for all types within the index # client.indices.create index: 'myindex', body: { mappings: { mytype: { _ttl: { enabled: true } } } } # # client.index index: 'myindex', type: 'mytype', id: '1', body: { title: 'TEST' }, ttl: '5s' # # sleep 3 and client.get index: 'myindex', type: 'mytype', id: '1' # # => {"_index"=>"myindex" ... "_source"=>{"title"=>"TEST"}} # # sleep 3 and client.get index: 'myindex', type: 'mytype', id: '1' # # => Elasticsearch::Transport::Transport::Errors::NotFound: [404] ... # # @option arguments [String] :id Document ID # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (*Required*) # @option arguments [Hash] :body The document (*Required*) # @option arguments [String] :wait_for_active_shards Sets the number of shard copies that must be active before proceeding with the index 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) # @option arguments [String] :op_type Explicit operation type (options: index, create) # @option arguments [String] :parent ID of the parent document # @option arguments [String] :refresh If `true` then refresh the affected 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. (options: true, false, wait_for) # @option arguments [String] :routing Specific routing value # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # @option arguments [Number] :if_seq_no only perform the index operation if the last operation that has changed the document has the specified sequence number # @option arguments [Number] :if_primary_term only perform the index operation if the last operation that has changed the document has the specified primary term # @option arguments [String] :pipeline The pipeline id to preprocess incoming documents with # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html # def index(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = arguments[:id] ? HTTP_PUT : HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:index, [ :wait_for_active_shards, :op_type, :parent, :refresh, :routing, :timeout, :version, :version_type, :if_seq_no, :if_primary_term, :pipeline ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/000077500000000000000000000000001361161326000301065ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/analyze.rb000066400000000000000000000047341361161326000321060ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return the result of the analysis process (tokens) # # Allows to "test-drive" the Elasticsearch analysis process by performing the analysis on the # same text with different analyzers. An ad-hoc analysis chain can be built from specific # _tokenizer_ and _filters_. # # @example Analyze text "Quick Brown Jumping Fox" with the _snowball_ analyzer # # client.indices.analyze text: 'The Quick Brown Jumping Fox', analyzer: 'snowball' # # @example Analyze text "Quick Brown Jumping Fox" with a custom tokenizer and filter chain # # client.indices.analyze body: { text: 'The Quick Brown Jumping Fox', # tokenizer: 'whitespace', # filter: ['lowercase','stop'] } # # @note If your text for analysis is longer than 4096 bytes then you should use the :body argument, rather than :text, to avoid HTTP transport errors # # @example Analyze text "Quick Brown Jumping Fox" with custom tokenizer, token and character filters # # client.indices.analyze body: { text: 'The Quick Brown Jumping Fox', # tokenizer: 'standard', # char_filter: ['html_strip'] } # # @option arguments [String] :index The name of the index to scope the operation # @option arguments [Hash] :body Define analyzer/tokenizer parameters and the text on which the analysis should be performed # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-analyze/ # def analyze(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_analyze' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) params[:filters] = Utils.__listify(params[:filters]) if params[:filters] body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:analyze, [ :index ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/clear_cache.rb000066400000000000000000000060501361161326000326450ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Clear caches and other auxiliary data structures. # # Can be performed against a specific index, or against all indices. # # By default, all caches and data structures will be cleared. # Pass a specific cache or structure name to clear just a single one. # # @example Clear all caches and data structures # # client.indices.clear_cache # # @example Clear the field data structure only # # client.indices.clear_cache field_data: true # # @example Clear only specific field in the field data structure # # client.indices.clear_cache field_data: true, fields: 'created_at', filter_cache: false, id_cache: false # # @option arguments [List] :index A comma-separated list of index name to limit the operation # @option arguments [Boolean] :field_data Clear field data. This is deprecated. Prefer `fielddata`. # @option arguments [Boolean] :fielddata Clear field data # @option arguments [List] :fields A comma-separated list of fields to clear when using the `fielddata` parameter (default: all) # @option arguments [Boolean] :query Clear query caches # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [List] :index A comma-separated list of index name to limit the operation # @option arguments [Boolean] :request_cache Clear request cache # @option arguments [Boolean] :request Clear request cache # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-clearcache.html # def clear_cache(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_cache/clear' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:clear_cache, [ :field_data, :fielddata, :fields, :query, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :index, :request_cache, :request ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/close.rb000066400000000000000000000040261361161326000315420ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Close an index (keep the data on disk, but deny operations with the index). # # A closed index can be opened again with the {Indices::Actions#close} API. # # @example Close index named _myindex_ # # client.indices.close index: 'myindex' # # @option arguments [List] :index A comma separated list of indices to close (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html # def close(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_close' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:close, [ :timeout, :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/create.rb000066400000000000000000000110111361161326000316700ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Create an index. # # Pass the index `settings` and `mappings` in the `:body` attribute. # # @example Create an index with specific settings, custom analyzers and mappings # # client.indices.create index: 'test', # body: { # settings: { # index: { # number_of_shards: 1, # number_of_replicas: 0, # 'routing.allocation.include.name' => 'node-1' # }, # analysis: { # filter: { # ngram: { # type: 'nGram', # min_gram: 3, # max_gram: 25 # } # }, # analyzer: { # ngram: { # tokenizer: 'whitespace', # filter: ['lowercase', 'stop', 'ngram'], # type: 'custom' # }, # ngram_search: { # tokenizer: 'whitespace', # filter: ['lowercase', 'stop'], # type: 'custom' # } # } # } # }, # mappings: { # document: { # properties: { # title: { # type: 'multi_field', # fields: { # title: { type: 'string', analyzer: 'snowball' }, # exact: { type: 'string', analyzer: 'keyword' }, # ngram: { type: 'string', # index_analyzer: 'ngram', # search_analyzer: 'ngram_search' # } # } # } # } # } # } # } # # @option arguments [String] :index The name of the index (*Required*) # @option arguments [Hash] :body The configuration for the index (`settings` and `mappings`) # @option arguments [String] :wait_for_active_shards Set the number of active shards to wait for before the operation returns. # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :update_all_types Whether to update the mapping for all fields with the same name across all types or not # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html # def create(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_PUT path = Utils.__pathify Utils.__escape(arguments[:index]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:create, [ :wait_for_active_shards, :timeout, :master_timeout, :update_all_types, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete.rb000066400000000000000000000045401361161326000317000ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Delete an index, list of indices, or all indices in the cluster. # # @example Delete an index # # client.indices.delete index: 'foo' # # @example Delete a list of indices # # client.indices.delete index: ['foo', 'bar'] # client.indices.delete index: 'foo,bar' # # # @example Delete a list of indices matching wildcard expression # # client.indices.delete index: 'foo*' # # @example Delete all indices # # client.indices.delete index: '_all' # # @option arguments [List] :index A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :ignore_unavailable Ignore unavailable indexes (default: false) # @option arguments [Boolean] :allow_no_indices Ignore if a wildcard expression resolves to no concrete indices (default: false) # @option arguments [String] :expand_wildcards Whether wildcard expressions should get expanded to open or closed indices (default: open) (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html # def delete(arguments={}) method = HTTP_DELETE path = Utils.__pathify Utils.__listify(arguments[:index]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete, [ :timeout, :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_alias.rb000066400000000000000000000033721361161326000330530ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Delete a single index alias. # # @example Delete an alias # # client.indices.delete_alias index: 'foo', name: 'bar' # # See the {Indices::Actions#update_aliases} for performing operations with index aliases in bulk. # # @option arguments [List] :index A comma-separated list of index names (supports wildcards); use `_all` for all indices (*Required*) # @option arguments [List] :name A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices. (*Required*) # @option arguments [Time] :timeout Explicit timestamp for the document # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html # def delete_alias(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] method = HTTP_DELETE path = Utils.__pathify Utils.__escape(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_alias, [ :timeout, :master_timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_mapping.rb000066400000000000000000000017411361161326000334130ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Delete all documents and mapping for a specific document type. # # @option arguments [List] :index A comma-separated list of index names; use `_all` for all indices (*Required*) # @option arguments [String] :type The name of the document type to delete (*Required*) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-delete-mapping/ # def delete_mapping(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = HTTP_DELETE path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__escape(arguments[:type]) params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_template.rb000066400000000000000000000031111361161326000335640ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Delete an index template. # # @example Delete a template named _mytemplate_ # # client.indices.delete_template name: 'mytemplate' # # @example Delete all templates # # client.indices.delete_template name: '*' # # @option arguments [String] :name The name of the template (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html # def delete_template(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] method = HTTP_DELETE path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_template, [ :timeout, :master_timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_warmer.rb000066400000000000000000000026021361161326000332520ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Delete one or more warmers for a list of indices. # # @example Delete a warmer named _mywarmer_ for index named _myindex_ # # client.indices.delete_warmer index: 'myindex', name: 'mywarmer' # # @option arguments [List] :index A comma-separated list of index names to register warmer for; use `_all` # or empty string to perform the operation on all indices (*Required*) # @option arguments [String] :name The name of the warmer (supports wildcards); leave empty to delete all warmers # @option arguments [List] :type A comma-separated list of document types to register warmer for; use `_all` # or empty string to perform the operation on all types # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-warmers/ # def delete_warmer(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_DELETE path = Utils.__pathify Utils.__listify(arguments[:index]), '_warmer', Utils.__listify(arguments[:name]) params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists.rb000066400000000000000000000042041361161326000317520ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return true if the index (or all indices in a list) exists, false otherwise. # # @example Check whether index named _myindex_ exists # # client.indices.exists? index: 'myindex' # # @option arguments [List] :index A comma-separated list of index names (*Required*) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Boolean] :ignore_unavailable Ignore unavailable indexes (default: false) # @option arguments [Boolean] :allow_no_indices Ignore if a wildcard expression resolves to no concrete indices (default: false) # @option arguments [String] :expand_wildcards Whether wildcard expressions should get expanded to open or closed indices (default: open) (options: open, closed, none, all) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Boolean] :include_defaults Whether to return all default setting for each of the indices. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-exists.html # def exists(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_HEAD path = Utils.__listify(arguments[:index]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists?, :exists # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:exists, [ :local, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :flat_settings, :include_defaults ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists_alias.rb000066400000000000000000000041001361161326000331160ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return true if the specified alias exists, false otherwise. # # @example Check whether index alias named _myalias_ exists # # client.indices.exists_alias? name: 'myalias' # # @option arguments [List] :index A comma-separated list of index names to filter aliases # @option arguments [List] :name A comma-separated list of alias names to return (*Required*) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html # def exists_alias(arguments={}) method = HTTP_HEAD path = Utils.__pathify Utils.__listify(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists_alias?, :exists_alias # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:exists_alias, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists_template.rb000066400000000000000000000031701361161326000336460ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return true if the specified index template exists, false otherwise. # # client.indices.exists_template? name: 'mytemplate' # # @option arguments [List] :name The comma separated names of the index templates (*Required*) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html # def exists_template(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] method = HTTP_HEAD path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists_template?, :exists_template # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:exists_template, [ :flat_settings, :master_timeout, :local ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists_type.rb000066400000000000000000000043511361161326000330160ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return true if the specified type exists, false otherwise. # # client.indices.exists_type? index: 'myindex', type: 'mytype' # # @option arguments [List] :index A comma-separated list of index names; use `_all` to check the types across all indices (*Required*) # @option arguments [List] :type A comma-separated list of document types to check (*Required*) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-types-exists.html # def exists_type(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = HTTP_HEAD path = Utils.__pathify Utils.__listify(arguments[:index]), '_mapping', Utils.__escape(arguments[:type]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists_type?, :exists_type # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:exists_type, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/flush.rb000066400000000000000000000046361361161326000315650ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # "Flush" the index or indices. # # The "flush" operation clears the transaction log and memory and writes data to disk. # It corresponds to a Lucene "commit" operation. # # @note The flush operation is handled automatically by Elasticsearch, you don't need to perform it manually. # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string for all indices # @option arguments [Boolean] :force Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal) # @option arguments [Boolean] :wait_if_ongoing If set to true the flush operation will block until the flush can be executed if another flush operation is already executing. The default is true. If set to false the flush will be skipped iff if another flush operation is already running. # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-flush/ # def flush(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_flush' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:flush, [ :force, :wait_if_ongoing, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/flush_synced.rb000066400000000000000000000032231361161326000331210ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string for all indices # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-synced-flush.html # def flush_synced(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_flush/synced' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:flush_synced, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/forcemerge.rb000066400000000000000000000056711361161326000325620ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Force merge an index, list of indices, or all indices in the cluster. # # @example Fully force merge an index # # client.indices.forcemerge index: 'foo', max_num_segments: 1 # # @example Do not flush index after force-merging # # client.indices.forcemerge index: 'foo', flush: false # # @example Do not expunge deleted documents after force-merging # # client.indices.forcemerge index: 'foo', only_expunge_deletes: false # # @example Force merge a list of indices # # client.indices.forcemerge index: ['foo', 'bar'] # client.indices.forcemerge index: 'foo,bar' # # @example forcemerge a list of indices matching wildcard expression # # client.indices.forcemerge index: 'foo*' # # @example forcemerge all indices # # client.indices.forcemerge index: '_all' # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Boolean] :flush Specify whether the index should be flushed after performing the operation (default: true) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Number] :max_num_segments The number of segments the index should be merged into (default: dynamic) # @option arguments [Boolean] :only_expunge_deletes Specify whether the operation should only expunge deleted documents # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-forcemerge.html # def forcemerge(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_forcemerge' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:forcemerge, [ :flush, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :max_num_segments, :only_expunge_deletes ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/freeze.rb000066400000000000000000000027551361161326000317240ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # In order to keep indices available and queryable for a longer period but at the same time reduce their # hardware requirements they can be transitioned into a frozen state. Once an index is frozen, all of its # transient shard memory (aside from mappings and analyzers) is moved to persistent storage. # # @option arguments [List] :index A comma separated list of indices to freeze. (*Required*) # # @note This feature is available in the Platinum distribution of Elasticsearch. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/frozen-indices.html # def freeze(arguments = {}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :timeout, :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :wait_for_active_shards] arguments = arguments.clone index = arguments.delete(:index) method = Elasticsearch::API::HTTP_POST path = Elasticsearch::API::Utils.__pathify Elasticsearch::API::Utils.__listify(index), '_freeze' params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params perform_request(method, path, params).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get.rb000066400000000000000000000040661361161326000312200ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Retrieve information about one or more indices # # @option arguments [List] :index A comma-separated list of index names (*Required*) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Boolean] :ignore_unavailable Ignore unavailable indexes (default: false) # @option arguments [Boolean] :allow_no_indices Ignore if a wildcard expression resolves to no concrete indices (default: false) # @option arguments [String] :expand_wildcards Whether wildcard expressions should get expanded to open or closed indices (default: open) (options: open, closed, none, all) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Boolean] :include_defaults Whether to return all default setting for each of the indices. # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-index.html # def get(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments.delete(:feature)) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get, [ :local, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :flat_settings, :include_defaults, :master_timeout, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_alias.rb000066400000000000000000000040561361161326000323700ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Get information about a specific alias. # # @example Return all indices an alias points to # # client.indices.get_alias name: '2013' # # @example Return all indices matching a wildcard pattern an alias points to # # client.indices.get_alias index: 'log*', name: '2013' # # @option arguments [List] :index A comma-separated list of index names to filter aliases # @option arguments [List] :name A comma-separated list of alias names to return # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html # def get_alias(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_alias, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_aliases.rb000066400000000000000000000026171361161326000327210ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Get a list of all aliases, or aliases for a specific index. # # @example Get a list of all aliases # # client.indices.get_aliases # # @option arguments [List] :index A comma-separated list of index names to filter aliases # @option arguments [List] :name A comma-separated list of alias names to filter # @option arguments [Time] :timeout Explicit timestamp for the document # @option arguments [Boolean] :local Return local information, # do not retrieve the state from master node (default: false) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html # def get_aliases(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_aliases', Utils.__listify(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_aliases, [ :timeout, :local ].freeze) end end end end get_field_mapping.rb000066400000000000000000000055441361161326000340210ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indicesmodule Elasticsearch module API module Indices module Actions # Return the mapping definition for specific field (or fields) # # @example Get mapping for a specific field across all indices # # client.indices.get_field_mapping field: 'foo' # # @example Get mapping for a specific field in an index # # client.indices.get_field_mapping index: 'foo', field: 'bar' # # @example Get mappings for multiple fields in an index # # client.indices.get_field_mapping index: 'foo', field: ['bar', 'bam'] # # @option arguments [List] :index A comma-separated list of index names # @option arguments [List] :type A comma-separated list of document types # @option arguments [List] :fields A comma-separated list of fields (*Required*) # @option arguments [Boolean] :include_defaults Whether the default mapping values should be returned as well # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-field-mapping.html # def get_field_mapping(arguments={}) arguments = arguments.clone fields = arguments.delete(:field) || arguments.delete(:fields) raise ArgumentError, "Required argument 'field' missing" unless fields method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), '_mapping', Utils.__listify(arguments[:type]), 'field', Utils.__listify(fields) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_field_mapping, [ :include_defaults, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_mapping.rb000066400000000000000000000046101361161326000327260ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return the mapping definitions for all indices, or specific indices/types. # # @example Get all mappings in the cluster # # client.indices.get_mapping # # @example Get mapping for a specific index # # client.indices.get_mapping index: 'foo' # # @example Get mapping for a specific type in a specific index # # client.indices.get_mapping index: 'foo', type: 'baz' # # # @option arguments [List] :index A comma-separated list of index names # @option arguments [List] :type A comma-separated list of document types # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html # def get_mapping(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_mapping', Utils.__listify(arguments[:type]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_mapping, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :master_timeout, :local, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_settings.rb000066400000000000000000000056621361161326000331430ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return the settings for all indices, or a list of indices. # # @example Get settings for all indices # # client.indices.get_settings # # @example Get settings for the 'foo' index # # client.indices.get_settings index: 'foo' # # @example Get settings for indices beginning with foo # # client.indices.get_settings prefix: 'foo' # # @example Get settings for an index named _myindex_ # # client.indices.get_settings index: 'myindex' # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [List] :name The name of the settings that should be included # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Boolean] :include_defaults Whether to return all default setting for each of the indices. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html # def get_settings(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), arguments.delete(:prefix), '_settings', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_settings, [ :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :flat_settings, :local, :include_defaults ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_template.rb000066400000000000000000000032021361161326000331020ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Get a single index template. # # @example Get all templates # # client.indices.get_template # # @example Get a template named _mytemplate_ # # client.indices.get_template name: 'mytemplate' # # @note Use the {Cluster::Actions#state} API to get a list of all templates. # # @option arguments [List] :name The comma separated names of the index templates # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html # def get_template(arguments={}) method = HTTP_GET path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_template, [ :flat_settings, :master_timeout, :local, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_warmer.rb000066400000000000000000000056321361161326000325750ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Get one or more warmers for an index. # # @example Get all warmers # # client.indices.get_warmer index: '_all' # # @example Get all warmers matching a wildcard expression # # client.indices.get_warmer index: '_all', name: 'ba*' # # @example Get all warmers for a single index # # client.indices.get_warmer index: 'foo' # # @example Get a specific warmer # # client.indices.get_warmer index: 'foo', name: 'bar' # # @option arguments [List] :index A comma-separated list of index names to restrict the operation; # use `_all` to perform the operation on all indices (*Required*) # @option arguments [String] :name The name of the warmer (supports wildcards); leave empty to get all warmers # @option arguments [List] :type A comma-separated list of document types to restrict the operation; # leave empty to perform the operation on all types # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed) # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore # `missing` ones (options: none, missing) @until 1.0 # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-warmers/ # def get_warmer(arguments={}) method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), '_warmer', Utils.__escape(arguments[:name]) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_warmer, [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/open.rb000066400000000000000000000041271361161326000314000ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Open a previously closed index (see the {Indices::Actions#close} API). # # @example Open index named _myindex_ # # client.indices.open index: 'myindex' # # @option arguments [List] :index A comma separated list of indices to open (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [String] :wait_for_active_shards Sets the number of active shards to wait for before the operation returns. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html # def open(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), '_open' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:open, [ :timeout, :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :wait_for_active_shards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/optimize.rb000066400000000000000000000103551361161326000322770ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Perform an index optimization. # # The "optimize" operation merges the index segments, increasing search performance. # It corresponds to a Lucene "merge" operation. # # @deprecated The "optimize" action has been deprecated in favor of forcemerge [https://github.com/elastic/elasticsearch/pull/13778] # # @example Fully optimize an index (merge to one segment) # # client.indices.optimize index: 'foo', max_num_segments: 1, wait_for_merge: false # # @note The optimize operation is handled automatically by Elasticsearch, you don't need to perform it manually. # The operation is expensive in terms of resources (I/O, CPU, memory) and can take a long time to # finish, potentially reducing operability of your cluster; schedule the manual optimization accordingly. # # @option arguments [List] :index A comma-separated list of index names; use `_all` # or empty string to perform the operation on all indices # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed) # @option arguments [Boolean] :flush Specify whether the index should be flushed after performing the operation # (default: true) # @option arguments [Boolean] :force Force a merge operation to run, even when the index has a single segment # (default: true) # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore # `missing` ones (options: none, missing) @until 1.0 # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # @option arguments [Number] :max_num_segments The number of segments the index should be merged into # (default: dynamic) # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :only_expunge_deletes Specify whether the operation should only expunge # deleted documents # @option arguments [Boolean] :refresh Specify whether the index should be refreshed after performing the operation # (default: true) # @option arguments [Boolean] :wait_for_merge Specify whether the request should block until the merge process # is finished (default: true) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-optimize/ # def optimize(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_optimize' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:optimize, [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :flush, :force, :master_timeout, :max_num_segments, :only_expunge_deletes, :operation_threading, :refresh, :wait_for_merge ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/params_registry.rb000066400000000000000000000022721361161326000336510ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_alias.rb000066400000000000000000000041411361161326000324140ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Create or update a single index alias. # # @example Create an alias for current month # # client.indices.put_alias index: 'logs-2013-06', name: 'current-month' # # @example Create an alias for multiple indices # # client.indices.put_alias index: 'logs-2013-06', name: 'year-2013' # client.indices.put_alias index: 'logs-2013-05', name: 'year-2013' # # See the {Indices::Actions#update_aliases} for performing operations with index aliases in bulk. # # @option arguments [List] :index A comma-separated list of index names the alias should point to (supports wildcards); use `_all` to perform the operation on all indices. (*Required*) # @option arguments [String] :name The name of the alias to be created or updated (*Required*) # @option arguments [Hash] :body The settings for the alias, such as `routing` or `filter` # @option arguments [Time] :timeout Explicit timestamp for the document # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html # def put_alias(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] method = HTTP_PUT path = Utils.__pathify Utils.__listify(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_alias, [ :timeout, :master_timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_mapping.rb000066400000000000000000000057061361161326000327660ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Create or update mapping. # # Pass the mapping definition(s) in the `:body` argument. # # @example Create or update a mapping for a specific document type # # client.indices.put_mapping index: 'myindex', type: 'mytype', body: { # mytype: { # properties: { # title: { type: 'string', analyzer: 'snowball' } # } # } # } # # @example Update the mapping for a specific type in all indices # # client.indices.put_mapping type: 'mytype', body: { # mytype: { # dynamic: 'strict' # } # } # # @option arguments [List] :index A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices. # @option arguments [String] :type The name of the document type (*Required*) # @option arguments [Hash] :body The mapping definition (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :update_all_types Whether to update the mapping for all fields with the same name across all types or not # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html # def put_mapping(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_PUT path = Utils.__pathify Utils.__listify(arguments[:index]), '_mapping', Utils.__escape(arguments[:type]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_mapping, [ :timeout, :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :update_all_types, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_settings.rb000066400000000000000000000060771361161326000331750ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Update the settings for one or multiple indices. # # @example Change the number of replicas for all indices # # client.indices.put_settings body: { index: { number_of_replicas: 0 } } # # # @example Change the number of replicas for a specific index # # client.indices.put_settings index: 'myindex', body: { index: { number_of_replicas: 0 } } # # # @example Disable "flush" for all indices # # client.indices.put_settings body: { 'index.translog.disable_flush' => true } # # @example Allocate specific index on specific nodes # # client.indices.put_settings index: 'my-big-index', # body: { 'index.routing.allocation.require.tag' => 'bigbox' } # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Hash] :body The index settings to be updated (*Required*) # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :preserve_existing Whether to update existing settings. If set to `true` existing settings on an index remain unchanged, the default is `false` # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-update-settings.html # def put_settings(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_PUT path = Utils.__pathify Utils.__listify(arguments[:index]), '_settings' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_settings, [ :master_timeout, :timeout, :preserve_existing, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :flat_settings ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_template.rb000066400000000000000000000041301361161326000331340ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Create or update an index template. # # @example Create a template for all indices starting with `logs-` # # client.indices.put_template name: 'foo', # body: { template: 'logs-*', settings: { 'index.number_of_shards' => 1 } } # # @option arguments [String] :name The name of the template (*Required*) # @option arguments [Hash] :body The template definition (*Required*) # @option arguments [Number] :order The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers) # @option arguments [Boolean] :create Whether the index template should only be added if new or can also replace an existing one # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html # def put_template(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_PUT path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_template, [ :order, :create, :timeout, :master_timeout, :flat_settings, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_warmer.rb000066400000000000000000000071771361161326000326340ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Create or update an index warmer. # # An index warmer will run before an index is refreshed, ie. available for search. # It allows you to register "heavy" queries with popular filters, facets or sorts, # increasing performance when the index is searched for the first time. # # @example Register a warmer which will populate the caches for `published` filter and sorting on `created_at` # # client.indices.put_warmer index: 'myindex', # name: 'main', # body: { # query: { filtered: { filter: { term: { published: true } } } }, # sort: [ "created_at" ] # } # # @option arguments [List] :index A comma-separated list of index names to register the warmer for; use `_all` # or empty string to perform the operation on all indices (*Required*) # @option arguments [String] :name The name of the warmer (*Required*) # @option arguments [List] :type A comma-separated list of document types to register the warmer for; # leave empty to perform the operation on all types # @option arguments [Hash] :body The search request definition for the warmer # (query, filters, facets, sorting, etc) (*Required*) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed) # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore # `missing` ones (options: none, missing) @until 1.0 # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-warmers/ # def put_warmer(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_PUT path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_warmer', Utils.__listify(arguments[:name]) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_warmer, [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/recovery.rb000066400000000000000000000031621361161326000322730ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return information about shard recovery for one or more indices # # @example Get recovery information for a single index # # client.indices.recovery index: 'foo' # # @example Get detailed recovery information for multiple indices # # client.indices.recovery index: ['foo', 'bar'], detailed: true # # @example Get recovery information for all indices # # client.indices.recovery # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Boolean] :detailed Whether to display detailed information about shard recovery # @option arguments [Boolean] :active_only Display only those recoveries that are currently on-going # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-recovery.html # def recovery(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_recovery' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:recovery, [ :detailed, :active_only ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/refresh.rb000066400000000000000000000044101361161326000320700ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Refresh the index and to make the changes (creates, updates, deletes) searchable. # # By default, Elasticsearch has a delay of 1 second until changes to an index are # available for search; the delay is configurable, see {Indices::Actions#put_settings}. # # You can trigger this operation explicitly, for example when performing a sequence of commands # in integration tests, or when you need to perform a manual "synchronization" of the index # with an external system at given moment. # # @example Refresh an index named _myindex_ # # client.indices.refresh index: 'myindex' # # @note The refresh operation can adversely affect indexing throughput when used too frequently. # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html # def refresh(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_refresh' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:refresh, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/rollover.rb000066400000000000000000000040201361161326000322730ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # The rollover index API rolls an alias over to a new index when the existing index # is considered to be too large or too old # # @option arguments [String] :alias The name of the alias to rollover (*Required*) # @option arguments [String] :new_index The name of the rollover index # @option arguments [Hash] :body The conditions that needs to be met for executing rollover # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :dry_run If set to true the rollover action will only be validated but not actually performed even if a condition matches. The default is false # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [String] :wait_for_active_shards Set the number of active shards to wait for on the newly created rollover index before the operation returns. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-rollover-index.html # def rollover(arguments={}) raise ArgumentError, "Required argument 'alias' missing" unless arguments[:alias] arguments = arguments.clone source = arguments.delete(:alias) target = arguments.delete(:new_index) method = HTTP_POST path = Utils.__pathify Utils.__escape(source), '_rollover', Utils.__escape(target) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:rollover, [ :timeout, :dry_run, :master_timeout, :wait_for_active_shards, :include_type_name ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/seal.rb000066400000000000000000000013011361161326000313520ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # "Seal" and index or indices for faster recovery # # @option arguments [List] :index A comma-separated list of index names; # use `_all` or empty string for all indices # # @see http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-seal.html # def seal(arguments={}) method = 'POST' path = Utils.__pathify Utils.__listify(arguments[:index]), '_seal' params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/segments.rb000066400000000000000000000035141361161326000322630ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return information about segments for one or more indices. # # The response contains information about segment size, number of documents, deleted documents, etc. # See also {Indices::Actions#optimize}. # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :verbose Includes detailed memory usage by Lucene. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-segments.html # def segments(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_segments' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:segments, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :verbose ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/shard_stores.rb000066400000000000000000000034221361161326000331340ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Provides low-level information about shards (allocated nodes, exceptions, ...) # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [List] :status A comma-separated list of statuses used to filter on shards to get store information for (options: green, yellow, red, all) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shards-stores.html # def shard_stores(arguments={}) method = 'GET' path = Utils.__pathify Utils.__escape(arguments[:index]), "_shard_stores" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:shard_stores, [ :status, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/shrink.rb000066400000000000000000000037211361161326000317340ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Copy an existing index into a new index with a fewer number of primary shards # # @option arguments [String] :index The name of the source index to shrink (*Required*) # @option arguments [String] :target The name of the target index to shrink into (*Required*) # @option arguments [Hash] :body The configuration for the target index (`settings` and `aliases`) # @option arguments [Boolean] :copy_settings whether or not to copy settings from the source index (defaults to false) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [String] :wait_for_active_shards Set the number of active shards to wait for on the shrunken index before the operation returns. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-shrink-index.html # def shrink(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'target' missing" unless arguments[:target] arguments = arguments.clone source = arguments.delete(:index) target = arguments.delete(:target) method = HTTP_PUT path = Utils.__pathify(source, '_shrink', target) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:shrink, [ :copy_settings, :timeout, :master_timeout, :wait_for_active_shards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/snapshot_index.rb000066400000000000000000000043201361161326000334600ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # When using the shared storage gateway, manually trigger the snapshot operation. # # @deprecated The shared gateway has been deprecated [https://github.com/elasticsearch/elasticsearch/issues/2458] # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string # to perform the operation on all indices # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed) # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore # `missing` ones (options: none, missing) @until 1.0 # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-gateway-snapshot/ # def snapshot_index(arguments={}) method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_gateway/snapshot' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:snapshot_index, [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/split.rb000066400000000000000000000041671361161326000315760ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # The split index API allows you to split an existing index into a new index, # where each original primary shard is split into two or more primary shards in the new index. # # @option arguments [String] :index The name of the source index to split (*Required*) # @option arguments [String] :target The name of the target index to split into (*Required*) # @option arguments [Hash] :body The configuration for the target index (`settings` and `aliases`) # @option arguments [Boolean] :copy_settings whether or not to copy settings from the source index (defaults to false) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [String] :wait_for_active_shards Set the number of active shards to wait for on the shrunken index before the operation returns. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-split-index.html # def split(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'target' missing" unless arguments[:target] arguments = arguments.clone source = arguments.delete(:index) target = arguments.delete(:target) method = Elasticsearch::API::HTTP_PUT path = Utils.__pathify Utils.__escape(source), '_split', Utils.__escape(target) params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:split, [ :copy_settings, :timeout, :master_timeout, :wait_for_active_shards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/stats.rb000066400000000000000000000152461361161326000316010ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return statistical information about one or more indices. # # The response contains comprehensive statistical information about metrics related to index: # how much time did indexing, search and other operations take, how much disk space it takes, # how much memory filter caches or field data require, etc. # # @example Get all available statistics for all indices # # client.indices.stats # # @example Get statistics for a single index # # client.indices.stats index: 'foo' # # @example Get statistics about documents and disk size for multiple indices # # client.indices.stats index: ['foo', 'bar'], docs: true, store: true # # @example Get statistics about filter cache and field data for all fields # # client.indices.stats fielddata: true, filter_cache: true # # @example Get statistics about filter cache and field data for specific fields # # client.indices.stats fielddata: true, filter_cache: true, fields: 'created_at,tags' # # @example Get statistics about filter cache and field data per field for all fields # # client.indices.stats fielddata: true, filter_cache: true, fields: '*' # # @example Get statistics about searches, with segmentation for different search groups # # client.indices.stats search: true, groups: ['groupA', 'groupB'] # # @option arguments [Boolean] :docs Return information about indexed and deleted documents # @option arguments [Boolean] :fielddata Return information about field data # @option arguments [Boolean] :fields A comma-separated list of fields for `fielddata` metric (supports wildcards) # @option arguments [Boolean] :filter_cache Return information about filter cache # @option arguments [Boolean] :flush Return information about flush operations # @option arguments [Boolean] :get Return information about get operations # @option arguments [Boolean] :groups A comma-separated list of search groups for `search` statistics # @option arguments [Boolean] :id_cache Return information about ID cache # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string # to perform the operation on all indices # @option arguments [Boolean] :indexing Return information about indexing operations # @option arguments [String] :level Return stats aggregated at cluster, index or shard level # (Options: cluster, indices, shards) # @option arguments [List] :types A comma-separated list of document types to include in the `indexing` info # @option arguments [Boolean] :merge Return information about merge operations # @option arguments [List] :metric Limit the information returned the specific metrics # (_all, completion, docs, fielddata, filter_cache, flush, get, # id_cache, indexing, merge, percolate, refresh, search, segments, # store, warmer, suggest) # @option arguments [Boolean] :refresh Return information about refresh operations # @option arguments [Boolean] :search Return information about search operations; use the `groups` parameter to # include information for specific search groups # @option arguments [List] :groups A comma-separated list of search groups to include in the `search` statistics # @option arguments [Boolean] :suggest Return information about suggest statistics # @option arguments [Boolean] :store Return information about the size of the index # @option arguments [Boolean] :warmer Return information about warmers # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed) # # @option arguments [Boolean] :include_segment_file_sizes Whether to report the aggregated disk usage of each one of the Lucene index files. Only applies if segment stats are requested. (default: false) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-stats.html # def stats(arguments={}) method = HTTP_GET parts = Utils.__extract_parts arguments, ParamsRegistry.get(:stats_parts) path = Utils.__pathify Utils.__listify(arguments[:index]), '_stats', Utils.__listify(parts) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(:stats_params) params[:fields] = Utils.__listify(params[:fields], :escape => false) if params[:fields] params[:groups] = Utils.__listify(params[:groups], :escape => false) if params[:groups] body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:stats_params, [ :fields, :completion_fields, :fielddata_fields, :groups, :level, :types, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :include_segment_file_sizes ].freeze) # Register this action with its valid parts when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:stats_parts, [ :docs, :fielddata, :filter_cache, :flush, :get, :indexing, :merge, :metric, :refresh, :search, :suggest, :store, :warmer ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/status.rb000066400000000000000000000055201361161326000317600ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return information about one or more indices # # @example Get information about all indices # # client.indices.status # # @example Get information about a specific index # # client.indices.status index: 'foo' # # @example Get information about shard recovery for a specific index # # client.indices.status index: 'foo', recovery: true # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string # to perform the operation on all indices # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that # are open, closed or both. (options: open, closed) # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore # `missing` ones (options: none, missing) @until 1.0 # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # @option arguments [Boolean] :recovery Return information about shard recovery (progress, size, etc) # @option arguments [Boolean] :snapshot Return information about snapshots (when shared gateway is used) # # @see http://elasticsearch.org/guide/reference/api/admin-indices-status/ # def status(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_status' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:status, [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :recovery, :snapshot ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/unfreeze.rb000066400000000000000000000027631361161326000322660ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # In order to keep indices available and queryable for a longer period but at the same time reduce their # hardware requirements they can be transitioned into a frozen state. Once an index is frozen, all of its # transient shard memory (aside from mappings and analyzers) is moved to persistent storage. # # @option arguments [List] :index A comma separated list of indices to unfreeze. (*Required*) # # @note This feature is available in the Platinum distribution of Elasticsearch. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/frozen-indices.html # def unfreeze(arguments = {}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :timeout, :master_timeout, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :wait_for_active_shards] arguments = arguments.clone index = arguments.delete(:index) method = Elasticsearch::API::HTTP_POST path = Elasticsearch::API::Utils.__pathify Elasticsearch::API::Utils.__listify(index), '_unfreeze' params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params perform_request(method, path, params).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/update_aliases.rb000066400000000000000000000036161361161326000334240ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Perform multiple operation on index aliases in a single request. # # Pass the `actions` (add, remove) in the `body` argument. # # @example Add multiple indices to a single alias # # client.indices.update_aliases body: { # actions: [ # { add: { index: 'logs-2013-06', alias: 'year-2013' } }, # { add: { index: 'logs-2013-05', alias: 'year-2013' } } # ] # } # # @example Swap an alias (atomic operation) # # client.indices.update_aliases body: { # actions: [ # { remove: { index: 'logs-2013-06', alias: 'current-month' } }, # { add: { index: 'logs-2013-07', alias: 'current-month' } } # ] # } # # @option arguments [Hash] :body The definition of `actions` to perform (*Required*) # @option arguments [Time] :timeout Request timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html # def update_aliases(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_POST path = "_aliases" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:update_aliases, [ :timeout, :master_timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/upgrade.rb000066400000000000000000000035511361161326000320660ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Upgrade the index or indices to the latest Lucene format. # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :wait_for_completion Specify whether the request should block until the all segments are upgraded (default: false) # @option arguments [Boolean] :only_ancient_segments If true, only ancient (an older Lucene major release) segments will be upgraded # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-upgrade.html # def upgrade(arguments={}) method = HTTP_POST path = "_upgrade" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:upgrade, [ :allow_no_indices, :expand_wildcards, :ignore_unavailable, :wait_for_completion, :only_ancient_segments ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/indices/validate_query.rb000066400000000000000000000115171361161326000334560ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Validate a query # # @example Validate a simple query string query # # client.indices.validate_query index: 'myindex', q: 'title:foo AND body:bar' # # @example Validate an invalid query (with explanation) # # client.indices.validate_query index: 'myindex', q: '[[[ BOOM! ]]]', explain: true # # @example Validate a DSL query (with explanation and rewrite). With rewrite set to true, the # explanation is more detailed showing the actual Lucene query that will # be executed. # # client.indices.validate_query index: 'myindex', # rewrite: true, # explain: true, # body: { # filtered: { # query: { # match: { # title: 'foo' # } # }, # filter: { # range: { # published_at: { # from: '2013-06-01' # } # } # } # } # } # # @option arguments [List] :index A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices # @option arguments [List] :type A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types # @option arguments [Hash] :body The query definition specified with the Query DSL # @option arguments [Boolean] :explain Return detailed information about the error # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given in the query string # @option arguments [Boolean] :lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored # @option arguments [Boolean] :rewrite Provide a more detailed explanation showing the actual Lucene query that will be executed. # @option arguments [Boolean] :all_shards Execute validation on all shards instead of one random shard per index # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/search-validate.html # def validate_query(arguments={}) method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_validate/query' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:validate_query, [ :explain, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :rewrite, :all_shards ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/info.rb000066400000000000000000000010451361161326000277500ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return simple information about the cluster (name, version). # # @see http://elasticsearch.org/guide/ # def info(arguments={}) method = HTTP_GET path = "" params = {} body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:info, [ ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/000077500000000000000000000000001361161326000277615ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/delete_pipeline.rb000066400000000000000000000022141361161326000334340ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions # Delete a speficied pipeline # # @option arguments [String] :id Pipeline ID (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # # @see https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html # def delete_pipeline(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = 'DELETE' path = Utils.__pathify "_ingest/pipeline", Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_pipeline, [ :master_timeout, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/get_pipeline.rb000066400000000000000000000017611361161326000327570ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions # Return a specified pipeline # # @option arguments [String] :id Comma separated list of pipeline ids. Wildcards supported # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # # @see https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html # def get_pipeline(arguments={}) method = 'GET' path = Utils.__pathify "_ingest/pipeline", Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_pipeline, [ :master_timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/params_registry.rb000066400000000000000000000022711361161326000335230ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/processor_grok.rb000066400000000000000000000015271361161326000333540ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions # Extracts structured fields out of a single text field within a document. You choose which field to extract # matched fields from, as well as the grok pattern you expect will match. # # # @see https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html # def processor_grok(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_ingest/processor/grok" params = {} body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:processor_grok, [ ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/put_pipeline.rb000066400000000000000000000024761361161326000330140ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions # Add or update a specified pipeline # # @option arguments [String] :id Pipeline ID (*Required*) # @option arguments [Hash] :body The ingest definition (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # # @see https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html # def put_pipeline(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = 'PUT' path = Utils.__pathify "_ingest/pipeline", Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_pipeline, [ :master_timeout, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ingest/simulate.rb000066400000000000000000000023041361161326000321300ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions # Execute a specific pipeline against the set of documents provided in the body of the request # # @option arguments [String] :id Pipeline ID # @option arguments [Hash] :body The simulate definition (*Required*) # @option arguments [Boolean] :verbose Verbose mode. Display data output for each processor in executed pipeline # # @see https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html # def simulate(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = 'GET' path = Utils.__pathify "_ingest/pipeline", Utils.__escape(arguments[:id]), '_simulate' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:simulate, [ :verbose ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/list_benchmarks.rb000066400000000000000000000014021361161326000321620ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return a list of running benchmarks # # @example # # client.list_benchmarks # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string # to perform the operation on all indices # @option arguments [String] :type The name of the document type # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html # def list_benchmarks(arguments={}) method = HTTP_GET path = "_bench" params = {} body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/mget.rb000066400000000000000000000064071361161326000277600ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return multiple documents from one or more indices in a single request. # # Pass the request definition in the `:body` argument, either as an Array of `docs` specifications, # or `ids`, when the `:index` and document `:type` are specified. # # @example Get multiple documents fully specified in the `docs` definition # # client.mget body: { # docs: [ # { _index: 'myindex', _type: 'mytype', _id: '1' }, # { _index: 'myindex', _type: 'mytype', _id: '2' }, # { _index: 'myindex', _type: 'mytype', _id: '3' } # ] # } # # @example Get multiple documents specified by `ids` while passing `:index` and `:type` # # client.mget index: 'myindex', type: 'mytype', body: { ids: ['1', '2', '3'] } # # @example Get only specific fields from documents # # client.mget index: 'myindex', type: 'mytype', body: { ids: ['1', '2', '3'] }, fields: ['title'] # # @option arguments [String] :index The name of the index # @option arguments [String] :type The type of the document # @option arguments [Hash] :body Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL. (*Required*) # @option arguments [List] :stored_fields A comma-separated list of stored fields to return in the response # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode # @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation # @option arguments [String] :routing Specific routing value # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # # @see http://elasticsearch.org/guide/reference/api/multi-get/ # def mget(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_mget' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:mget, [ :stored_fields, :preference, :realtime, :refresh, :routing, :_source, :_source_excludes, :_source_includes ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/mlt.rb000066400000000000000000000143701361161326000276160ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return documents similar to the specified one. # # Performs a `more_like_this` query with the specified document as the input. # # @example Search for similar documents using the `title` property of document `myindex/mytype/1` # # # First, let's setup a synonym-aware analyzer ("quick" <=> "fast") # client.indices.create index: 'myindex', body: { # settings: { # analysis: { # filter: { # synonyms: { # type: 'synonym', # synonyms: [ "quick,fast" ] # } # }, # analyzer: { # title_synonym: { # type: 'custom', # tokenizer: 'whitespace', # filter: ['lowercase', 'stop', 'snowball', 'synonyms'] # } # } # } # }, # mappings: { # mytype: { # properties: { # title: { # type: 'string', # analyzer: 'title_synonym' # } # } # } # } # } # # # Index three documents # client.index index: 'myindex', type: 'mytype', id: 1, body: { title: 'Quick Brown Fox' } # client.index index: 'myindex', type: 'mytype', id: 2, body: { title: 'Slow Black Dog' } # client.index index: 'myindex', type: 'mytype', id: 3, body: { title: 'Fast White Rabbit' } # client.indices.refresh index: 'myindex' # # client.mlt index: 'myindex', type: 'mytype', id: 1, mlt_fields: 'title', min_doc_freq: 1, min_term_freq: 1 # # => { ... {"title"=>"Fast White Rabbit"}}]}} # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (use `_all` to fetch # the first document matching the ID across all types) (*Required*) # @option arguments [Hash] :body A specific search request definition # @option arguments [Number] :boost_terms The boost factor # @option arguments [Number] :max_doc_freq The word occurrence frequency as count: words with higher occurrence # in the corpus will be ignored # @option arguments [Number] :max_query_terms The maximum query terms to be included in the generated query # @option arguments [Number] :max_word_len The minimum length of the word: longer words will be ignored # @option arguments [Number] :min_doc_freq The word occurrence frequency as count: words with lower occurrence # in the corpus will be ignored # @option arguments [Number] :min_term_freq The term frequency as percent: terms with lower occurence # in the source document will be ignored # @option arguments [Number] :min_word_len The minimum length of the word: shorter words will be ignored # @option arguments [List] :mlt_fields Specific fields to perform the query against # @option arguments [Number] :percent_terms_to_match How many terms have to match in order to consider # the document a match (default: 0.3) # @option arguments [String] :routing Specific routing value # @option arguments [Number] :search_from The offset from which to return results # @option arguments [List] :search_indices A comma-separated list of indices to perform the query against # (default: the index containing the document) # @option arguments [String] :search_query_hint The search query hint # @option arguments [String] :search_scroll A scroll search request definition # @option arguments [Number] :search_size The number of documents to return (default: 10) # @option arguments [String] :search_source A specific search request definition (instead of using the request body) # @option arguments [String] :search_type Specific search type (eg. `dfs_then_fetch`, `count`, etc) # @option arguments [List] :search_types A comma-separated list of types to perform the query against # (default: the same type as the document) # @option arguments [List] :stop_words A list of stop words to be ignored # # @see http://elasticsearch.org/guide/reference/api/more-like-this/ # def mlt(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_mlt' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) [:mlt_fields, :search_indices, :search_types, :stop_words].each do |name| params[name] = Utils.__listify(params[name]) if params[name] end body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:mlt, [ :boost_terms, :max_doc_freq, :max_query_terms, :max_word_len, :min_doc_freq, :min_term_freq, :min_word_len, :mlt_fields, :percent_terms_to_match, :routing, :search_from, :search_indices, :search_query_hint, :search_scroll, :search_size, :search_source, :search_type, :search_types, :stop_words ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/mpercolate.rb000066400000000000000000000053741361161326000311610ustar00rootroot00000000000000module Elasticsearch module API module Actions # Perform multiple percolate operations in a single request, similar to the {#msearch} API # # Pass the percolate definitions as header-body pairs in the `:body` argument, as an Array of Hashes. # # @example Perform two different percolations in a single request # # client.mpercolate \ # body: [ # { percolate: { index: "my-index", type: "my-type" } }, # { doc: { message: "foo bar" } }, # { percolate: { index: "my-other-index", type: "my-other-type", id: "1" } }, # { } # ] # # @option arguments [String] :index The index of the document being count percolated to use as default # @option arguments [String] :type The type of the document being percolated to use as default. # @option arguments [Array] The percolate request definitions (header & body pairs) (*Required*) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are # open, closed or both. (options: open, closed) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-percolate.html # def mpercolate(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_GET path = "_mpercolate" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] case when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : Elasticsearch::API.serializer.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:mpercolate, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_format ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/msearch.rb000066400000000000000000000107711361161326000304450ustar00rootroot00000000000000module Elasticsearch module API module Actions # Perform multiple search operations in a single request. # # Pass the search definitions in the `:body` argument # # @example Perform multiple different searches as `:search` # # client.msearch \ # body: [ # { search: { query: { match_all: {} } } }, # { index: 'myindex', type: 'mytype', search: { query: { query_string: { query: '"Test 1"' } } } }, # { search_type: 'count', search: { aggregations: { published: { terms: { field: 'published' } } } } } # ] # # @example Perform multiple different searches as an array of meta/data pairs # # client.msearch \ # body: [ # { query: { match_all: {} } }, # { index: 'myindex', type: 'mytype' }, # { query: { query_string: { query: '"Test 1"' } } }, # { search_type: 'query_then_fetch' }, # { aggregations: { published: { terms: { field: 'published' } } } } # ] # # @option arguments [List] :index A comma-separated list of index names to use as default # @option arguments [List] :type A comma-separated list of document types to use as default # @option arguments [Hash] :body The request definitions (metadata-search request definition pairs), separated by newlines (*Required*) # @option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch, dfs_query_then_fetch, dfs_query_and_fetch) # @option arguments [Number] :max_concurrent_searches Controls the maximum number of concurrent searches the multi search api will execute # @option arguments [Boolean] :typed_keys Specify whether aggregation and suggester names should be prefixed by their respective types in the response # @option arguments [Number] :pre_filter_shard_size A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint. # @option arguments [Number] :max_concurrent_shard_requests The number of concurrent shard requests each sub search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests # @option arguments [Boolean] :rest_total_hits_as_int This parameter is ignored in this version. It is used in the next major version to control whether the rest response should render the total.hits as an object or a number # # @see https://www.elastic.co/guide/en/elasticsearch/reference/5.x/search-multi-search.html # def msearch(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_msearch' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] case when body.is_a?(Array) && body.any? { |d| d.has_key? :search } payload = body. inject([]) do |sum, item| meta = item data = meta.delete(:search) sum << meta sum << data sum end. map { |item| Elasticsearch::API.serializer.dump(item) } payload << "" unless payload.empty? payload = payload.join("\n") when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : Elasticsearch::API.serializer.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload, {"Content-Type" => "application/x-ndjson"}).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:msearch, [ :search_type, :max_concurrent_searches, :typed_keys, :pre_filter_shard_size, :max_concurrent_shard_requests, :rest_total_hits_as_int ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/msearch_template.rb000066400000000000000000000052461361161326000323410ustar00rootroot00000000000000module Elasticsearch module API module Actions # Execute several search requests using templates (inline, indexed or stored in a file) # # @example Search with an inline script # # client.msearch_template body: [ # { index: 'test' }, # { inline: { query: { match: { title: '{{q}}' } } }, params: { q: 'foo'} } # ] # # @option arguments [List] :index A comma-separated list of index names to use as default # @option arguments [List] :type A comma-separated list of document types to use as default # @option arguments [Hash] :body The request definitions (metadata-search request definition pairs), separated by newlines (*Required*) # @option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch, dfs_query_then_fetch, dfs_query_and_fetch) # @option arguments [Boolean] :typed_keys Specify whether aggregation and suggester names should be prefixed by their respective types in the response # @option arguments [Number] :max_concurrent_searches Controls the maximum number of concurrent searches the multi search api will execute # @option arguments [Boolean] :rest_total_hits_as_int This parameter is ignored in this version. It is used in the next major version to control whether the rest response should render the total.hits as an object or a number # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-search-template.html # def msearch_template(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_msearch/template' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] case when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : Elasticsearch::API.serializer.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload, {"Content-Type" => "application/x-ndjson"}).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:msearch_template, [ :search_type, :typed_keys, :max_concurrent_searches, :rest_total_hits_as_int ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/mtermvectors.rb000066400000000000000000000101311361161326000315430ustar00rootroot00000000000000module Elasticsearch module API module Actions # Returns information and statistics about terms in the fields of multiple documents # in a single request/response. The semantics are similar to the {#mget} API. # # @example Return information about multiple documents in a specific index # # subject.mtermvectors index: 'my-index', type: 'my-type', body: { ids: [1, 2, 3] } # # @option arguments [String] :index The index in which the document resides. # @option arguments [String] :type The type of the document. # @option arguments [Hash] :body Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation. # @option arguments [List] :ids A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body # @option arguments [Boolean] :term_statistics Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [Boolean] :field_statistics Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [List] :fields A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [Boolean] :offsets Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [Boolean] :positions Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [Boolean] :payloads Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [String] :routing Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [String] :parent Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". # @option arguments [Boolean] :realtime Specifies if requests are real-time as opposed to near-real-time (default: true). # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html # # @see #mget # @see #termvector # def mtermvectors(arguments={}) ids = arguments.delete(:ids) method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_mtermvectors' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) if ids body = { :ids => ids } else body = arguments[:body] end perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:mtermvectors, [ :ids, :term_statistics, :field_statistics, :fields, :offsets, :positions, :payloads, :preference, :routing, :parent, :realtime, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/000077500000000000000000000000001361161326000276005ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/hot_threads.rb000066400000000000000000000043351361161326000324360ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions # Returns information about the hottest threads in the cluster or on a specific node as a String. # # # The information is returned as text, and allows you to understand what are currently # the most taxing operations happening in the cluster, for debugging or monitoring purposes. # # @example Return 10 hottest threads # # client.nodes.hot_threads threads: 10 # # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [Time] :interval The interval for the second sampling of threads # @option arguments [Number] :snapshots Number of samples of thread stacktrace (default: 10) # @option arguments [Number] :threads Specify the number of threads to provide information for (default: 3) # @option arguments [Boolean] :ignore_idle_threads Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true) # @option arguments [String] :type The type to sample (default: cpu) (options: cpu, wait, block) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-hot-threads.html # def hot_threads(arguments={}) method = HTTP_GET path = Utils.__pathify '_nodes', Utils.__listify(arguments[:node_id]), 'hot_threads' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:hot_threads, [ :interval, :snapshots, :threads, :ignore_idle_threads, :type, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/info.rb000066400000000000000000000050111361161326000310550ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions # Returns information about nodes in the cluster (cluster settings, JVM version, etc). # # Use the `all` option to return all available settings, or limit the information returned # to a specific type (eg. `http`). # # Use the `node_id` option to limit information to specific node(s). # # @example Return information about JVM # # client.nodes.info jvm: true # # @example Return information about HTTP and network # # client.nodes.info http: true, network: true # # @example Pass a list of metrics # # client.nodes.info metric: ['http', 'network'] # # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [List] :metric A comma-separated list of metrics you wish returned. Leave empty to return all. (options: settings,os,process,jvm,thread_pool,transport,http,plugins,ingest) # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html # def info(arguments={}) arguments = arguments.clone metric = arguments.delete(:metric) method = HTTP_GET if metric parts = metric else parts = Utils.__extract_parts arguments, ParamsRegistry.get(:info_parts) end path = Utils.__pathify '_nodes', Utils.__listify(arguments[:node_id]), Utils.__listify(parts) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(:info_params) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:info_params, [ :flat_settings, :timeout ].freeze) # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:info, [ :flat_settings, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/params_registry.rb000066400000000000000000000022701361161326000333410ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end reload_secure_settings.rb000066400000000000000000000030221361161326000345770ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodesmodule Elasticsearch module API module Nodes module Actions # Re-read the local node's encrypted keystore. Specifically, it will prompt the keystore # decryption and reading across the cluster. # # @example Reload secure settings for all nodes # # client.nodes.reload_secure_settings # # @example Reload secure settings for a list of nodes # # client.nodes.reload_secure_settings(node_id: 'foo,bar') # # @option arguments [List] :node_id A comma-separated list of node IDs to span the reload/reinit call. Should stay empty because reloading usually involves all cluster nodes. # @option arguments [Time] :timeout Explicit operation timeout # # @see https://www.elastic.co/guide/en/elasticsearch/reference/6.x/secure-settings.html#reloadable-secure-settings # def reload_secure_settings(arguments={}) valid_params = [ :timeout ] method = HTTP_POST path = Utils.__pathify '_nodes', Utils.__listify(arguments[:node_id]), 'reload_secure_settings' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:reload_secure_settings, [ :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/shutdown.rb000066400000000000000000000026001361161326000317760ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions # Shutdown one or all nodes # # @example Shut down node named _Bloke_ # # client.nodes.shutdown node_id: 'Bloke' # # @option arguments [List] :node_id A comma-separated list of node IDs or names to perform the operation on; use # `_local` to shutdown the node you're connected to, leave empty to # shutdown all nodes # @option arguments [Time] :delay Set the delay for the operation (default: 1s) # @option arguments [Boolean] :exit Exit the JVM as well (default: true) # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-nodes-shutdown/ # def shutdown(arguments={}) method = HTTP_POST path = Utils.__pathify '_cluster/nodes', Utils.__listify(arguments[:node_id]), '_shutdown' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:shutdown, [ :delay, :exit ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/stats.rb000066400000000000000000000070351361161326000312700ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions # Returns statistical information about nodes in the cluster. # # @example Return statistics about JVM # # client.nodes.stats metric: 'jvm' # # @example Return statistics about field data structures for all fields # # client.nodes.stats metric: 'indices', index_metric: 'fielddata', fields: '*', human: true # # @option arguments [List] :metric Limit the information returned to the specified metrics (options: _all,breaker,fs,http,indices,jvm,os,process,thread_pool,transport,discovery) # @option arguments [List] :index_metric Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. (options: _all,completion,docs,fielddata,query_cache,flush,get,indexing,merge,request_cache,refresh,search,segments,store,warmer,suggest) # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [List] :completion_fields A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) # @option arguments [List] :fielddata_fields A comma-separated list of fields for `fielddata` index metric (supports wildcards) # @option arguments [List] :fields A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) # @option arguments [Boolean] :groups A comma-separated list of search groups for `search` index metric # @option arguments [String] :level Return indices stats aggregated at index, node or shard level (options: indices, node, shards) # @option arguments [List] :types A comma-separated list of document types for the `indexing` index metric # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :include_segment_file_sizes Whether to report the aggregated disk usage of each one of the Lucene index files (only applies if segment stats are requested) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html # def stats(arguments={}) arguments = arguments.clone node_id = arguments.delete(:node_id) path = Utils.__pathify '_nodes', Utils.__listify(node_id), 'stats', Utils.__listify(arguments.delete(:metric)), Utils.__listify(arguments.delete(:index_metric)) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) [:completion_fields, :fielddata_fields, :fields, :groups, :types].each do |key| params[key] = Utils.__listify(params[key]) if params[key] end body = nil perform_request(HTTP_GET, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:stats, [ :completion_fields, :fielddata_fields, :fields, :groups, :level, :types, :timeout, :include_segment_file_sizes ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/nodes/usage.rb000066400000000000000000000024411361161326000312320ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions # The cluster nodes usage API allows to retrieve information on the usage of features for each node. # # @option arguments [List] :metric Limit the information returned to the specified metrics (options: _all,rest_actions) # @option arguments [List] :node_id A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-usage.html # def usage(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_nodes/usage" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:usage, [ :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/params_registry.rb000066400000000000000000000021331361161326000322270ustar00rootroot00000000000000module Elasticsearch module API module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/percolate.rb000066400000000000000000000100111361161326000307640ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return names of queries matching a document. # # Percolator allows you to register queries and then evaluate a document against them: # the IDs of matching queries are returned in the response. # # @deprecated The `_percolate` API has been deprecated in favour of a special field mapping and the # `percolate` query; # see https://www.elastic.co/guide/en/elasticsearch/reference/5.5/breaking_50_percolator.html # # See full example for Elasticsearch 5.x and higher in # # @option arguments [String] :index The index of the document being percolated. (*Required*) # @option arguments [String] :type The type of the document being percolated. (*Required*) # @option arguments [String] :id Fetch the document specified by index/type/id and # use it instead of the passed `doc` # @option arguments [Hash] :body The percolator request definition using the percolate DSL # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [String] :preference Specify the node or shard the operation should be performed on # (default: random) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into # no concrete indices. (This includes `_all` string or when no # indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are # open, closed or both. (options: open, closed) # @option arguments [String] :percolate_index The index to percolate the document into. Defaults to passed `index`. # @option arguments [String] :percolate_format Return an array of matching query IDs instead of objects. # (options: ids) # @option arguments [String] :percolate_type The type to percolate document into. Defaults to passed `type`. # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-percolate.html # def percolate(arguments={}) Utils.__report_unsupported_method :percolate raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_percolate' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:percolate, [ :routing, :preference, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_index, :percolate_type, :percolate_format, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/ping.rb000066400000000000000000000015651361161326000277610ustar00rootroot00000000000000module Elasticsearch module API module Actions # Returns true if the cluster returns a successful HTTP response, false otherwise. # # @example # # client.ping # # @see http://elasticsearch.org/guide/ # def ping(arguments={}) method = HTTP_HEAD path = "" params = {} body = nil begin perform_request(method, path, params, body).status == 200 ? true : false rescue Exception => e if e.class.to_s =~ /NotFound|ConnectionFailed/ || e.message =~ /Not\s*Found|404|ConnectionFailed/i false else raise e end end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:ping, [ ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/put_script.rb000066400000000000000000000040411361161326000312100ustar00rootroot00000000000000module Elasticsearch module API module Actions # Store a script in an internal index (`.scripts`), to be able to reference them # in search definitions (with dynamic scripting disabled) # # @example Storing an Mvel script in Elasticsearch and using it in function score # # client.put_script lang: 'groovy', id: 'my_score', body: { script: 'log(_score * factor)' } # # client.search body: { # query: { # function_score: { # query: { match: { title: 'foo' } }, # functions: [ { script_score: { script_id: 'my_score', params: { factor: 3 } } } ] # } # } # } # # @option arguments [String] :id Script ID (*Required*) # @option arguments [String] :context Script context # @option arguments [Hash] :body The document (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [String] :context Context name to compile script against # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html#_indexed_scripts # def put_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_PUT path = "_scripts/#{arguments.has_key?(:lang) ? "#{arguments.delete(:lang)}/" : ''}#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:put_script, [ :timeout, :master_timeout, :context ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/put_template.rb000066400000000000000000000015361361161326000315250ustar00rootroot00000000000000module Elasticsearch module API module Actions # Store a template for the search definition in Elasticsearch, # to be later used with the `search_template` method # # @option arguments [String] :id Template ID (*Required*) # @option arguments [Hash] :body The document (*Required*) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html # def put_template(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_POST path = "_scripts/#{arguments[:id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/rank_eval.rb000066400000000000000000000040451361161326000307620ustar00rootroot00000000000000module Elasticsearch module API module Actions # The ranking evaluation API allows to evaluate the quality of ranked search results over a set of typical search queries. # Given this set of queries and a list of manually rated documents, the _rank_eval endpoint calculates and # returns typical information retrieval metrics like mean reciprocal rank, precision or discounted cumulative gain. # # @option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices # @option arguments [Hash] :body The ranking evaluation search definition, including search requests, document ratings and ranking metric definition. (*Required*) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-rank-eval.html # def rank_eval(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_GET path = "_rank_eval" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:rank_eval, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/reindex.rb000066400000000000000000000056601361161326000304620ustar00rootroot00000000000000module Elasticsearch module API module Actions # Copy documents from one index to another, potentially changing # its settings, mappings and the documents itself. # # @example Copy documents into a different index # # client.reindex body: { source: { index: 'test1' }, dest: { index: 'test2' } } # # @example Limit the copied documents with a query # # client.reindex body: { # source: { # index: 'test1', # query: { terms: { category: ['one', 'two'] } } # }, # dest: { # index: 'test2' # } # } # # @example Remove a field from reindexed documents # # client.reindex body: { # source: { # index: 'test1' # }, # dest: { # index: 'test3' # }, # script: { # inline: 'ctx._source.remove("category")' # } # } # # @option arguments [Hash] :body The search definition using the Query DSL and the prototype for the index request. (*Required*) # @option arguments [Boolean] :refresh Should the effected indexes be refreshed? # @option arguments [Time] :timeout Time each individual bulk request should wait for shards that are unavailable. # @option arguments [String] :wait_for_active_shards Sets the number of shard copies that must be active before proceeding with the reindex 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) # @option arguments [Boolean] :wait_for_completion Should the request should block until the reindex is complete. # @option arguments [Number] :requests_per_second The throttle to set on this request in sub-requests per second. -1 means no throttle. # @option arguments [Number] :slices The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks. # # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html # def reindex(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = 'POST' path = "_reindex" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:reindex, [ :refresh, :timeout, :wait_for_active_shards, :wait_for_completion, :requests_per_second, :slices ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/reindex_rethrottle.rb000066400000000000000000000022351361161326000327310ustar00rootroot00000000000000module Elasticsearch module API module Actions # The value of requests_per_second can be changed on a running reindex using the _rethrottle # # @option arguments [String] :task_id The task id to rethrottle (*Required*) # @option arguments [Number] :requests_per_second The throttle to set on this request in floating sub-requests per second. -1 means set no throttle. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html # def reindex_rethrottle(arguments={}) raise ArgumentError, "Required argument 'task_id' missing" unless arguments[:task_id] method = Elasticsearch::API::HTTP_POST path = "_reindex/#{arguments[:task_id]}/_rethrottle" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:reindex_rethrottle, [ :requests_per_second ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/remote/000077500000000000000000000000001361161326000277635ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/remote/info.rb000066400000000000000000000007551361161326000312520ustar00rootroot00000000000000module Elasticsearch module API module Remote module Actions # Returns all of the configured remote cluster information # # @see http://www.elastic.co/guide/en/elasticsearch/reference/master/remote-info.html # def info(arguments={}) method = HTTP_GET path = "_remote/info" params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/render_search_template.rb000066400000000000000000000017061361161326000335200ustar00rootroot00000000000000module Elasticsearch module API module Actions # Pre-render search requests before they are executed and fill existing templates with template parameters # # @option arguments [String] :id The id of the stored search template # @option arguments [Hash] :body The search definition template and its params # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html # def render_search_template(arguments={}) method = 'GET' path = "_render/template" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:render_search_template, [ :id ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/scripts_painless_execute.rb000066400000000000000000000014551361161326000341310ustar00rootroot00000000000000module Elasticsearch module API module Actions # The Painless execute API allows an arbitrary script to be executed and a result to be returned. # # @option arguments [Hash] :body The script to execute # # @see https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-execute-api.html # def scripts_painless_execute(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_scripts/painless/_execute" params = {} body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:scripts_painless_execute, [ ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/scroll.rb000066400000000000000000000065431361161326000303230ustar00rootroot00000000000000module Elasticsearch module API module Actions # Efficiently iterate over a large result set. # # When using `from` and `size` to return a large result sets, performance drops as you "paginate" in the set, # and you can't guarantee the consistency when the index is being updated at the same time. # # The "Scroll" API uses a "point in time" snapshot of the index state, which was created via a "Search" API # request specifying the `scroll` parameter. # # @example A basic example # # result = client.search index: 'scrollindex', # scroll: '5m', # body: { query: { match: { title: 'test' } }, sort: '_id' } # # result = client.scroll scroll: '5m', body: { scroll_id: result['_scroll_id'] } # # @example Call the `scroll` API until all the documents are returned # # # Index 1,000 documents # client.indices.delete index: 'test' # 1_000.times do |i| client.index index: 'test', type: 'test', id: i+1, body: {title: "Test #{i+1}"} end # client.indices.refresh index: 'test' # # # Open the "view" of the index by passing the `scroll` parameter # # Sorting by `_doc` makes the operations faster # r = client.search index: 'test', scroll: '1m', body: {sort: ['_doc']} # # # Display the initial results # puts "--- BATCH 0 -------------------------------------------------" # puts r['hits']['hits'].map { |d| d['_source']['title'] }.inspect # # # Call the `scroll` API until empty results are returned # while r = client.scroll(body: { scroll_id: r['_scroll_id'] }, scroll: '5m') and not r['hits']['hits'].empty? do # puts "--- BATCH #{defined?($i) ? $i += 1 : $i = 1} -------------------------------------------------" # puts r['hits']['hits'].map { |d| d['_source']['title'] }.inspect # puts # end # # @option arguments [String] :scroll_id The scroll ID # @option arguments [Hash] :body The scroll ID if not passed by URL or query parameter. # @option arguments [Time] :scroll Specify how long a consistent view of the index should be maintained for scrolled search # @option arguments [String] :scroll_id The scroll ID for scrolled search # @option arguments [Boolean] :rest_total_hits_as_int This parameter is ignored in this version. It is used in the next major version to control whether the rest response should render the total.hits as an object or a number # # @see http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/scan-scroll.html#scan-scroll # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html # def scroll(arguments={}) method = HTTP_GET path = "_search/scroll" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:scroll, [ :scroll, :scroll_id, :rest_total_hits_as_int ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/search.rb000066400000000000000000000254741361161326000302760ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return documents matching a query, as well as aggregations (facets), highlighted snippets, suggestions, etc. # # The search API is used to query one or more indices either using simple # [query string queries](http://www.elasticsearch.org/guide/reference/api/search/uri-request/) # as the `:q` argument , or by passing the # [full request definition](http://www.elasticsearch.org/guide/reference/api/search/request-body/) # in the [Query DSL](http://www.elasticsearch.org/guide/reference/query-dsl/) as the `:body` argument. # # @example Search with a simple query string query # # client.search index: 'myindex', q: 'title:test' # # @example Passing a full request definition in the Elasticsearch's Query DSL as a `Hash` # # client.search index: 'myindex', # body: { # query: { match: { title: 'test' } }, # aggregations: { tags: { terms: { field: 'tags' } } } # } # # @example Paginating results: return 10 documents, beginning from the 10th # # client.search index: 'myindex', # body: { # query: { match: { title: 'test' } }, # from: 10, # size: 10 # } # # @example Passing the search definition as a `String`, built with a JSON builder # # require 'jbuilder' # # json = Jbuilder.encode do |json| # json.query do # json.match do # json.title do # json.query 'test 1' # json.operator 'and' # end # end # end # end # # client.search index: 'myindex', body: json # # @example Wrapping the result in [`Hashie::Mash`](https://github.com/intridea/hashie) for easier access # # response = client.search index: 'myindex', # body: { # query: { match: { title: 'test' } }, # aggregations: { tags: { terms: { field: 'tags' } } } # } # # response = Hashie::Mash.new response # # response.hits.hits.first._source.title # # response.aggregations.tags.terms.to_a.map { |f| "#{f.term} [#{f.count}]" }.join(', ') # # # @option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices # @option arguments [List] :type A comma-separated list of document types to search; leave empty to perform the operation on all types # @option arguments [Hash] :body The search definition using the Query DSL # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given in the query string # @option arguments [Boolean] :explain Specify whether to return detailed information about score computation as part of a hit # @option arguments [List] :stored_fields A comma-separated list of stored fields to return as part of a hit # @option arguments [List] :docvalue_fields A comma-separated list of fields to return as the docvalue representation of a field for each hit # @option arguments [Number] :from Starting offset (default: 0) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :ignore_throttled Whether specified concrete, expanded or aliased indices should be ignored when throttled # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [Time] :scroll Specify how long a consistent view of the index should be maintained for scrolled search # @option arguments [String] :search_type Search operation type (options: query_then_fetch, dfs_query_then_fetch) # @option arguments [Number] :size Number of hits to return (default: 10) # @option arguments [List] :sort A comma-separated list of : pairs # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [Number] :terminate_after The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. # @option arguments [List] :stats Specific 'tag' of the request for logging and statistical purposes # @option arguments [String] :suggest_field Specify which field to use for suggestions # @option arguments [String] :suggest_mode Specify suggest mode (options: missing, popular, always) # @option arguments [Number] :suggest_size How many suggestions to return in response # @option arguments [String] :suggest_text The source text for which the suggestions should be returned # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :track_scores Whether to calculate and return scores even if they are not used for sorting # @option arguments [Boolean] :track_total_hits Indicate if the number of documents that match the query should be tracked # @option arguments [Boolean] :allow_partial_search_results Indicate if an error should be returned if there is a partial search failure or timeout # @option arguments [Boolean] :typed_keys Specify whether aggregation and suggester names should be prefixed by their respective types in the response # @option arguments [Boolean] :version Specify whether to return document version as part of a hit # @option arguments [Boolean] :request_cache Specify if request cache should be used for this request or not, defaults to index level setting # @option arguments [Number] :batched_reduce_size The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large. # @option arguments [Number] :max_concurrent_shard_requests The number of concurrent shard requests this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests # @option arguments [Number] :pre_filter_shard_size A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint. # @option arguments [Boolean] :rest_total_hits_as_int This parameter is ignored in this version. It is used in the next major version to control whether the rest response should render the total.hits as an object or a number # # @return [Hash] # # @see http://www.elasticsearch.org/guide/reference/api/search/ # @see http://www.elasticsearch.org/guide/reference/api/search/request-body/ # def search(arguments={}) arguments[:index] = UNDERSCORE_ALL if ! arguments[:index] && arguments[:type] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), UNDERSCORE_SEARCH ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] params[:fields] = Utils.__listify(params[:fields], :escape => false) if params[:fields] params[:fielddata_fields] = Utils.__listify(params[:fielddata_fields], :escape => false) if params[:fielddata_fields] # FIX: Unescape the `filter_path` parameter due to __listify default behavior. Investigate. params[:filter_path] = defined?(EscapeUtils) ? EscapeUtils.unescape_url(params[:filter_path]) : CGI.unescape(params[:filter_path]) if params[:filter_path] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:search, [ :analyzer, :analyze_wildcard, :default_operator, :df, :explain, :stored_fields, :docvalue_fields, :from, :ignore_unavailable, :ignore_throttled, :allow_no_indices, :expand_wildcards, :lenient, :preference, :q, :routing, :scroll, :search_type, :size, :sort, :_source, :_source_excludes, :_source_includes, :terminate_after, :stats, :suggest_field, :suggest_mode, :suggest_size, :suggest_text, :timeout, :track_scores, :track_total_hits, :allow_partial_search_results, :typed_keys, :version, :request_cache, :batched_reduce_size, :max_concurrent_shard_requests, :pre_filter_shard_size, :rest_total_hits_as_int, :seq_no_primary_term ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/search_exists.rb000066400000000000000000000064461361161326000316730ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return whether documents exists for a particular query # # @option arguments [List] :index A comma-separated list of indices to restrict the results # @option arguments [List] :type A comma-separated list of types to restrict the results # @option arguments [Hash] :body A query to restrict the results specified with the Query DSL (optional) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves # into no concrete indices. # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices # that are open, closed or both. # (options: open, closed, none, all) # @option arguments [Number] :min_score Include only documents with a specific `_score` value in the result # @option arguments [String] :preference Specify the node or shard the operation should be performed on # (default: random) # @option arguments [String] :routing Specific routing value # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be # analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) # (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given # in the query string # @option arguments [Boolean] :lenient Specify whether format-based query failures # (such as providing text to a numeric field) should be ignored # @option arguments [Boolean] :lowercase_expanded_terms Specify whether query terms should be lowercased # # @see http://www.elastic.co/guide/en/elasticsearch/reference/master/search-exists.html # def search_exists(arguments={}) method = 'POST' path = "_search/exists" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:search_exists, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :min_score, :preference, :routing, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :lowercase_expanded_terms ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/search_shards.rb000066400000000000000000000037051361161326000316330ustar00rootroot00000000000000module Elasticsearch module API module Actions # Returns the names of indices and shards on which a search request would be executed # # @option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [String] :routing Specific routing value # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-shards.html # def search_shards(arguments={}) method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_search_shards' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:search_shards, [ :preference, :routing, :local, :ignore_unavailable, :allow_no_indices, :expand_wildcards ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/search_template.rb000066400000000000000000000076341361161326000321670ustar00rootroot00000000000000module Elasticsearch module API module Actions # Configure the search definition witha template in Mustache and parameters # # @example Insert the start and end values for the `range` query # # client.search_template index: 'myindex', # body: { # template: { # query: { # range: { # date: { gte: "{{start}}", lte: "{{end}}" } # } # } # }, # params: { start: "2014-02-01", end: "2014-03-01" } # } # # @option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices # @option arguments [List] :type A comma-separated list of document types to search; leave empty to perform the operation on all types # @option arguments [Hash] :body The search definition template and its params (*Required*) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :ignore_throttled Whether specified concrete, expanded or aliased indices should be ignored when throttled # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [Time] :scroll Specify how long a consistent view of the index should be maintained for scrolled search # @option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch, dfs_query_then_fetch, dfs_query_and_fetch) # @option arguments [Boolean] :explain Specify whether to return detailed information about score computation as part of a hit # @option arguments [Boolean] :profile Specify whether to profile the query execution # @option arguments [Boolean] :typed_keys Specify whether aggregation and suggester names should be prefixed by their respective types in the response # @option arguments [Boolean] :rest_total_hits_as_int This parameter is ignored in this version. It is used in the next major version to control whether the rest response should render the total.hits as an object or a number # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html # def search_template(arguments={}) method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_search/template' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:search_template, [ :ignore_unavailable, :ignore_throttled, :allow_no_indices, :expand_wildcards, :preference, :routing, :scroll, :search_type, :explain, :profile, :typed_keys, :rest_total_hits_as_int ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/000077500000000000000000000000001361161326000303275ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/create.rb000066400000000000000000000042001361161326000321130ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions # Create a new snapshot in the repository # # @example Create a snapshot of the whole cluster in the `my-backups` repository # # client.snapshot.create repository: 'my-backups', snapshot: 'snapshot-1' # # @example Create a snapshot for specific indices in the `my-backups` repository # # client.snapshot.create repository: 'my-backups', # snapshot: 'snapshot-2', # body: { indices: 'foo,bar', ignore_unavailable: true } # # @option arguments [String] :repository A repository name (*Required*) # @option arguments [String] :snapshot A snapshot name (*Required*) # @option arguments [Hash] :body The snapshot definition # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :wait_for_completion Should this request wait until the operation has completed before returning # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def create(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] repository = arguments.delete(:repository) snapshot = arguments.delete(:snapshot) method = HTTP_PUT path = Utils.__pathify( '_snapshot', Utils.__escape(repository), Utils.__escape(snapshot) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:create, [ :master_timeout, :wait_for_completion ].freeze) end end end end create_repository.rb000066400000000000000000000037201361161326000343410ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshotmodule Elasticsearch module API module Snapshot module Actions # Create a repository for storing snapshots # # @example Create a repository at `/tmp/backup` # # client.snapshot.create_repository repository: 'my-backups', # body: { # type: 'fs', # settings: { location: '/tmp/backup', compress: true } # } # # @option arguments [String] :repository A repository name (*Required*) # @option arguments [Hash] :body The repository definition (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :verify Whether to verify the repository after creation # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def create_repository(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] repository = arguments.delete(:repository) method = HTTP_PUT path = Utils.__pathify( '_snapshot', Utils.__escape(repository) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:create_repository, [ :master_timeout, :timeout, :verify ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/delete.rb000066400000000000000000000034341361161326000321220ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions # Delete a snapshot from the repository # # @note Will also abort a currently running snapshot. # # @example Delete the `snapshot-1` snapshot # # client.snapshot.delete repository: 'my-backups', snapshot: 'snapshot-1' # # @option arguments [String] :repository A repository name (*Required*) # @option arguments [String] :snapshot A snapshot name (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def delete(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] repository = arguments.delete(:repository) snapshot = arguments.delete(:snapshot) method = HTTP_DELETE path = Utils.__pathify( '_snapshot', Utils.__escape(repository), Utils.__listify(snapshot) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete, [ :master_timeout ].freeze) end end end end delete_repository.rb000066400000000000000000000031351361161326000343400ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshotmodule Elasticsearch module API module Snapshot module Actions # Delete a specific repository or repositories # # @example Delete the `my-backups` repository # # client.snapshot.delete_repository repository: 'my-backups' # # @option arguments [List] :repository A comma-separated list of repository names (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def delete_repository(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] repository = arguments.delete(:repository) method = HTTP_DELETE path = Utils.__pathify( '_snapshot', Utils.__listify(repository) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:delete_repository, [ :master_timeout, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/get.rb000066400000000000000000000047211361161326000314370ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions # Return information about specific (or all) snapshots # # @example Return information about the `snapshot-2` snapshot # # client.snapshot.get repository: 'my-backup', snapshot: 'snapshot-2' # # @example Return information about multiple snapshots # # client.snapshot.get repository: 'my-backup', snapshot: ['snapshot-2', 'snapshot-3'] # # @example Return information about all snapshots in the repository # # client.snapshot.get repository: 'my-backup', snapshot: '_all' # # @option arguments [String] :repository A repository name (*Required*) # @option arguments [List] :snapshot A comma-separated list of snapshot names (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :ignore_unavailable Whether to ignore unavailable snapshots, defaults to false which means a SnapshotMissingException is thrown # @option arguments [Boolean] :verbose Whether to show verbose snapshot info or only show the basic info found in the repository index blob # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def get(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] repository = arguments.delete(:repository) snapshot = arguments.delete(:snapshot) method = HTTP_GET path = Utils.__pathify( '_snapshot', Utils.__escape(repository), Utils.__listify(snapshot) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get, [ :master_timeout, :ignore_unavailable, :verbose ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/get_repository.rb000066400000000000000000000032161361161326000337340ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions # Get information about snapshot repositories or a specific repository # # @example Get all repositories # # client.snapshot.get_repository # # @example Get a specific repository # # client.snapshot.get_repository repository: 'my-backups' # # @option arguments [List] :repository A comma-separated list of repository names # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node (default: false) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def get_repository(arguments={}) repository = arguments.delete(:repository) method = HTTP_GET path = Utils.__pathify( '_snapshot', Utils.__escape(repository) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get_repository, [ :master_timeout, :local ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/params_registry.rb000066400000000000000000000022731361161326000340730ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/restore.rb000066400000000000000000000045171361161326000323460ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions # Restore the state from a snapshot # # @example Restore from the `snapshot-1` snapshot # # client.snapshot.restore repository: 'my-backups', snapshot: 'snapshot-1' # # @example Restore a specific index under a different name # # client.snapshot.restore repository: 'my-backups', # snapshot: 'snapshot-1', # body: { # rename_pattern: "^(.*)$", # rename_replacement: "restored_$1" # } # # @note You cannot restore into an open index, you have to {Indices::Actions#close} it first # # @option arguments [String] :repository A repository name (*Required*) # @option arguments [String] :snapshot A snapshot name (*Required*) # @option arguments [Hash] :body Details of what to restore # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :wait_for_completion Should this request wait until the operation has completed before returning # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def restore(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] repository = arguments.delete(:repository) snapshot = arguments.delete(:snapshot) method = HTTP_POST path = Utils.__pathify( '_snapshot', Utils.__escape(repository), Utils.__escape(snapshot), '_restore' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:restore, [ :master_timeout, :wait_for_completion ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/status.rb000066400000000000000000000036061361161326000322040ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions # Return information about a running snapshot # # @example Return information about all currently running snapshots # # client.snapshot.status repository: 'my-backups', human: true # # @example Return information about a specific snapshot # # client.snapshot.status repository: 'my-backups', human: true # # @option arguments [String] :repository A repository name # @option arguments [List] :snapshot A comma-separated list of snapshot names # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Boolean] :ignore_unavailable Whether to ignore unavailable snapshots, defaults to false which means a SnapshotMissingException is thrown # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def status(arguments={}) repository = arguments.delete(:repository) snapshot = arguments.delete(:snapshot) method = HTTP_GET path = Utils.__pathify( '_snapshot', Utils.__escape(repository), Utils.__escape(snapshot), '_status') params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:status, [ :master_timeout, :ignore_unavailable ].freeze) end end end end verify_repository.rb000066400000000000000000000024151361161326000344020ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/snapshotmodule Elasticsearch module API module Snapshot module Actions # Explicitly perform the verification of a repository # # @option arguments [String] :repository A repository name (*Required*) # @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html # def verify_repository(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] repository = arguments.delete(:repository) method = HTTP_POST path = Utils.__pathify( '_snapshot', Utils.__escape(repository), '_verify' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:verify_repository, [ :master_timeout, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/suggest.rb000066400000000000000000000040621361161326000305000ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return query terms suggestions based on provided text and configuration. # # Pass the request definition in the `:body` argument. # # @example Return query terms suggestions ("auto-correction") # # client.suggest index: 'myindex', # body: { my_suggest: { text: 'tset', term: { field: 'title' } } } # # => { ... "my_suggest"=>[ {"text"=>"tset", ... "options"=>[{"text"=>"test", "score"=>0.75, "freq"=>5}] }]} # # @option arguments [List] :index A comma-separated list of index names to restrict the operation; # use `_all` or empty string to perform the operation on all indices # @option arguments [Hash] :body The request definition # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore `missing` ones # (options: none, missing) # @option arguments [String] :preference Specify the node or shard the operation should be performed on # (default: random) # @option arguments [String] :routing Specific routing value # @option arguments [String] :source The URL-encoded request definition (instead of using request body) # # @since 0.90 # # @see http://elasticsearch.org/guide/reference/api/search/suggest/ # def suggest(arguments={}) method = HTTP_POST path = Utils.__pathify( Utils.__listify(arguments[:index]), '_suggest' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:suggest, [ :ignore_indices, :preference, :routing, :source ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/tasks/000077500000000000000000000000001361161326000276155ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/tasks/cancel.rb000066400000000000000000000027721361161326000313770ustar00rootroot00000000000000module Elasticsearch module API module Tasks module Actions # Cancel a specific task # # @option arguments [String] :task_id Cancel the task with specified task id (node_id:task_number) # @option arguments [List] :nodes A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [List] :actions A comma-separated list of actions that should be cancelled. Leave empty to cancel all. # @option arguments [String] :parent_task_id Cancel tasks with specified parent task id (node_id:task_number). Set to -1 to cancel all. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html # def cancel(arguments={}) arguments = arguments.clone task_id = arguments.delete(:task_id) method = 'POST' path = Utils.__pathify( '_tasks', Utils.__escape(task_id), '_cancel' ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:cancel, [ :nodes, :actions, :parent_task_id ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/tasks/get.rb000066400000000000000000000022541361161326000307240ustar00rootroot00000000000000module Elasticsearch module API module Tasks module Actions # Return information about a specific task # # @option arguments [String] :task_id Return the task with specified id (node_id:task_number) (*Required*) # @option arguments [Boolean] :wait_for_completion Wait for the matching tasks to complete (default: false) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html # def get(arguments={}) arguments = arguments.clone task_id = arguments.delete(:task_id) method = HTTP_GET path = Utils.__pathify '_tasks', Utils.__escape(task_id) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:get, [ :wait_for_completion, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/tasks/list.rb000066400000000000000000000036051361161326000311210ustar00rootroot00000000000000module Elasticsearch module API module Tasks module Actions # Return the list of tasks # # @option arguments [List] :nodes A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes # @option arguments [List] :actions A comma-separated list of actions that should be returned. Leave empty to return all. # @option arguments [Boolean] :detailed Return detailed task information (default: false) # @option arguments [String] :parent_task_id Return tasks with specified parent task id (node_id:task_number). Set to -1 to return all. # @option arguments [Boolean] :wait_for_completion Wait for the matching tasks to complete (default: false) # @option arguments [String] :group_by Group tasks by nodes or parent/child relationships (options: nodes, parents, none) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html # def list(arguments={}) arguments = arguments.clone task_id = arguments.delete(:task_id) method = 'GET' path = Utils.__pathify( '_tasks', Utils.__escape(task_id) ) params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:list, [ :nodes, :actions, :detailed, :parent_task_id, :wait_for_completion, :group_by, :timeout ].freeze) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/tasks/params_registry.rb000066400000000000000000000022701361161326000333560ustar00rootroot00000000000000module Elasticsearch module API module Tasks module Actions module ParamsRegistry extend self # A Mapping of all the actions to their list of valid params. # # @since 6.2.0 PARAMS = {} # Register an action with its list of valid params. # # @example Register the action. # ParamsRegistry.register(:benchmark, [ :verbose ]) # # @param [ Symbol ] action The action to register. # @param [ Array[Symbol] ] valid_params The list of valid params. # # @since 6.2.0 def register(action, valid_params) PARAMS[action.to_sym] = valid_params end # Get the list of valid params for a given action. # # @example Get the list of valid params. # ParamsRegistry.get(:benchmark) # # @param [ Symbol ] action The action. # # @return [ Array ] The list of valid params for the action. # # @since 6.2.0 def get(action) PARAMS.fetch(action, []) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/termvectors.rb000066400000000000000000000113121361161326000313700ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return information and statistics about terms in the fields of a particular document # # @example Get statistics for an indexed document # # client.indices.create index: 'my_index', # body: { # mappings: { # my_type: { # properties: { # text: { # type: 'string', # term_vector: 'with_positions_offsets_payloads' # } # } # } # } # } # # client.index index: 'my_index', type: 'my_type', id: '1', body: { text: 'Foo Bar Fox' } # # client.termvectors index: 'my_index', type: 'my_type', id: '1' # # => { ..., "term_vectors" => { "text" => { "field_statistics" => { ... }, "terms" => { "bar" => ... } } } # # # @example Get statistics for an arbitrary document # # client.termvector index: 'my_index', type: 'my_type', # body: { # doc: { # text: 'Foo Bar Fox' # } # } # # => { ..., "term_vectors" => { "text" => { "field_statistics" => { ... }, "terms" => { "bar" => ... } } } # # # @option arguments [String] :index The index in which the document resides. (*Required*) # @option arguments [String] :type The type of the document. (*Required*) # @option arguments [String] :id The id of the document, when not specified a doc param should be supplied. # @option arguments [Hash] :body Define parameters and or supply a document to get termvectors for. See documentation. # @option arguments [Boolean] :term_statistics Specifies if total term frequency and document frequency should be returned. # @option arguments [Boolean] :field_statistics Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. # @option arguments [List] :fields A comma-separated list of fields to return. # @option arguments [Boolean] :offsets Specifies if term offsets should be returned. # @option arguments [Boolean] :positions Specifies if term positions should be returned. # @option arguments [Boolean] :payloads Specifies if term payloads should be returned. # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random). # @option arguments [String] :routing Specific routing value. # @option arguments [String] :parent Parent id of documents. # @option arguments [Boolean] :realtime Specifies if request is real-time as opposed to near-real-time (default: true). # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-termvectors.html # def termvectors(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] method = HTTP_GET endpoint = arguments.delete(:endpoint) || '_termvectors' path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), arguments[:id], endpoint params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # @deprecated Use the plural version, {#termvectors} # def termvector(arguments={}) termvectors(arguments.merge :endpoint => '_termvector') end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:termvectors, [ :term_statistics, :field_statistics, :fields, :offsets, :positions, :payloads, :preference, :routing, :parent, :realtime, :version, :version_type ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/update.rb000066400000000000000000000126721361161326000303070ustar00rootroot00000000000000module Elasticsearch module API module Actions # Update a document without sending the whole document in the request ("partial update"). # # Send either a partial document (`doc` ) which will be deeply merged into an existing document, # or a `script`, which will update the document content, in the `:body` argument. # # The partial update operation allows you to limit the amount of data you send over the wire and # reduces the chance of failed updates due to conflict. # # Specify the `:version` and `:retry_on_conflict` arguments to balance convenience and consistency. # # @example Update document _title_ using partial `doc`-ument # # client.update index: 'myindex', type: 'mytype', id: '1', # body: { doc: { title: 'Updated' } } # # @example Add a tag to document `tags` property using a `script` # # client.update index: 'myindex', type: 'mytype', id: '1', # body: { script: { source: 'ctx._source.tags.add(params.tag)', params: { tag: 'x' } } } # # @example Increment a document counter by 1 _or_ initialize it, when the document does not exist # # client.update index: 'myindex', type: 'mytype', id: '666', # body: { script: 'ctx._source.counter += 1', upsert: { counter: 1 } } # # @example Delete a document if it's tagged "to-delete" # # client.update index: 'myindex', type: 'mytype', id: '1', # body: { script: 'ctx._source.tags.contains(params.tag) ? ctx.op = "delete" : ctx.op = "none"', # params: { tag: 'to-delete' } } # # # @option arguments [String] :id Document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (*Required*) # @option arguments [Hash] :body The request definition requires either `script` or partial `doc` (*Required*) # @option arguments [String] :wait_for_active_shards Sets the number of shard copies that must be active before proceeding with the update 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) # @option arguments [List] :fields A comma-separated list of fields to return in the response # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [String] :lang The script language (default: painless) # @option arguments [String] :parent ID of the parent document. Is is only used for routing and when for the upsert request # @option arguments [String] :refresh 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. (options: true, false, wait_for) # @option arguments [Number] :retry_on_conflict Specify how many times should the operation be retried when a conflict occurs (default: 0) # @option arguments [String] :routing Specific routing value # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, force) # @since 0.20 # # @see http://elasticsearch.org/guide/reference/api/update/ # def update(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_update' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] if Array(arguments[:ignore]).include?(404) Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:update, [ :wait_for_active_shards, :fields, :_source, :_source_excludes, :_source_includes, :lang, :parent, :refresh, :retry_on_conflict, :routing, :timeout, :version, :version_type, :if_seq_no, :include_type_name, :if_primary_term ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actions/update_by_query.rb000066400000000000000000000157621361161326000322310ustar00rootroot00000000000000module Elasticsearch module API module Actions # Process every document matching a query, potentially updating it # # @example Update all documents in the index, eg. to pick up new mappings # # client.update_by_query index: 'articles' # # @example Update a property of documents matching a query in the index # # client.update_by_query index: 'article', # body: { # script: { inline: 'ctx._source.views += 1' }, # query: { match: { title: 'foo' } } # } # # @option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices (*Required*) # @option arguments [List] :type A comma-separated list of document types to search; leave empty to perform the operation on all types # @option arguments [Hash] :body The search definition using the Query DSL # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given in the query string # @option arguments [Number] :from Starting offset (default: 0) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :conflicts What to do when the update by query hits version conflicts? (options: abort, proceed) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored # @option arguments [String] :pipeline Ingest pipeline to set on index requests made by this action. (default: none) # @option arguments [String] :preference Specify the node or shard the operation should be performed on (default: random) # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [List] :routing A comma-separated list of specific routing values # @option arguments [Time] :scroll Specify how long a consistent view of the index should be maintained for scrolled search # @option arguments [String] :search_type Search operation type (options: query_then_fetch, dfs_query_then_fetch) # @option arguments [Time] :search_timeout Explicit timeout for each search request. Defaults to no timeout. # @option arguments [Number] :size Number of hits to return (default: 10) # @option arguments [List] :sort A comma-separated list of : pairs # @option arguments [List] :_source True or false to return the _source field or not, or a list of fields to return # @option arguments [List] :_source_excludes A list of fields to exclude from the returned _source field # @option arguments [List] :_source_includes A list of fields to extract and return from the _source field # @option arguments [Number] :terminate_after The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. # @option arguments [List] :stats Specific 'tag' of the request for logging and statistical purposes # @option arguments [Boolean] :version Specify whether to return document version as part of a hit # @option arguments [Boolean] :version_type Should the document increment the version number (internal) on hit or not (reindex) # @option arguments [Boolean] :request_cache Specify if request cache should be used for this request or not, defaults to index level setting # @option arguments [Boolean] :refresh Should the effected indexes be refreshed? # @option arguments [Time] :timeout Time each individual bulk request should wait for shards that are unavailable. # @option arguments [String] :wait_for_active_shards Sets the number of shard copies that must be active before proceeding with the update by query 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) # @option arguments [Number] :scroll_size Size on the scroll request powering the update by query # @option arguments [Boolean] :wait_for_completion Should the request should block until the update by query operation is complete. # @option arguments [Number] :requests_per_second The throttle to set on this request in sub-requests per second. -1 means no throttle. # @option arguments [Number] :slices The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html # def update_by_query(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '/_update_by_query' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:update_by_query, [ :analyzer, :analyze_wildcard, :default_operator, :df, :from, :ignore_unavailable, :allow_no_indices, :conflicts, :expand_wildcards, :lenient, :pipeline, :preference, :q, :routing, :scroll, :search_type, :search_timeout, :size, :sort, :_source, :_source_excludes, :_source_includes, :terminate_after, :stats, :version, :version_type, :request_cache, :refresh, :timeout, :wait_for_active_shards, :scroll_size, :wait_for_completion, :requests_per_second, :slices ].freeze) end end end update_by_query_rethrottle.rb000066400000000000000000000023111361161326000344100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/actionsmodule Elasticsearch module API module Actions # The value of requests_per_second can be changed on a running update by query using the _rethrottle API # # @option arguments [String] :task_id The task id to rethrottle (*Required*) # @option arguments [Number] :requests_per_second The throttle to set on this request in floating sub-requests per second. -1 means set no throttle. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html # def update_by_query_rethrottle(arguments={}) raise ArgumentError, "Required argument 'task_id' missing" unless arguments[:task_id] method = Elasticsearch::API::HTTP_POST path = "_update_by_query/#{arguments[:task_id]}/_rethrottle" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = nil perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:update_by_query_rethrottle, [ :requests_per_second ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/000077500000000000000000000000001361161326000267645ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/cat.rb000066400000000000000000000006451361161326000300650ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions; end # Client for the "cat" namespace (includes the {Cat::Actions} methods) # class CatClient include Common::Client, Common::Client::Base, Cat::Actions end # Proxy method for {CatClient}, available in the receiving object # def cat @cat ||= CatClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/cluster.rb000066400000000000000000000007111361161326000307710ustar00rootroot00000000000000module Elasticsearch module API module Cluster module Actions; end # Client for the "cluster" namespace (includes the {Cluster::Actions} methods) # class ClusterClient include Common::Client, Common::Client::Base, Cluster::Actions end # Proxy method for {ClusterClient}, available in the receiving object # def cluster @cluster ||= ClusterClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/common.rb000066400000000000000000000010431361161326000305770ustar00rootroot00000000000000module Elasticsearch module API module Common module Actions; end module Client # Base client wrapper # module Base attr_reader :client def initialize(client) @client = client end end # Delegates the `perform_request` method to the wrapped client # def perform_request(method, path, params={}, body=nil, headers=nil) client.perform_request method, path, params, body, headers end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/indices.rb000066400000000000000000000007111361161326000307260ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions; end # Client for the "indices" namespace (includes the {Indices::Actions} methods) # class IndicesClient include Common::Client, Common::Client::Base, Indices::Actions end # Proxy method for {IndicesClient}, available in the receiving object # def indices @indices ||= IndicesClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/ingest.rb000066400000000000000000000007001361161326000305770ustar00rootroot00000000000000module Elasticsearch module API module Ingest module Actions; end # Client for the "ingest" namespace (includes the {Ingest::Actions} methods) # class IngestClient include Common::Client, Common::Client::Base, Ingest::Actions end # Proxy method for {IngestClient}, available in the receiving object # def ingest @ingest ||= IngestClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/nodes.rb000066400000000000000000000006671361161326000304320ustar00rootroot00000000000000module Elasticsearch module API module Nodes module Actions; end # Client for the "nodes" namespace (includes the {Nodes::Actions} methods) # class NodesClient include Common::Client, Common::Client::Base, Nodes::Actions end # Proxy method for {NodesClient}, available in the receiving object # def nodes @nodes ||= NodesClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/remote.rb000066400000000000000000000007001361161326000306010ustar00rootroot00000000000000module Elasticsearch module API module Remote module Actions; end # Client for the "remote" namespace (includes the {Remote::Actions} methods) # class RemoteClient include Common::Client, Common::Client::Base, Remote::Actions end # Proxy method for {RemoteClient}, available in the receiving object # def remote @remote ||= RemoteClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/snapshot.rb000066400000000000000000000007221361161326000311510ustar00rootroot00000000000000module Elasticsearch module API module Snapshot module Actions; end # Client for the "snapshot" namespace (includes the {Snapshot::Actions} methods) # class SnapshotClient include Common::Client, Common::Client::Base, Snapshot::Actions end # Proxy method for {SnapshotClient}, available in the receiving object # def snapshot @snapshot ||= SnapshotClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/namespace/tasks.rb000066400000000000000000000006671361161326000304470ustar00rootroot00000000000000module Elasticsearch module API module Tasks module Actions; end # Client for the "tasks" namespace (includes the {Tasks::Actions} methods) # class TasksClient include Common::Client, Common::Client::Base, Tasks::Actions end # Proxy method for {TasksClient}, available in the receiving object # def tasks @tasks ||= TasksClient.new(self) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/utils.rb000066400000000000000000000230461361161326000265220ustar00rootroot00000000000000module Elasticsearch module API # Generic utility methods # module Utils # URL-escape a string # # @example # __escape('foo/bar') # => 'foo%2Fbar' # __escape('bar^bam') # => 'bar%5Ebam' # # @api private def __escape(string) return string if string == '*' defined?(EscapeUtils) ? EscapeUtils.escape_url(string.to_s) : CGI.escape(string.to_s) end # Create a "list" of values from arguments, ignoring nil values and encoding special characters. # # @example Create a list from array # __listify(['A','B']) # => 'A,B' # # @example Create a list from arguments # __listify('A','B') # => 'A,B' # # @example Escape values # __listify('foo','bar^bam') # => 'foo,bar%5Ebam' # # @example Do not escape the values # __listify('foo','bar^bam', escape: false) # => 'foo,bar^bam' # # @api private def __listify(*list) options = list.last.is_a?(Hash) ? list.pop : {} escape = options[:escape] Array(list). flat_map { |e| e.respond_to?(:split) ? e.split(',') : e }. flatten. compact. map { |e| escape == false ? e : __escape(e) }. join(',') end # Create a path (URL part) from arguments, ignoring nil values and empty strings. # # @example Create a path from array # __pathify(['foo', '', nil, 'bar']) # => 'foo/bar' # # @example Create a path from arguments # __pathify('foo', '', nil, 'bar') # => 'foo/bar' # # # @example Encode special characters # __pathify(['foo', 'bar^bam']) # => 'foo/bar%5Ebam' # # @api private def __pathify(*segments) Array(segments).flatten. compact. reject { |s| s.to_s.strip.empty? }. join('/'). squeeze('/') end # Convert an array of payloads into Elasticsearch `header\ndata` format # # Supports various different formats of the payload: Array of Strings, Header/Data pairs, # or the conveniency "combined" format where data is passed along with the header # in a single item. # # Elasticsearch::API::Utils.__bulkify [ # { :index => { :_index => 'myindexA', :_type => 'mytype', :_id => '1', :data => { :title => 'Test' } } }, # { :update => { :_index => 'myindexB', :_type => 'mytype', :_id => '2', :data => { :doc => { :title => 'Update' } } } } # ] # # # => {"index":{"_index":"myindexA","_type":"mytype","_id":"1"}} # # => {"title":"Test"} # # => {"update":{"_index":"myindexB","_type":"mytype","_id":"2"}} # # => {"doc":{"title":"Update"}} # def __bulkify(payload) operations = %w[index create delete update] case # Hashes with `:data` when payload.any? { |d| d.is_a?(Hash) && d.values.first.is_a?(Hash) && operations.include?(d.keys.first.to_s) && (d.values.first[:data] || d.values.first['data']) } payload = payload. inject([]) do |sum, item| operation, meta = item.to_a.first meta = meta.clone data = meta.delete(:data) || meta.delete('data') sum << { operation => meta } sum << data if data sum end. map { |item| Elasticsearch::API.serializer.dump(item) } payload << '' unless payload.empty? # Array of strings when payload.all? { |d| d.is_a? String } payload << '' # Header/Data pairs else payload = payload.map { |item| Elasticsearch::API.serializer.dump(item) } payload << '' end payload = payload.join("\n") end # Validates the argument Hash against common and valid API parameters # # @param arguments [Hash] Hash of arguments to verify and extract, **with symbolized keys** # @param valid_params [Array] An array of symbols with valid keys # # @return [Hash] Return whitelisted Hash # @raise [ArgumentError] If the arguments Hash contains invalid keys # # @example Extract parameters # __validate_and_extract_params( { :foo => 'qux' }, [:foo, :bar] ) # # => { :foo => 'qux' } # # @example Raise an exception for invalid parameters # __validate_and_extract_params( { :foo => 'qux', :bam => 'mux' }, [:foo, :bar] ) # # ArgumentError: "URL parameter 'bam' is not supported" # # @example Skip validating parameters # __validate_and_extract_params( { :foo => 'q', :bam => 'm' }, [:foo, :bar], { skip_parameter_validation: true } ) # # => { :foo => "q", :bam => "m" } # # @example Skip validating parameters when the module setting is set # Elasticsearch::API.settings[:skip_parameter_validation] = true # __validate_and_extract_params( { :foo => 'q', :bam => 'm' }, [:foo, :bar] ) # # => { :foo => "q", :bam => "m" } # # @api private # def __validate_and_extract_params(arguments, params=[], options={}) if options[:skip_parameter_validation] || Elasticsearch::API.settings[:skip_parameter_validation] arguments else __validate_params(arguments, params) __extract_params(arguments, params, options.merge(:escape => false)) end end def __validate_params(arguments, valid_params=[]) arguments.each do |k,v| raise ArgumentError, "URL parameter '#{k}' is not supported" \ unless COMMON_PARAMS.include?(k) || COMMON_QUERY_PARAMS.include?(k) || valid_params.include?(k) end end def __extract_params(arguments, params=[], options={}) result = arguments.select { |k,v| COMMON_QUERY_PARAMS.include?(k) || params.include?(k) } result = Hash[result] unless result.is_a?(Hash) # Normalize Ruby 1.8 and Ruby 1.9 Hash#select behaviour result = Hash[result.map { |k,v| v.is_a?(Array) ? [k, __listify(v, options)] : [k,v] }] # Listify Arrays result end # Extracts the valid parts of the URL from the arguments # # @note Mutates the `arguments` argument, to prevent failures in `__validate_and_extract_params`. # # @param arguments [Hash] Hash of arguments to verify and extract, **with symbolized keys** # @param valid_parts [Array] An array of symbol with valid keys # # @return [Array] Valid parts of the URL as an array of strings # # @example Extract parts # __extract_parts { :foo => true }, [:foo, :bar] # # => [:foo] # # # @api private # def __extract_parts(arguments, valid_parts=[]) parts = Hash[arguments.select { |k,v| valid_parts.include?(k) }] parts = parts.reduce([]) { |sum, item| k, v = item; v.is_a?(TrueClass) ? sum << k.to_s : sum << v } arguments.delete_if { |k,v| valid_parts.include? k } return parts end # Calls the given block, rescuing from `StandardError`. # # Primary use case is the `:ignore` parameter for API calls. # # Returns `false` if exception contains NotFound in its class name or message, # else re-raises the exception. # # @yield [block] A block of code to be executed with exception handling. # # @api private # def __rescue_from_not_found(&block) yield rescue StandardError => e if e.class.to_s =~ /NotFound/ || e.message =~ /Not\s*Found/i false else raise e end end def __report_unsupported_parameters(arguments, params=[]) messages = [] unsupported_params = params.select {|d| d.is_a?(Hash) ? arguments.include?(d.keys.first) : arguments.include?(d) } unsupported_params.each do |param| name = case param when Symbol param when Hash param.keys.first else raise ArgumentError, "The param must be a Symbol or a Hash" end explanation = if param.is_a?(Hash) ". #{param.values.first[:explanation]}." else ". This parameter is not supported in the version you're using: #{Elasticsearch::API::VERSION}, and will be removed in the next release." end message = "[!] You are using unsupported parameter [:#{name}]" if source = caller && caller.last message += " in `#{source}`" end message += explanation messages << message end unless messages.empty? messages << "Suppress this warning by the `-WO` command line flag." if STDERR.tty? Kernel.warn messages.map { |m| "\e[31;1m#{m}\e[0m" }.join("\n") else Kernel.warn messages.join("\n") end end end def __report_unsupported_method(name) message = "[!] You are using unsupported method [#{name}]" if source = caller && caller.last message += " in `#{source}`" end message += ". This method is not supported in the version you're using: #{Elasticsearch::API::VERSION}, and will be removed in the next release. Suppress this warning by the `-WO` command line flag." if STDERR.tty? Kernel.warn "\e[31;1m#{message}\e[0m" else Kernel.warn message end end extend self end end end elasticsearch-ruby-6.8.1/elasticsearch-api/lib/elasticsearch/api/version.rb000066400000000000000000000001021361161326000270330ustar00rootroot00000000000000module Elasticsearch module API VERSION = '6.8.1' end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/000077500000000000000000000000001361161326000216315ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/000077500000000000000000000000001361161326000244435ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/000077500000000000000000000000001361161326000252145ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/000077500000000000000000000000001361161326000266545ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/abort_benchmark_spec.rb000066400000000000000000000004051361161326000333330ustar00rootroot00000000000000require 'spec_helper' describe 'client#abort_benchmark' do let(:expected_args) do [ 'POST', '_bench/abort/foo', {}, nil ] end it 'performs the request' do expect(client_double.abort_benchmark(name: 'foo')) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/benchmark_spec.rb000066400000000000000000000004041361161326000321430ustar00rootroot00000000000000require 'spec_helper' describe 'client#benchmark' do let(:expected_args) do [ 'PUT', '_bench', {}, { name: 'foo' } ] end it 'performs the request' do expect(client_double.benchmark(body: { name: 'foo' })) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/bulk_spec.rb000066400000000000000000000061121361161326000311500ustar00rootroot00000000000000require 'spec_helper' describe 'client#bulk' do let(:expected_args) do [ 'POST', url, params, body, headers ] end let(:headers) { { 'Content-Type' => 'application/x-ndjson' } } let(:params) { {} } let(:url) { '_bulk' } let(:body) { '' } context 'when a list of operations is provided' do let(:body) do <<-PAYLOAD.gsub(/^\s+/, '') {"index":{"_index":"myindexA","_type":"mytype","_id":"1"}} {"title":"Test"} {"update":{"_index":"myindexB","_type":"mytype","_id":"2"}} {"doc":{"title":"Update"}} {"delete":{"_index":"myindexC","_type":"mytypeC","_id":"3"}} {"index":{"_index":"myindexD","_type":"mytype","_id":"1"}} {"data":"MYDATA"} PAYLOAD end it 'performs the request' do expect(client_double.bulk(:body => [ { :index => { :_index => 'myindexA', :_type => 'mytype', :_id => '1', :data => { :title => 'Test' } } }, { :update => { :_index => 'myindexB', :_type => 'mytype', :_id => '2', :data => { :doc => { :title => 'Update' } } } }, { :delete => { :_index => 'myindexC', :_type => 'mytypeC', :_id => '3' } }, { :index => { :_index => 'myindexD', :_type => 'mytype', :_id => '1', :data => { :data => 'MYDATA' } } }, ])).to eq({}) end end context 'when an index is specified' do let(:url) { 'myindex/_bulk' } it 'performs the request' do expect(client_double.bulk(index: 'myindex', body: [])).to eq({}) end end context 'when there are data keys in the head/data payloads' do let(:body) do <<-PAYLOAD.gsub(/^\s+/, '') {"update":{"_index":"myindex","_type":"mytype","_id":"1"}} {"doc":{"data":{"title":"Update"}}} PAYLOAD end it 'performs the request' do expect(client_double.bulk(body:[ { :update => { :_index => 'myindex', :_type => 'mytype', :_id => '1' } }, { :doc => { :data => { :title => 'Update' } } } ])).to eq({}) end end context 'when the payload is a string' do let(:body) do 'foo\nbar' end it 'performs the request' do expect(client_double.bulk(body: 'foo\nbar')).to eq({}) end end context 'when the payload is an array of Strings' do let(:body) do "foo\nbar\n" end it 'performs the request' do expect(client_double.bulk(body: ['foo', 'bar'])).to eq({}) end end context 'when there are parameters' do let(:params) do { refresh: true } end it 'performs the request' do expect(client_double.bulk(refresh: true, body: [])).to eq({}) end end context 'when url characters need to be URL-escaped' do let(:url) do 'foo%5Ebar/_bulk' end it 'performs the request' do expect(client_double.bulk(index: 'foo^bar', body: [])).to eq({}) end end context 'when the type is provided' do let(:url) do 'myindex/mytype/_bulk' end it 'performs the request' do expect(client_double.bulk(index: 'myindex', type: 'mytype', body: [])).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/000077500000000000000000000000001361161326000274235ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/aliases_spec.rb000066400000000000000000000004121361161326000324000ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#aliases' do let(:expected_args) do [ 'GET', '_cat/aliases', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.aliases).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/allocation_spec.rb000066400000000000000000000004231361161326000331060ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#allocation' do let(:expected_args) do [ 'GET', '_cat/allocation', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.allocation).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/count_spec.rb000066400000000000000000000004041361161326000321100ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#count' do let(:expected_args) do [ 'GET', '_cat/count', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.count).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/fielddata_spec.rb000066400000000000000000000011111361161326000326710ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#fielddata' do let(:expected_args) do [ 'GET', '_cat/fielddata', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.fielddata).to eq({}) end context 'when field are specified' do let(:expected_args) do [ 'GET', '_cat/fielddata/foo,bar', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.fielddata(fields: ['foo', 'bar'])).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/health_spec.rb000066400000000000000000000004071361161326000322300ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#health' do let(:expected_args) do [ 'GET', '_cat/health', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.health).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/help_spec.rb000066400000000000000000000003741361161326000317160ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#help' do let(:expected_args) do [ 'GET', '_cat', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.help).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/indices_spec.rb000066400000000000000000000004121361161326000323750ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#indices' do let(:expected_args) do [ 'GET', '_cat/indices', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.indices).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/master_spec.rb000066400000000000000000000004071361161326000322560ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#master' do let(:expected_args) do [ 'GET', '_cat/master', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.master).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/nodeattrs_spec.rb000066400000000000000000000004201361161326000327610ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#nodeattrs' do let(:expected_args) do [ 'GET', '_cat/nodeattrs', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.nodeattrs).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/nodes_spec.rb000066400000000000000000000004041361161326000320700ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#nodes' do let(:expected_args) do [ 'GET', '_cat/nodes', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.nodes).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/pending_tasks_spec.rb000066400000000000000000000004341361161326000336140ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#pending_tasks' do let(:expected_args) do [ 'GET', '_cat/pending_tasks', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.pending_tasks).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/plugins_spec.rb000066400000000000000000000004121361161326000324400ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#plugins' do let(:expected_args) do [ 'GET', '_cat/plugins', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.plugins).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/recovery_spec.rb000066400000000000000000000004151361161326000326200ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#recovery' do let(:expected_args) do [ 'GET', '_cat/recovery', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.recovery).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/repositories_spec.rb000066400000000000000000000004311361161326000335070ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#repositories' do let(:expected_args) do [ 'GET', '_cat/repositories', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.repositories).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/segments_spec.rb000066400000000000000000000004151361161326000326070ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#segments' do let(:expected_args) do [ 'GET', '_cat/segments', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.segments).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/shards_spec.rb000066400000000000000000000004071361161326000322470ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#shards' do let(:expected_args) do [ 'GET', '_cat/shards', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.shards).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/snapshot_spec.rb000066400000000000000000000004471361161326000326260ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#snapshots' do let(:expected_args) do [ 'GET', '_cat/snapshots/foo', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.snapshots(repository: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/tasks_spec.rb000066400000000000000000000004041361161326000321050ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#tasks' do let(:expected_args) do [ 'GET', '_cat/tasks', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.tasks).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/templates_spec.rb000066400000000000000000000004201361161326000327540ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#templates' do let(:expected_args) do [ 'GET', '_cat/templates', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.templates).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cat/thread_pool_spec.rb000066400000000000000000000004261361161326000332640ustar00rootroot00000000000000require 'spec_helper' describe 'client.cat#thread_pool' do let(:expected_args) do [ 'GET', '_cat/thread_pool', {}, nil, nil ] end it 'performs the request' do expect(client_double.cat.thread_pool).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/clear_scroll_spec.rb000066400000000000000000000011401361161326000326530ustar00rootroot00000000000000require 'spec_helper' describe 'client#clear_scroll' do let(:expected_args) do [ 'DELETE', '_search/scroll/abc123', {}, nil ] end it 'performs the request' do expect(client_double.clear_scroll(scroll_id: 'abc123')).to eq({}) end context 'when a list of scroll ids is provided' do let(:expected_args) do [ 'DELETE', '_search/scroll/abc123,def456', {}, nil ] end it 'performs the request' do expect(client_double.clear_scroll(scroll_id: ['abc123', 'def456'])).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cluster/000077500000000000000000000000001361161326000303355ustar00rootroot00000000000000allocation_explain_spec.rb000066400000000000000000000004671361161326000354710ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/clusterrequire 'spec_helper' describe 'client.cluster#allocation_explain' do let(:expected_args) do [ 'GET', '_cluster/allocation/explain', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.allocation_explain).to eq({}) end end get_settings_spec.rb000066400000000000000000000004411361161326000343130ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/clusterrequire 'spec_helper' describe 'client.cluster#get_settings' do let(:expected_args) do [ 'GET', '_cluster/settings', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.get_settings).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cluster/health_spec.rb000066400000000000000000000016021361161326000331400ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#health' do let(:expected_args) do [ 'GET', '_cluster/health', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.health).to eq({}) end context 'when a level is specified' do let(:expected_args) do [ 'GET', '_cluster/health', { level: 'indices' }, nil, nil ] end it 'performs the request' do expect(client_double.cluster.health(level: 'indices')).to eq({}) end end context 'when an index is specified' do let(:expected_args) do [ 'GET', '_cluster/health/foo', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.health(index: 'foo')).to eq({}) end end end pending_tasks_spec.rb000066400000000000000000000004501361161326000344450ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/clusterrequire 'spec_helper' describe 'client.cluster#pending_tasks' do let(:expected_args) do [ 'GET', '_cluster/pending_tasks', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.pending_tasks).to eq({}) end end put_settings_spec.rb000066400000000000000000000004401361161326000343430ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/clusterrequire 'spec_helper' describe 'client.cluster#put_settings' do let(:expected_args) do [ 'PUT', '_cluster/settings', {}, {}, nil ] end it 'performs the request' do expect(client_double.cluster.put_settings).to eq({}) end end remote_info_spec.rb000066400000000000000000000004321361161326000341220ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/clusterrequire 'spec_helper' describe 'client.cluster#remote_info' do let(:expected_args) do [ 'GET', '_remote/info', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.remote_info).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cluster/reroute_spec.rb000066400000000000000000000012431361161326000333610ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#reroute' do let(:expected_args) do [ 'POST', '_cluster/reroute', {}, {}, nil ] end it 'performs the request' do expect(client_double.cluster.reroute).to eq({}) end context 'when a body is specified' do let(:expected_args) do [ 'POST', '_cluster/reroute', {}, { commands: [ move: { index: 'myindex', shard: 0 }] }, nil ] end it 'performs the request' do expect(client_double.cluster.reroute(body: { commands: [ move: { index: 'myindex', shard: 0 }] })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cluster/state_spec.rb000066400000000000000000000011131361161326000330100ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#state' do let(:expected_args) do [ 'GET', '_cluster/state', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.state).to eq({}) end context 'when a metric is specified' do let(:expected_args) do [ 'GET', '_cluster/state/foo,bar', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.state(metric: ['foo', 'bar'])).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/cluster/stats_spec.rb000066400000000000000000000011001361161326000330220ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#stats' do let(:expected_args) do [ 'GET', '_cluster/stats', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.stats).to eq({}) end context 'when a node_id is specified' do let(:expected_args) do [ 'GET', '_cluster/stats/nodes/1', {}, nil, nil ] end it 'performs the request' do expect(client_double.cluster.stats(node_id: 1)).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/count_percolate_spec.rb000066400000000000000000000005271361161326000334050ustar00rootroot00000000000000require 'spec_helper' describe 'client#count_percolate' do let(:expected_args) do [ 'GET', 'foo/bar/_percolate/count', {}, { doc: { foo: 'bar' } } ] end it 'performs the request' do expect(client_double.count_percolate(index: 'foo', type: 'bar', body: { doc: { foo: 'bar' } })).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/count_spec.rb000066400000000000000000000015271361161326000313500ustar00rootroot00000000000000require 'spec_helper' describe 'client#count' do let(:expected_args) do [ 'GET', '_count', {}, nil ] end it 'performs the request' do expect(client_double.count).to eq({}) end context 'when an index and type are specified' do let(:expected_args) do [ 'GET', 'foo,bar/t1,t2/_count', {}, nil ] end it 'performs the request' do expect(client_double.count(index: ['foo','bar'], type: ['t1','t2'])).to eq({}) end end context 'when there is a query provided' do let(:expected_args) do [ 'GET', '_count', {}, { match: { foo: 'bar' } } ] end it 'performs the request' do expect(client_double.count(body: { match: { foo: 'bar' } })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/create_document_spec.rb000066400000000000000000000025651361161326000333640ustar00rootroot00000000000000require 'spec_helper' describe 'client#create_document' do let(:expected_args) do [ 'PUT', 'foo/bar/123', { op_type: 'create' }, { foo: 'bar' } ] end it 'performs the request' do expect(client_double.create(index: 'foo', type: 'bar', id: '123', body: { foo: 'bar'})).to eq({}) end context 'when the request needs to be URL-escaped' do let(:expected_args) do [ 'PUT', 'foo/bar%2Fbam/123', { op_type: 'create' }, { } ] end it 'performs the request' do expect(client_double.create(index: 'foo', type: 'bar/bam', id: '123', body: {})).to eq({}) end end context 'when an id is provided as an integer' do let(:expected_args) do [ 'PUT', 'foo/bar/1', { op_type: 'create' }, { foo: 'bar' } ] end it 'updates the arguments with the `op_type`' do expect(client_double.create(index: 'foo', type: 'bar', id: 1, body: { foo: 'bar' })).to eq({}) end end context 'when an id is not provided' do let(:expected_args) do [ 'POST', 'foo/bar', { }, { foo: 'bar' } ] end it 'updates the arguments with the `op_type`' do expect(client_double.create(index: 'foo', type: 'bar', body: { foo: 'bar' })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/delete_by_query_spec.rb000066400000000000000000000022021361161326000333700ustar00rootroot00000000000000require 'spec_helper' describe 'client#delete_by_query' do let(:expected_args) do [ 'POST', 'foo/_delete_by_query', {}, { term: {} } ] end it 'requires the :index argument' do expect { Class.new { include Elasticsearch::API }.new.delete_by_query(body: {}) }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.delete_by_query(index: 'foo', body: { term: {} })).to eq({}) end context 'when the type argument is provided' do let(:expected_args) do [ 'POST', 'foo/tweet,post/_delete_by_query', {}, { term: {} } ] end it 'performs the request' do expect(client_double.delete_by_query(index: 'foo', type: ['tweet', 'post'], body: { term: {} })).to eq({}) end end context 'when a query is provided' do let(:expected_args) do [ 'POST', 'foo/_delete_by_query', { q: 'foo:bar' }, nil ] end it 'performs the request' do expect(client_double.delete_by_query(index: 'foo', q: 'foo:bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/delete_document_spec.rb000066400000000000000000000041501361161326000333530ustar00rootroot00000000000000require 'spec_helper' describe 'client#delete' do let(:expected_args) do [ 'DELETE', 'foo/bar/1', params, nil ] end let(:params) do {} end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.delete(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :type argument' do expect { client.delete(index: 'foo', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :id argument' do expect { client.delete(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.delete(index: 'foo', type: 'bar', id: '1')).to eq({}) end context 'when url params are provided' do let(:params) do { routing: 'abc123' } end it 'performs the request' do expect(client_double.delete(index: 'foo', type: 'bar', id: '1', routing: 'abc123')).to eq({}) end end context 'when invalid url params are provided' do it 'raises an ArgumentError' do expect { client.delete(index: 'foo', type: 'bar', id: '1', qwertypoiuy: 'asdflkjhg') }.to raise_exception(ArgumentError) end end context 'when the url params need to be escaped' do let(:expected_args) do [ 'DELETE', 'foo%5Ebar/bar%2Fbam/1', params, nil ] end it 'escapes the url params' do expect(client_double.delete(index: 'foo^bar', type: 'bar/bam', id: 1)).to eq({}) end end context 'when the index is not found' do before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'raises the exception' do expect { client.delete(index: 'foo', type: 'bar', id: 'XXX') }.to raise_exception(NotFound) end context 'when the :ignore option is provided' do it 'does not raise the NotFound exception' do expect(client.delete(index: 'foo', type: 'bar', id: 1, ignore: 404)).to eq(false) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/delete_script_spec.rb000066400000000000000000000011071361161326000330400ustar00rootroot00000000000000require 'spec_helper' describe 'client#delete_script' do let(:expected_args) do [ 'DELETE', '_scripts/groovy/foo', {}, nil ] end it 'performs the request' do expect(client_double.delete_script(lang: 'groovy', id: 'foo')).to eq({}) end context 'when lang parameter is not provided' do let(:expected_args) do [ 'DELETE', '_scripts/foo', {}, nil ] end it 'performs the request' do expect(client_double.delete_script(id: 'foo')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/delete_template_spec.rb000066400000000000000000000004331361161326000333500ustar00rootroot00000000000000require 'spec_helper' describe 'client#delete_template' do let(:expected_args) do [ 'DELETE', '_search/template/foo', {}, nil ] end it 'performs the request' do expect(client_double.delete_template(id: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/exists_document_spec.rb000066400000000000000000000043711361161326000334350ustar00rootroot00000000000000require 'spec_helper' describe 'client#exists' do let(:expected_args) do [ 'HEAD', url, params, nil ] end let(:params) do {} end let(:url) do 'foo/bar/1' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.exists(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :id argument' do expect { client.exists(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end context 'when the type parameter is not provided' do let(:url) do 'foo/_all/1' end it 'performs the request' do expect(client_double.exists(index: 'foo', id: '1')).to eq(true) end end it 'is aliased to a predicated method' do expect(client_double.exists?(index: 'foo', type: 'bar', id: '1')).to eq(true) end context 'when URL parameters are provided' do let(:params) do { routing: 'abc123' } end it 'passes the parameters' do expect(client_double.exists(index: 'foo', type: 'bar', id: '1', routing: 'abc123')).to eq(true) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo/bar%2Fbam/1' end it 'URL-escapes the characters' do expect(client_double.exists(index: 'foo', type: 'bar/bam', id: '1')).to eq(true) end end context 'when the response is 404' do before do expect(response_double).to receive(:status).and_return(404) end it 'returns false' do expect(client_double.exists(index: 'foo', type: 'bar', id: '1')).to eq(false) end end context 'when the response is 404 NotFound' do before do expect(response_double).to receive(:status).and_raise(StandardError.new('404 NotFound')) end it 'returns false' do expect(client_double.exists(index: 'foo', type: 'bar', id: '1')).to eq(false) end end context 'when there are other errors' do before do expect(response_double).to receive(:status).and_raise(StandardError) end it 'raises the error' do expect { client_double.exists(index: 'foo', type: 'bar', id: '1') }.to raise_exception(StandardError) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/explain_document_spec.rb000066400000000000000000000032611361161326000335530ustar00rootroot00000000000000require 'spec_helper' describe 'client#explain' do let(:expected_args) do [ 'GET', url, params, body ] end let(:params) do {} end let(:body) do {} end let(:url) do 'foo/bar/1/_explain' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.explain(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :id argument' do expect { client.explain(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end it 'requires the :type argument' do expect { client.explain(index: 'foo', id: '1') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.explain(index: 'foo', type: 'bar', id: 1, body: {})).to eq({}) end context 'when a query is provided' do let(:params) do { q: 'abc123' } end let(:body) do nil end it 'passes the query' do expect(client_double.explain(index: 'foo', type: 'bar', id: '1', q: 'abc123')).to eq({}) end end context 'when a query definition is provided' do let(:body) do { query: { match: {} } } end it 'passes the query definition' do expect(client_double.explain(index: 'foo', type: 'bar', id: '1', body: { query: { match: {} } })).to eq({}) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/1/_explain' end it 'URL-escapes the parts' do expect(client_double.explain(index: 'foo^bar', type: 'bar/bam', id: '1', body: { })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/field_caps_spec.rb000066400000000000000000000004521361161326000323050ustar00rootroot00000000000000require 'spec_helper' describe 'client#field_caps' do let(:expected_args) do [ 'GET', 'foo/_field_caps', { fields: 'bar' }, nil ] end it 'performs the request' do expect(client_double.field_caps(index: 'foo', fields: 'bar')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/field_stats_spec.rb000066400000000000000000000003761361161326000325220ustar00rootroot00000000000000require 'spec_helper' describe 'client#field_stats' do let(:expected_args) do [ 'GET', '_field_stats', { }, nil ] end it 'performs the request' do expect(client_double.field_stats).to eq({}) end end get_document_source_spec.rb000066400000000000000000000031161361161326000341720ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actionsrequire 'spec_helper' describe 'client#get_source' do let(:expected_args) do [ 'GET', url, params, nil ] end let(:params) do { } end let(:url) do 'foo/bar/1/_source' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.get_source(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :id argument' do expect { client.get_source(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end context 'when the type parameter is not provided' do let(:url) do 'foo/_all/1/_source' end it 'performs the request' do expect(client_double.get_source(index: 'foo', id: '1')).to eq({}) end end context 'when URL parameters are provided' do let(:params) do { routing: 'abc123' } end it 'Passes the URL params' do expect(client_double.get_source(index: 'foo', type: 'bar', id: '1', routing: 'abc123')).to eq({}) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/1/_source' end it 'URL-escapes the parts' do expect(client_double.get_source(index: 'foo^bar', type: 'bar/bam', id: '1')).to eq({}) end end context 'when the request raises a NotFound error' do before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'returns false' do expect(client.get_source(index: 'foo', id: '1')).to eq(false) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/get_document_spec.rb000066400000000000000000000041201361161326000326650ustar00rootroot00000000000000require 'spec_helper' describe 'client#get' do let(:expected_args) do [ 'GET', url, params, nil ] end let(:params) do { } end let(:url) do 'foo/bar/1' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.get(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :id argument' do expect { client.get(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end context 'when the type parameter is not provided' do let(:url) do 'foo/_all/1' end it 'performs the request' do expect(client_double.get(index: 'foo', id: '1')).to eq({}) end end context 'when URL parameters are provided' do let(:params) do { routing: 'abc123' } end it 'Passes the URL params' do expect(client_double.get(index: 'foo', type: 'bar', id: '1', routing: 'abc123')).to eq({}) end end context 'when invalid URL parameters are provided' do it 'Passes the URL params' do expect { client.get(index: 'foo', type: 'bar', id: '1', qwert: 'abc123') }.to raise_exception(ArgumentError) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/1' end it 'URL-escapes the parts' do expect(client_double.get(index: 'foo^bar', type: 'bar/bam', id: '1')).to eq({}) end end context 'when the request raises a NotFound error' do before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'raises an exception' do expect { client.get(index: 'foo', id: '1') }.to raise_exception(NotFound) end context 'when the ignore option is provided' do context 'when the response is 404' do let(:params) do { ignore: 404 } end it 'returns false' do expect(client.get(index: 'foo', type: 'bar', id: '1', ignore: 404)).to eq(false) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/get_script_spec.rb000066400000000000000000000012011361161326000323500ustar00rootroot00000000000000require 'spec_helper' describe 'client#get_script' do let(:expected_args) do [ 'GET', url, params, nil ] end let(:params) do { } end context 'when the `lang` parameter is specificed' do let(:url) do '_scripts/groovy/foo' end it 'performs the request' do expect(client_double.get_script(lang: 'groovy', id: 'foo')).to eq({}) end end context 'when the `lang` parameter is not specificed' do let(:url) do '_scripts/foo' end it 'performs the request' do expect(client_double.get_script(id: 'foo')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/get_template_spec.rb000066400000000000000000000016661361161326000326760ustar00rootroot00000000000000require 'spec_helper' describe 'client#get_template' do let(:expected_args) do [ 'GET', url, params, nil ] end let(:params) do { } end let(:client) do Class.new { include Elasticsearch::API }.new end context 'when the `lang` parameter is specified' do let(:url) do '_scripts/foo' end it 'performs the request' do expect(client_double.get_template(id: 'foo')).to eq({}) end end context 'when the request raises a NotFound exception' do before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'raises the exception' do expect { client.get_template(id: 'foo') }.to raise_exception(NotFound) end context 'when the ignore parameter is specified' do it 'returns false' do expect(client.get_template(id: 'foo', ignore: 404)).to eq(false) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/hashie_spec.rb000066400000000000000000000035051361161326000314570ustar00rootroot00000000000000require 'spec_helper' require 'hashie' describe 'Hashie' do let(:json) do <<-JSON { "took": 14, "timed_out": false, "_shards": { "total": 1, "successful": 1, "failed": 0 }, "hits": { "total": 5, "max_score": 0.51104903, "hits": [ { "_index": "myindex", "_type": "mytype", "_id": "1", "_score": 0.51104903, "_source": { "title": "Test 1", "tags": [ "y", "z" ], "published": true, "published_at": "2013-06-22T21:13:00Z", "counter": 1 } } ] }, "facets": { "tags": { "_type": "terms", "missing": 0, "total": 10, "other": 0, "terms": [ { "term": "z", "count": 4 }, { "term": "y", "count": 3 }, { "term": "x", "count": 3 } ] } } } JSON end let(:response) do Hashie::Mash.new MultiJson.load(json) end it 'wraps the response' do expect(response.hits.hits.first._source.title).to eq('Test 1') expect(response.facets.tags.terms.first.term).to eq('z') end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/index_document_spec.rb000066400000000000000000000045171361161326000332270ustar00rootroot00000000000000require 'spec_helper' describe 'client#index' do let(:expected_args) do [ request_type, url, params, body ] end let(:request_type) do 'POST' end let(:params) do { } end let(:url) do 'foo/bar' end let(:body) do { :foo => 'bar' } end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.index(type: 'bar') }.to raise_exception(ArgumentError) end it 'requires the :type argument' do expect { client.index(index: 'foo') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.index(index: 'foo', type: 'bar', body: { foo: 'bar' })).to eq({}) end context 'when a specific id is provided' do let(:request_type) do 'PUT' end let(:url) do 'foo/bar/1' end it 'performs the request' do expect(client_double.index(index: 'foo', type: 'bar', id: '1', body: { foo: 'bar' })).to eq({}) end end context 'when URL parameters are provided' do let(:request_type) do 'POST' end let(:url) do 'foo/bar' end let(:params) do { op_type: 'create' } end let(:body) do nil end it 'passes the URL params' do expect(client_double.index(index: 'foo', type: 'bar', op_type: 'create')).to eq({}) end context 'when a specific id is provided' do let(:request_type) do 'PUT' end let(:url) do 'foo/bar/1' end let(:params) do { op_type: 'create' } end it 'passes the URL params' do expect(client_double.index(index: 'foo', type: 'bar', id: '1', op_type: 'create')).to eq({}) end end end context 'when the request needs to be URL-escaped' do let(:request_type) do 'PUT' end let(:url) do 'foo/bar%2Fbam/123' end let(:body) do nil end it 'URL-escapes the parts' do expect(client_double.index(index: 'foo', type: 'bar/bam', id: '123')).to eq({}) end end context 'when an invalid URL parameter is provided' do it 'raises and ArgumentError' do expect { client.index(index: 'foo', type: 'bar', id: '1', qwerty: 'yuiop') }.to raise_exception(ArgumentError) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/000077500000000000000000000000001361161326000302725ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/analyze_spec.rb000066400000000000000000000014651361161326000333020ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#analyze' do let(:expected_args) do [ 'GET', url, params, body, nil ] end let(:body) do nil end let(:url) do '_analyze' end let(:params) do {} end it 'performs the request' do expect(client_double.indices.analyze).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_analyze' end let(:params) do { index: 'foo' } end it 'performs the request' do expect(client_double.indices.analyze(index: 'foo')).to eq({}) end end context 'when a body is specified' do let(:body) do 'foo' end it 'performs the request' do expect(client_double.indices.analyze(body: 'foo')).to eq({}) end end end clear_cache_spec.rb000066400000000000000000000021441361161326000337640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#clear_cache' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:url) do '_cache/clear' end let(:params) do {} end it 'performs the request' do expect(client_double.indices.clear_cache).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_cache/clear' end let(:params) do { index: 'foo' } end it 'performs the request' do expect(client_double.indices.clear_cache(index: 'foo')).to eq({}) end end context 'when params are specified' do let(:params) do { field_data: true } end it 'performs the request' do expect(client_double.indices.clear_cache(field_data: true)).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_cache/clear' end let(:params) do { index: 'foo^bar' } end it 'performs the request' do expect(client_double.indices.clear_cache(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/close_spec.rb000066400000000000000000000022101361161326000327310ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#close' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:params) do {} end context 'when there is no index specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.close }.to raise_exception(ArgumentError) end end context 'when an index is specified' do let(:url) do 'foo/_close' end it 'performs the request' do expect(client_double.indices.close(index: 'foo')).to eq({}) end end context 'when params are specified' do let(:params) do { timeout: '1s' } end let(:url) do 'foo/_close' end it 'performs the request' do expect(client_double.indices.close(index: 'foo', timeout: '1s')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_close' end it 'performs the request' do expect(client_double.indices.close(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/create_spec.rb000066400000000000000000000021671361161326000331020ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#create' do let(:expected_args) do [ 'PUT', url, params, nil, nil ] end let(:params) do {} end context 'when there is no index specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.create }.to raise_exception(ArgumentError) end end context 'when an index is specified' do let(:url) do 'foo' end it 'performs the request' do expect(client_double.indices.create(index: 'foo')).to eq({}) end end context 'when params are specified' do let(:params) do { timeout: '1s' } end let(:url) do 'foo' end it 'performs the request' do expect(client_double.indices.create(index: 'foo', timeout: '1s')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar' end it 'performs the request' do expect(client_double.indices.create(index: 'foo^bar')).to eq({}) end end end delete_alias_spec.rb000066400000000000000000000023661361161326000341740ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#delete_alias' do let(:expected_args) do [ 'DELETE', url, params, nil, nil ] end let(:params) do {} end context 'when there is no index specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.delete_alias(name: 'foo') }.to raise_exception(ArgumentError) end end context 'when there is no name specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.delete_alias(index: 'foo') }.to raise_exception(ArgumentError) end end context 'when an index and name are specified' do let(:url) do 'foo/_alias/bar' end it 'performs the request' do expect(client_double.indices.delete_alias(index: 'foo', name: 'bar')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_alias/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.delete_alias(index: 'foo^bar', name: 'bar/bam')).to eq({}) end end end delete_mapping_spec.rb000066400000000000000000000027441361161326000345360ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#delete_mapping' do let(:expected_args) do [ 'DELETE', url, params, nil, nil ] end let(:params) do {} end context 'when there is no index specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.delete_mapping(type: 'foo') }.to raise_exception(ArgumentError) end end context 'when there is no type specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.delete_mapping(index: 'foo') }.to raise_exception(ArgumentError) end end context 'when an index and type are specified' do let(:url) do 'foo/bar' end it 'performs the request' do expect(client_double.indices.delete_mapping(index: 'foo', type: 'bar')).to eq({}) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/baz' end it 'performs the request' do expect(client_double.indices.delete_mapping(index: ['foo','bar'], type: 'baz')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.delete_mapping(index: 'foo^bar', type: 'bar/bam')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/delete_spec.rb000066400000000000000000000033101361161326000330700ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#delete' do let(:expected_args) do [ 'DELETE', url, params, nil, nil ] end let(:params) do {} end let(:url) do 'foo' end it 'performs the request' do expect(client_double.indices.delete(index: 'foo')).to eq({}) end context 'when more than one index is specified' do let(:url) do 'foo,bar' end it 'performs the request' do expect(client_double.indices.delete(index: ['foo', 'bar'])).to eq({}) end end context 'when params are specified' do let(:params) do { timeout: '1s' } end it 'performs the request' do expect(client_double.indices.delete(index: 'foo', timeout: '1s')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar' end it 'performs the request' do expect(client_double.indices.delete(index: 'foo^bar')).to eq({}) end end context 'when a NotFound exception is raised by the request' do let(:client) do Class.new { include Elasticsearch::API }.new end before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'raises the exception' do expect { client.indices.delete(index: 'foo') }.to raise_exception(NotFound) end end context 'when the ignore parameter is specified' do let(:client) do Class.new { include Elasticsearch::API }.new end before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'ignores the code' do expect(client.indices.delete(index: 'foo', ignore: 404)).to eq(false) end end end delete_template_spec.rb000066400000000000000000000025141361161326000347110ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#delete_template' do let(:expected_args) do [ 'DELETE', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_template/foo' end it 'performs the request' do expect(client_double.indices.delete_template(name: 'foo')).to eq({}) end context 'when the path needs to be URL-escaped' do let(:url) do '_template/foo%5Ebar' end it 'performs the request' do expect(client_double.indices.delete_template(name: 'foo^bar')).to eq({}) end end context 'when a NotFound exception is raised by the request' do let(:client) do Class.new { include Elasticsearch::API }.new end before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'raises the exception' do expect { client.indices.delete_template(name: 'foo') }.to raise_exception(NotFound) end end context 'when the ignore parameter is specified' do let(:client) do Class.new { include Elasticsearch::API }.new end before do expect(client).to receive(:perform_request).and_raise(NotFound) end it 'ignores the code' do expect(client.indices.delete_template(name: 'foo', ignore: 404)).to eq(false) end end end delete_warmer_spec.rb000066400000000000000000000032141361161326000343710ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#delete_warmer' do let(:expected_args) do [ 'DELETE', url, params, nil, nil ] end let(:params) do {} end context 'when an index is not specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.delete_warmer }.to raise_exception(ArgumentError) end end context 'when an index is specified' do let(:url) do 'foo/_warmer' end it 'performs the request' do expect(client_double.indices.delete_warmer(index: 'foo')).to eq({}) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_warmer' end it 'performs the request' do expect(client_double.indices.delete_warmer(index: ['foo', 'bar'])).to eq({}) end end context 'when a single warmer is specified' do let(:url) do 'foo/_warmer/bar' end it 'performs the request' do expect(client_double.indices.delete_warmer(index: 'foo', name: 'bar')).to eq({}) end end context 'when a multiple warmers are specified' do let(:url) do 'foo/_warmer/bar,baz' end it 'performs the request' do expect(client_double.indices.delete_warmer(index: 'foo', name: ['bar', 'baz'])).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_warmer/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.delete_warmer(index: 'foo^bar', name: 'bar/bam')).to eq({}) end end end exists_alias_spec.rb000066400000000000000000000040151361161326000342420ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#exists_alias' do let(:expected_args) do [ 'HEAD', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_alias/foo' end it 'performs the request' do expect(client_double.indices.exists_alias(name: 'foo')).to eq(true) end it 'aliased to a predicate method' do expect(client_double.indices.exists_alias?(name: 'foo')).to eq(true) end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_alias/bam' end it 'performs the request' do expect(client_double.indices.exists_alias(index: ['foo','bar'], name: 'bam')).to eq(true) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_alias/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.exists_alias(index: 'foo^bar', name: 'bar/bam')).to eq(true) end end context 'when 404 response is received' do let(:response_double) do double('response', status: 404, body: {}, headers: {}) end it 'returns false' do expect(client_double.indices.exists_alias(name: 'foo')).to eq(false) end end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new('404 Not Found')) end end it 'returns false' do expect(client.indices.exists_alias(name: 'foo')).to eq(false) end end context 'when a generic exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new) end end it 'raises the exception' do expect { client.indices.exists_alias(name: 'foo') }.to raise_exception(StandardError) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/exists_spec.rb000066400000000000000000000036411361161326000331540ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#exists' do let(:expected_args) do [ 'HEAD', url, params, nil, nil ] end let(:params) do {} end let(:url) do 'foo' end it 'performs the request' do expect(client_double.indices.exists(index: 'foo')).to eq(true) end it 'aliased to a predicate method' do expect(client_double.indices.exists?(index: 'foo')).to eq(true) end context 'when multiple indices are specified' do let(:url) do 'foo,bar' end it 'performs the request' do expect(client_double.indices.exists(index: ['foo','bar'])).to eq(true) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar' end it 'performs the request' do expect(client_double.indices.exists(index: 'foo^bar')).to eq(true) end end context 'when 404 response is received' do let(:response_double) do double('response', status: 404, body: {}, headers: {}) end it 'returns false' do expect(client_double.indices.exists(index: 'foo')).to eq(false) end end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new('404 Not Found')) end end it 'returns false' do expect(client.indices.exists(index: 'foo')).to eq(false) end end context 'when a generic exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new) end end it 'raises the exception' do expect { client.indices.exists(index: 'foo') }.to raise_exception(StandardError) end end end exists_template_spec.rb000066400000000000000000000032301361161326000347620ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#exists_template' do let(:expected_args) do [ 'HEAD', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_template/foo' end it 'performs the request' do expect(client_double.indices.exists_template(name: 'foo')).to eq(true) end context 'when the path needs to be URL-escaped' do let(:url) do '_template/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.exists_template(name: 'bar/bam')).to eq(true) end end context 'when 404 response is received' do let(:response_double) do double('response', status: 404, body: {}, headers: {}) end it 'returns false' do expect(client_double.indices.exists_template(name: 'foo')).to eq(false) end end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new('404 Not Found')) end end it 'returns false' do expect(client.indices.exists_template(name: 'foo')).to eq(false) end end context 'when a generic exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new) end end it 'raises the exception' do expect { client.indices.exists_template(name: 'foo') }.to raise_exception(StandardError) end end end exists_type_spec.rb000066400000000000000000000041251361161326000341340ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#exists_type' do let(:expected_args) do [ 'HEAD', url, params, nil, nil ] end let(:params) do {} end let(:url) do 'foo/_mapping/bar' end it 'performs the request' do expect(client_double.indices.exists_type(index: 'foo', type: 'bar')).to eq(true) end it 'aliased to a predicate method' do expect(client_double.indices.exists_type?(index: 'foo', type: 'bar')).to eq(true) end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_mapping/bam' end it 'performs the request' do expect(client_double.indices.exists_type(index: ['foo','bar'], type: 'bam')).to eq(true) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_mapping/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.exists_type(index: 'foo^bar', type: 'bar/bam')).to eq(true) end end context 'when 404 response is received' do let(:response_double) do double('response', status: 404, body: {}, headers: {}) end it 'returns false' do expect(client_double.indices.exists_type(index: 'foo', type: 'bar')).to eq(false) end end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new('404 Not Found')) end end it 'returns false' do expect(client.indices.exists_type(index: 'foo', type: 'bar')).to eq(false) end end context 'when a generic exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new) end end it 'raises the exception' do expect { client.indices.exists_type(index: 'foo', type: 'bar') }.to raise_exception(StandardError) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/flush_spec.rb000066400000000000000000000023761361161326000327620ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#flush' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_flush' end it 'performs the request' do expect(client_double.indices.flush).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_flush' end it 'performs the request' do expect(client_double.indices.flush(index: 'foo')).to eq({}) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_flush' end it 'performs the request' do expect(client_double.indices.flush(index: ['foo','bar'])).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_flush' end it 'performs the request' do expect(client_double.indices.flush(index: 'foo^bar')).to eq({}) end end context 'when URL parameters are specified' do let(:url) do 'foo/_flush' end let(:params) do { ignore_unavailable: true } end it 'performs the request' do expect(client_double.indices.flush(index: 'foo', ignore_unavailable: true)).to eq({}) end end end flush_synced_spec.rb000066400000000000000000000031711361161326000342420ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#flush_synced' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:params) do {} end let(:url) do 'foo/_flush/synced' end it 'performs the request' do expect(client_double.indices.flush_synced(index: 'foo')).to eq({}) end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(NotFound) end end it 'raises the exception' do expect { client.indices.flush_synced(index: 'foo') }.to raise_exception(NotFound) end end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(NotFound) end end it 'raises the exception' do expect { client.indices.flush_synced(index: 'foo') }.to raise_exception(NotFound) end end context 'when the ignore parameter is specified' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(StandardError.new('404 Not Found')) end end let(:params) do { ignore: 404 } end it 'does not raise the exception' do expect(client.indices.flush_synced(index: 'foo', ignore: 404)).to eq(false) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/forcemerge_spec.rb000066400000000000000000000004301361161326000337440ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#forcemerge' do let(:expected_args) do [ 'POST', '_forcemerge', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.forcemerge).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/get_alias_spec.rb000066400000000000000000000014611361161326000335630ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#get_alias' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_alias/foo' end it 'performs the request' do expect(client_double.indices.get_alias(name: 'foo')).to eq({}) end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_alias/bam' end it 'performs the request' do expect(client_double.indices.get_alias(index: ['foo','bar'], name: 'bam')).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_alias/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.get_alias(index: 'foo^bar', name: 'bar/bam')).to eq({}) end end end get_aliases_spec.rb000066400000000000000000000017311361161326000340340ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#get_aliases' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_aliases' end it 'performs the request' do expect(client_double.indices.get_aliases).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_aliases' end it 'performs the request' do expect(client_double.indices.get_aliases(index: 'foo')).to eq({}) end end context 'when a specified alias is specified' do let(:url) do 'foo/_aliases/bar' end it 'performs the request' do expect(client_double.indices.get_aliases(index: 'foo', name: 'bar')).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_aliases' end it 'performs the request' do expect(client_double.indices.get_aliases(index: 'foo^bar')).to eq({}) end end end get_field_mapping_spec.rb000066400000000000000000000015071361161326000352120ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#get_field_mapping' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_mapping/field/foo' end it 'performs the request' do expect(client_double.indices.get_field_mapping(field: 'foo')).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_mapping/field/bam' end it 'performs the request' do expect(client_double.indices.get_field_mapping(index: 'foo', field: 'bam')).to eq({}) end end context 'when a type is specified' do let(:url) do 'foo/_mapping/bar/field/bam' end it 'performs the request' do expect(client_double.indices.get_field_mapping(index: 'foo', type: 'bar', field: 'bam')).to eq({}) end end end get_mapping_spec.rb000066400000000000000000000024011361161326000340410ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#get_mapping' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_mapping' end it 'performs the request' do expect(client_double.indices.get_mapping).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_mapping' end it 'performs the request' do expect(client_double.indices.get_mapping(index: 'foo')).to eq({}) end end context 'when an index and type are specified' do let(:url) do 'foo/_mapping/bar' end it 'performs the request' do expect(client_double.indices.get_mapping(index: 'foo', type: 'bar')).to eq({}) end end context 'when multiple indices and types are specified' do let(:url) do 'foo,bar/_mapping/bam,baz' end it 'performs the request' do expect(client_double.indices.get_mapping(index: ['foo', 'bar'], type: ['bam', 'baz'])).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_mapping/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.get_mapping(index: 'foo^bar', type: 'bar/bam')).to eq({}) end end end get_settings_spec.rb000066400000000000000000000017331361161326000342550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#get_settings' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_settings' end it 'performs the request' do expect(client_double.indices.get_settings).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_settings' end it 'performs the request' do expect(client_double.indices.get_settings(index: 'foo')).to eq({}) end end context 'when a name is specified' do let(:url) do 'foo/_settings/foo.bar' end it 'performs the request' do expect(client_double.indices.get_settings(index: 'foo', name: 'foo.bar')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_settings' end it 'performs the request' do expect(client_double.indices.get_settings(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/get_spec.rb000066400000000000000000000014511361161326000324110ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#get' do let(:expected_args) do [ 'GET', url, params, nil, nil ] end let(:params) do {} end let(:url) do 'foo' end it 'performs the request' do expect(client_double.indices.get(index: 'foo')).to eq({}) end context 'when parameters are specified' do let(:params) do { ignore_unavailable: 1 } end it 'performs the request' do expect(client_double.indices.get(index: 'foo', ignore_unavailable: 1)).to eq({}) end end context 'when features are specified' do let(:url) do 'foo/_settings' end it 'includes them in the URL' do expect(client_double.indices.get(index: 'foo', feature: '_settings')).to eq({}) end end end get_template_spec.rb000066400000000000000000000021221361161326000342210ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.indices#get_template' do let(:expected_args) do [ 'GET', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_template/foo' end it 'performs the request' do expect(client_double.indices.get_template(name: 'foo')).to eq({}) end context 'when the path needs to be URL-escaped' do let(:url) do '_template/foo%5Ebar' end it 'performs the request' do expect(client_double.indices.get_template(name: 'foo^bar')).to eq({}) end end context 'when a \'not found\' exception is raised with the ignore parameter' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).with(*expected_args).and_raise(NotFound) end end let(:url) do '_template' end let(:params) do { ignore: 404 } end it 'returns false' do skip expect(client.indices.get_template(id: 'foo', ignore: 404)).to eq(false) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/get_warmer_spec.rb000066400000000000000000000015201361161326000337630ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#get_warmer' do let(:expected_args) do [ 'GET', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_all/_warmer' end it 'performs the request' do expect(client_double.indices.get_warmer(index: '_all')).to eq({}) end context 'when a specified warmer is specified' do let(:url) do 'foo/_warmer/bar' end it 'performs the request' do expect(client_double.indices.get_warmer(index: 'foo', name: 'bar')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_warmer/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.get_warmer(index: 'foo^bar', name: 'bar/bam')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/open_spec.rb000066400000000000000000000014261361161326000325750ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#open' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:params) do {} end let(:url) do 'foo/_open' end it 'performs the request' do expect(client_double.indices.open(index: 'foo')).to eq({}) end context 'when parameters are specified' do let(:params) do { timeout: '1s' } end it 'performs the request' do expect(client_double.indices.open(index: 'foo', timeout: '1s')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_open' end it 'performs the request' do expect(client_double.indices.open(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/optimize_spec.rb000066400000000000000000000020761361161326000334760ustar00rootroot00000000000000require 'spec_helper' describe 'client.indices#optimize' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_optimize' end it 'performs the request' do expect(client_double.indices.optimize).to eq({}) end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_optimize' end it 'performs the request' do expect(client_double.indices.optimize(index: ['foo', 'bar'])).to eq({}) end end context 'when parameters are specified' do let(:params) do { max_num_segments: 1 } end let(:url) do 'foo/_optimize' end it 'performs the request' do expect(client_double.indices.optimize(index: 'foo', max_num_segments: 1)).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do 'foo%5Ebar/_optimize' end it 'performs the request' do expect(client_double.indices.optimize(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/put_alias_spec.rb000066400000000000000000000025611361161326000336160ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#put_alias' do let(:expected_args) do [ 'PUT', url, {}, body, nil ] end let(:url) do 'foo/_alias/bar' end let(:body) do nil end it 'performs the request' do expect(client_double.indices.put_alias(index: 'foo', name: 'bar')).to eq({}) end context 'when there is no name specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_alias(name: 'foo') }.to raise_exception(ArgumentError) end end context 'when a body is specified' do let(:body) do { filter: 'foo' } end it 'performs the request' do expect(client_double.indices.put_alias(index: 'foo', name: 'bar', body: { filter: 'foo' })).to eq({}) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_alias/bam' end it 'performs the request' do expect(client_double.indices.put_alias(index: ['foo','bar'], name: 'bam')).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_alias/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.put_alias(index: 'foo^bar', name: 'bar/bam')).to eq({}) end end end put_mapping_spec.rb000066400000000000000000000033061361161326000340770ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#put_mapping' do let(:expected_args) do [ 'PUT', url, {}, body, nil ] end let(:url) do 'foo/_mapping/bar' end let(:body) do {} end it 'performs the request' do expect(client_double.indices.put_mapping(index: 'foo', type: 'bar', body: {})).to eq({}) end context 'when there is no type specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_mapping(type: 'foo') }.to raise_exception(ArgumentError) end end context 'when there is no body specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_mapping(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end end context 'when a body is specified' do let(:body) do { filter: 'foo' } end it 'performs the request' do expect(client_double.indices.put_mapping(index: 'foo', type: 'bar', body: { filter: 'foo' })).to eq({}) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_mapping/bam' end it 'performs the request' do expect(client_double.indices.put_mapping(index: ['foo','bar'], type: 'bam', body: {})).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_mapping/bar%2Fbam' end it 'performs the request' do expect(client_double.indices.put_mapping(index: 'foo^bar', type: 'bar/bam', body: {})).to eq({}) end end end put_settings_spec.rb000066400000000000000000000025241361161326000343050ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#put_settings' do let(:expected_args) do [ 'PUT', url, params, body, nil ] end let(:url) do '_settings' end let(:body) do {} end let(:params) do {} end it 'performs the request' do expect(client_double.indices.put_settings(body: {})).to eq({}) end context 'when there is no body specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_settings }.to raise_exception(ArgumentError) end end context 'when an index is specified' do let(:url) do 'foo/_settings' end it 'performs the request' do expect(client_double.indices.put_settings(index: 'foo', body: {})).to eq({}) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_settings' end it 'performs the request' do expect(client_double.indices.put_settings(index: ['foo','bar'], body: {})).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_settings' end it 'performs the request' do expect(client_double.indices.put_settings(index: 'foo^bar', body: {})).to eq({}) end end end put_template_spec.rb000066400000000000000000000030721361161326000342570ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#put_template' do let(:expected_args) do [ 'PUT', url, params, body, nil ] end let(:url) do '_template/foo' end let(:body) do { template: 'bar' } end let(:params) do {} end it 'performs the request' do expect(client_double.indices.put_template(name: 'foo', body: { template: 'bar' })).to eq({}) end context 'when there is no name specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_template(body: {}) }.to raise_exception(ArgumentError) end end context 'when there is no body specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_template(name: 'foo') }.to raise_exception(ArgumentError) end end context 'when parameters are specified' do let(:params) do { order: 3 } end let(:url) do '_template/foo' end let(:body) do {} end it 'performs the request' do expect(client_double.indices.put_template(name: 'foo', order: 3, body: {})).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do '_template/foo%5Ebar' end let(:body) do {} end it 'performs the request' do expect(client_double.indices.put_template(name: 'foo^bar', body: {})).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/put_warmer_spec.rb000066400000000000000000000036061361161326000340230ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#put_warmer' do let(:expected_args) do [ 'PUT', url, params, body, nil ] end let(:url) do 'foo/_warmer/bar' end let(:body) do { query: { match_all: {} } } end let(:params) do {} end it 'performs the request' do expect(client_double.indices.put_warmer(index: 'foo', name: 'bar', body: { query: { match_all: {} } })).to eq({}) end context 'when there is no name specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_warmer(body: {}) }.to raise_exception(ArgumentError) end end context 'when there is no body specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.put_warmer(name: 'foo') }.to raise_exception(ArgumentError) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_warmer/xul' end let(:body) do {} end it 'performs the request' do expect(client_double.indices.put_warmer(index: ['foo', 'bar'], name: 'xul', body: {})).to eq({}) end end context 'when a type is specified' do let(:url) do 'foo/bar/_warmer/xul' end let(:body) do {} end it 'performs the request' do expect(client_double.indices.put_warmer(index: 'foo', type: 'bar', name: 'xul', body: {})).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/_warmer/qu+uz' end let(:body) do {} end it 'performs the request' do expect(client_double.indices.put_warmer(index: 'foo^bar', type: 'bar/bam', name: 'qu uz', body: {})).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/recovery_spec.rb000066400000000000000000000004431361161326000334700ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#recovery' do let(:expected_args) do [ 'GET', 'foo/_recovery', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.recovery(index: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/refresh_spec.rb000066400000000000000000000023751361161326000332760ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#refresh' do let(:expected_args) do [ 'POST', url, params, body, nil ] end let(:url) do '_refresh' end let(:body) do nil end let(:params) do {} end it 'performs the request' do expect(client_double.indices.refresh).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_refresh' end it 'performs the request' do expect(client_double.indices.refresh(index: 'foo')).to eq({}) end end context 'when multiple indicies are specified as a list' do let(:url) do 'foo,bar/_refresh' end it 'performs the request' do expect(client_double.indices.refresh(index: ['foo', 'bar'])).to eq({}) end end context 'when multiple indicies are specified as a string' do let(:url) do 'foo,bar/_refresh' end it 'performs the request' do expect(client_double.indices.refresh(index: 'foo,bar')).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_refresh' end it 'performs the request' do expect(client_double.indices.refresh(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/rollover_spec.rb000066400000000000000000000011541361161326000334760ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#rollover' do let(:expected_args) do [ 'POST', url, params, body, nil ] end let(:url) do 'foo/_rollover' end let(:body) do nil end let(:params) do {} end it 'performs the request' do expect(client_double.indices.rollover(alias: 'foo')).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_rollover/bar' end it 'performs the request' do expect(client_double.indices.rollover(alias: 'foo', new_index: 'bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/seal_spec.rb000066400000000000000000000004301361161326000325520ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#seal' do let(:expected_args) do [ 'POST', 'foo/_seal', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.seal(index: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/segments_spec.rb000066400000000000000000000024071361161326000334610ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#segments' do let(:expected_args) do [ 'GET', url, params, body, nil ] end let(:url) do '_segments' end let(:body) do nil end let(:params) do {} end it 'performs the request' do expect(client_double.indices.segments).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_segments' end it 'performs the request' do expect(client_double.indices.segments(index: 'foo')).to eq({}) end end context 'when multiple indicies are specified as a list' do let(:url) do 'foo,bar/_segments' end it 'performs the request' do expect(client_double.indices.segments(index: ['foo', 'bar'])).to eq({}) end end context 'when multiple indicies are specified as a string' do let(:url) do 'foo,bar/_segments' end it 'performs the request' do expect(client_double.indices.segments(index: 'foo,bar')).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_segments' end it 'performs the request' do expect(client_double.indices.segments(index: 'foo^bar')).to eq({}) end end end shard_stores_spec.rb000066400000000000000000000004351361161326000342540ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#shard_stores' do let(:expected_args) do [ 'GET', '_shard_stores', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.shard_stores).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/shrink_spec.rb000066400000000000000000000010221361161326000331220ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#shrink' do let(:expected_args) do [ 'PUT', 'foo/_shrink/bar', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.shrink(index: 'foo', target: 'bar')).to eq({}) end it 'does not mutate the arguments' do arguments = { index: 'foo', target: 'bar' } client_double.indices.shrink(arguments) expect(arguments[:index]).to eq('foo') expect(arguments[:target]).to eq('bar') end end snapshot_index_spec.rb000066400000000000000000000032211361161326000345760ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#snapshot_index' do let(:expected_args) do [ 'POST', url, params, body, nil ] end let(:url) do '_gateway/snapshot' end let(:body) do nil end let(:params) do {} end it 'performs the request' do expect(client_double.indices.snapshot_index).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_gateway/snapshot' end it 'performs the request' do expect(client_double.indices.snapshot_index(index: 'foo')).to eq({}) end end context 'when multiple indicies are specified as a list' do let(:url) do 'foo,bar/_gateway/snapshot' end it 'performs the request' do expect(client_double.indices.snapshot_index(index: ['foo', 'bar'])).to eq({}) end end context 'when multiple indicies are specified as a string' do let(:url) do 'foo,bar/_gateway/snapshot' end it 'performs the request' do expect(client_double.indices.snapshot_index(index: 'foo,bar')).to eq({}) end end context 'when parameters are specified' do let(:params) do { ignore_indices: 'missing' } end let(:url) do 'foo/_gateway/snapshot' end it 'performs the request' do expect(client_double.indices.snapshot_index(index: 'foo', ignore_indices: 'missing')).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_gateway/snapshot' end it 'performs the request' do expect(client_double.indices.snapshot_index(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/split_spec.rb000066400000000000000000000004551361161326000327700ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#split' do let(:expected_args) do [ 'PUT', 'foo/_split/bar', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.split(index: 'foo', target: 'bar')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/status_spec.rb000066400000000000000000000032271361161326000331600ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#status' do let(:expected_args) do [ 'GET', url, params, body, nil ] end let(:url) do '_status' end let(:body) do nil end let(:params) do {} end it 'performs the request' do expect(client_double.indices.status).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_status' end it 'performs the request' do expect(client_double.indices.status(index: 'foo')).to eq({}) end end context 'when multiple indicies are specified as a list' do let(:url) do 'foo,bar/_status' end it 'performs the request' do expect(client_double.indices.status(index: ['foo', 'bar'])).to eq({}) end end context 'when multiple indicies are specified as a string' do let(:url) do 'foo,bar/_status' end it 'performs the request' do expect(client_double.indices.status(index: 'foo,bar')).to eq({}) end end context 'when parameters are specified' do let(:params) do { recovery: true } end let(:url) do 'foo/_status' end it 'performs the request' do expect(client_double.indices.status(index: 'foo', recovery: true)).to eq({}) end end context 'when a \'not found\' exception is raised' do let(:client) do Class.new { include Elasticsearch::API }.new.tap do |_client| expect(_client).to receive(:perform_request).and_raise(NotFound) end end it 'does not raise the exception' do expect(client.indices.status(index: 'foo', ignore: 404)).to eq(false) end end end update_aliases_spec.rb000066400000000000000000000016051361161326000345370ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#update_aliases' do let(:expected_args) do [ 'POST', '_aliases', params, body, nil ] end let(:body) do { actions: [] } end let(:params) do {} end it 'performs the request' do expect(client_double.indices.update_aliases(body: { actions: [] })).to eq({}) end context 'when a body is not specified' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an exception' do expect { client.indices.update_aliases }.to raise_exception(ArgumentError) end end context 'when parameters are specified' do let(:params) do { timeout: '1s' } end it 'performs the request' do expect(client_double.indices.update_aliases(timeout: '1s', body: { actions: [] })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indices/upgrade_spec.rb000066400000000000000000000004171361161326000332620ustar00rootroot00000000000000require 'spec_helper' describe 'client.cluster#upgrade' do let(:expected_args) do [ 'POST', '_upgrade', {}, nil, nil ] end it 'performs the request' do expect(client_double.indices.upgrade).to eq({}) end end validate_query_spec.rb000066400000000000000000000041041361161326000345670ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/indicesrequire 'spec_helper' describe 'client.cluster#validate_query' do let(:expected_args) do [ 'GET', url, params, body, nil ] end let(:url) do '_validate/query' end let(:body) do nil end let(:params) do {} end it 'performs the request' do expect(client_double.indices.validate_query).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_validate/query' end it 'performs the request' do expect(client_double.indices.validate_query(index: 'foo')).to eq({}) end end context 'when a type and index are specified' do let(:url) do 'foo/bar/_validate/query' end it 'performs the request' do expect(client_double.indices.validate_query(index: 'foo', type: 'bar')).to eq({}) end end context 'when multiple indicies are specified as a list' do let(:url) do 'foo,bar/_validate/query' end it 'performs the request' do expect(client_double.indices.validate_query(index: ['foo', 'bar'])).to eq({}) end end context 'when multiple indicies are specified as a string' do let(:url) do 'foo,bar/_validate/query' end it 'performs the request' do expect(client_double.indices.validate_query(index: 'foo,bar')).to eq({}) end end context 'when parameters are specified' do let(:params) do { explain: true, q: 'foo' } end let(:url) do '_validate/query' end it 'performs the request' do expect(client_double.indices.validate_query(explain: true, q: 'foo')).to eq({}) end end context 'when a body is specified' do let(:body) do { filtered: {} } end it 'performs the request' do expect(client_double.indices.validate_query(body: { filtered: {} })).to eq({}) end end context 'when the path needs to be URL-escaped' do let(:url) do 'foo%5Ebar/_validate/query' end it 'performs the request' do expect(client_double.indices.validate_query(index: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/info_spec.rb000066400000000000000000000003441361161326000311470ustar00rootroot00000000000000require 'spec_helper' describe 'client#info' do let(:expected_args) do [ 'GET', '', { }, nil ] end it 'performs the request' do expect(client_double.info).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/ingest/000077500000000000000000000000001361161326000301455ustar00rootroot00000000000000delete_pipeline_spec.rb000066400000000000000000000014151361161326000345550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/ingestrequire 'spec_helper' describe 'client.ingest#delete_pipeline' do let(:expected_args) do [ 'DELETE', url, {}, nil, nil ] end let(:url) do '_ingest/pipeline/foo' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :id argument' do expect { client.ingest.delete_pipeline }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.ingest.delete_pipeline(id: 'foo')).to eq({}) end context 'when the path must be URL-escaped' do let(:url) do '_ingest/pipeline/foo%5Ebar' end it 'performs the request' do expect(client_double.ingest.delete_pipeline(id: 'foo^bar')).to eq({}) end end end get_pipeline_spec.rb000066400000000000000000000010631361161326000340710ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/ingestrequire 'spec_helper' describe 'client.ingest#get_pipeline' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_ingest/pipeline/foo' end it 'performs the request' do expect(client_double.ingest.get_pipeline(id: 'foo')).to eq({}) end context 'when the path must be URL-escaped' do let(:url) do '_ingest/pipeline/foo%5Ebar' end it 'performs the request' do expect(client_double.ingest.get_pipeline(id: 'foo^bar')).to eq({}) end end end put_pipeline_spec.rb000066400000000000000000000014211361161326000341200ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/ingestrequire 'spec_helper' describe 'client.ingest#put_pipeline' do let(:expected_args) do [ 'PUT', url, {}, {}, nil ] end let(:url) do '_ingest/pipeline/foo' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :id argument' do expect { client.ingest.put_pipeline }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.ingest.put_pipeline(id: 'foo', body: {})).to eq({}) end context 'when the path must be URL-escaped' do let(:url) do '_ingest/pipeline/foo%5Ebar' end it 'performs the request' do expect(client_double.ingest.put_pipeline(id: 'foo^bar', body: {})).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/ingest/simulate_spec.rb000066400000000000000000000010621361161326000333260ustar00rootroot00000000000000require 'spec_helper' describe 'client.ingest#simulate' do let(:expected_args) do [ 'GET', url, {}, {}, nil ] end let(:url) do '_ingest/pipeline/_simulate' end it 'performs the request' do expect(client_double.ingest.simulate(body: {})).to eq({}) end context 'when a pipeline id is provided' do let(:url) do '_ingest/pipeline/foo/_simulate' end it 'performs the request' do expect(client_double.ingest.simulate(id: 'foo', body: {})).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/json_builders_spec.rb000066400000000000000000000020631361161326000330560ustar00rootroot00000000000000require 'spec_helper' describe 'JSON builders' do context 'JBuilder' do let(:expected_args) do [ 'GET', '_search', {}, body ] end let(:json) do Jbuilder.encode do |json| json.query do json.match do json.title do json.query 'test' end end end end end let(:body) do json end it 'properly builds the json' do expect(client_double.search(body: json)).to eq({}) end end context 'Jsonify' do let(:expected_args) do [ 'GET', '_search', {}, body ] end let(:json) do Jsonify::Builder.compile do |json| json.query do json.match do json.title do json.query 'test' end end end end end let(:body) do json end it 'properly builds the json' do expect(client_double.search(body: json)).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/list_benchmarks_spec.rb000066400000000000000000000004001361161326000333550ustar00rootroot00000000000000require 'spec_helper' describe 'client#list_benchmarks' do let(:expected_args) do [ 'GET', '_bench', { }, nil ] end it 'performs the request' do expect(client_double.list_benchmarks).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/mget_spec.rb000066400000000000000000000026531361161326000311550ustar00rootroot00000000000000require 'spec_helper' describe 'client#mget' do let(:expected_args) do [ 'GET', url, params, body ] end let(:body) do { docs: [] } end let(:url) do '_mget' end let(:params) do {} end it 'performs the request' do expect(client_double.mget(body: { :docs => [] })).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_mget' end it 'performs the request' do expect(client_double.mget(index: 'foo', body: { :docs => [] })).to eq({}) end end context 'when a type is specified' do let(:url) do 'foo/bar/_mget' end let(:body) do { ids: [ '1', '2' ]} end it 'performs the request' do expect(client_double.mget(index: 'foo', type: 'bar', body: { :ids => [ '1', '2'] })).to eq({}) end end context 'when url parameters are provided' do let(:params) do { refresh: true } end let(:body) do {} end it 'performs the request' do expect(client_double.mget(body: {}, refresh: true)).to eq({}) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/_mget' end let(:body) do { ids: [ '1', '2' ]} end it 'performs the request' do expect(client_double.mget(index: 'foo^bar', type: 'bar/bam', body: { :ids => [ '1', '2'] })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/mlt_spec.rb000066400000000000000000000143701361161326000310140ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return documents similar to the specified one. # # Performs a `more_like_this` query with the specified document as the input. # # @example Search for similar documents using the `title` property of document `myindex/mytype/1` # # # First, let's setup a synonym-aware analyzer ("quick" <=> "fast") # client.indices.create index: 'myindex', body: { # settings: { # analysis: { # filter: { # synonyms: { # type: 'synonym', # synonyms: [ "quick,fast" ] # } # }, # analyzer: { # title_synonym: { # type: 'custom', # tokenizer: 'whitespace', # filter: ['lowercase', 'stop', 'snowball', 'synonyms'] # } # } # } # }, # mappings: { # mytype: { # properties: { # title: { # type: 'string', # analyzer: 'title_synonym' # } # } # } # } # } # # # Index three documents # client.index index: 'myindex', type: 'mytype', id: 1, body: { title: 'Quick Brown Fox' } # client.index index: 'myindex', type: 'mytype', id: 2, body: { title: 'Slow Black Dog' } # client.index index: 'myindex', type: 'mytype', id: 3, body: { title: 'Fast White Rabbit' } # client.indices.refresh index: 'myindex' # # client.mlt index: 'myindex', type: 'mytype', id: 1, mlt_fields: 'title', min_doc_freq: 1, min_term_freq: 1 # # => { ... {"title"=>"Fast White Rabbit"}}]}} # # @option arguments [String] :id The document ID (*Required*) # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (use `_all` to fetch # the first document matching the ID across all types) (*Required*) # @option arguments [Hash] :body A specific search request definition # @option arguments [Number] :boost_terms The boost factor # @option arguments [Number] :max_doc_freq The word occurrence frequency as count: words with higher occurrence # in the corpus will be ignored # @option arguments [Number] :max_query_terms The maximum query terms to be included in the generated query # @option arguments [Number] :max_word_len The minimum length of the word: longer words will be ignored # @option arguments [Number] :min_doc_freq The word occurrence frequency as count: words with lower occurrence # in the corpus will be ignored # @option arguments [Number] :min_term_freq The term frequency as percent: terms with lower occurence # in the source document will be ignored # @option arguments [Number] :min_word_len The minimum length of the word: shorter words will be ignored # @option arguments [List] :mlt_fields Specific fields to perform the query against # @option arguments [Number] :percent_terms_to_match How many terms have to match in order to consider # the document a match (default: 0.3) # @option arguments [String] :routing Specific routing value # @option arguments [Number] :search_from The offset from which to return results # @option arguments [List] :search_indices A comma-separated list of indices to perform the query against # (default: the index containing the document) # @option arguments [String] :search_query_hint The search query hint # @option arguments [String] :search_scroll A scroll search request definition # @option arguments [Number] :search_size The number of documents to return (default: 10) # @option arguments [String] :search_source A specific search request definition (instead of using the request body) # @option arguments [String] :search_type Specific search type (eg. `dfs_then_fetch`, `count`, etc) # @option arguments [List] :search_types A comma-separated list of types to perform the query against # (default: the same type as the document) # @option arguments [List] :stop_words A list of stop words to be ignored # # @see http://elasticsearch.org/guide/reference/api/more-like-this/ # def mlt(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_mlt' params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) [:mlt_fields, :search_indices, :search_types, :stop_words].each do |name| params[name] = Utils.__listify(params[name]) if params[name] end body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:mlt, [ :boost_terms, :max_doc_freq, :max_query_terms, :max_word_len, :min_doc_freq, :min_term_freq, :min_word_len, :mlt_fields, :percent_terms_to_match, :routing, :search_from, :search_indices, :search_query_hint, :search_scroll, :search_size, :search_source, :search_type, :search_types, :stop_words ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/mpercolate_spec.rb000066400000000000000000000021231361161326000323440ustar00rootroot00000000000000require 'spec_helper' describe 'client#mpercolate' do let(:expected_args) do [ 'GET', '_mpercolate', params, body ] end let(:body) do nil end let(:params) do {} end context 'when a body is provided as a document' do let(:body) do "{\"percolate\":{\"index\":\"my-index\",\"type\":\"my-type\"}}\n{\"doc\":{\"message\":\"foo bar\"}}\n" + "{\"percolate\":{\"index\":\"my-other-index\",\"type\":\"my-other-type\",\"id\":\"1\"}}\n{}\n" end it 'performs the request' do expect(client_double.mpercolate(body: [ { percolate: { index: "my-index", type: "my-type" } }, { doc: { message: "foo bar" } }, { percolate: { index: "my-other-index", type: "my-other-type", id: "1" } }, { } ])).to eq({}) end end context 'when a body is provided as a string' do let(:body) do %Q|{"foo":"bar"}\n{"moo":"lam"}| end it 'performs the request' do expect(client_double.mpercolate(body: %Q|{"foo":"bar"}\n{"moo":"lam"}|)).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/msearch_spec.rb000066400000000000000000000054341361161326000316430ustar00rootroot00000000000000require 'spec_helper' describe 'client#msearch' do let(:expected_args) do [ 'GET', url, params, body, headers ] end let(:body) do nil end let(:url) do '_msearch' end let(:params) do {} end let(:headers) do { 'Content-Type' => 'application/x-ndjson' } end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :body argument' do expect { client.msearch }.to raise_exception(ArgumentError) end context 'when the body is an object' do let(:body) do <<-PAYLOAD.gsub(/^\s+/, '') {"index":"foo"} {"query":{"match_all":{}}} {"index":"bar"} {"query":{"match":{"foo":"bar"}}} {"search_type":"count"} {"facets":{"tags":{}}} PAYLOAD end it 'performs the request' do expect(client_double.msearch body: [ { index: 'foo', search: { query: { match_all: {} } } }, { index: 'bar', search: { query: { match: { foo: 'bar' } } } }, { search_type: 'count', search: { facets: { tags: {} } } } ]) end end context 'when the body is a string' do let(:body) do %Q|{"foo":"bar"}\n{"moo":"lam"}| end it 'performs the request' do expect(client_double.msearch(body: %Q|{"foo":"bar"}\n{"moo":"lam"}|)).to eq({}) end end context 'when an index is specified' do let(:url) do 'foo/_msearch' end let(:body) do '' end it 'performs the request' do expect(client_double.msearch(index: 'foo', body: [])) end end context 'when a type and index are specified' do let(:url) do 'foo/bar/_msearch' end let(:body) do '' end it 'performs the request' do expect(client_double.msearch(index: 'foo', type: 'bar', body: [])) end end context 'when multiple indices and multiple types are specified' do let(:url) do 'foo,bar/lam,bam/_msearch' end let(:body) do '' end it 'performs the request' do expect(client_double.msearch(index: ['foo', 'bar'], type: ['lam', 'bam'], body: [])) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/_msearch' end let(:body) do '' end it 'performs the request' do expect(client_double.msearch(index: 'foo^bar', type: 'bar/bam', body: [])).to eq({}) end end context 'when the URL params need to be URL-encoded' do let(:url) do '_msearch' end let(:body) do '' end let(:params) do { search_type: 'scroll' } end it 'performs the request' do expect(client_double.msearch(body: [], search_type: 'scroll')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/msearch_template_spec.rb000066400000000000000000000027441361161326000335370ustar00rootroot00000000000000require 'spec_helper' describe 'client#msearch_template' do let(:expected_args) do [ 'GET', url, params, body, headers ] end let(:body) do nil end let(:params) do {} end let(:headers) do { 'Content-Type' => 'application/x-ndjson' } end let(:url) do '_msearch/template' end context 'when a body is provided as a document' do let(:body) do <<-PAYLOAD.gsub(/^\s+/, '') {"index":"foo"} {"inline":{"query":{"match":{"foo":"{{q}}"}}},"params":{"q":"foo"}} {"index":"bar"} {"id":"query_foo","params":{"q":"foo"}} PAYLOAD end it 'performs the request' do expect(client_double.msearch_template(body: [ { index: 'foo' }, { inline: { query: { match: { foo: '{{q}}' } } }, params: { q: 'foo' } }, { index: 'bar' }, { id: 'query_foo', params: { q: 'foo' } } ])).to eq({}) end end context 'when a body is provided as a string' do let(:body) do %Q|{"foo":"bar"}\n{"moo":"lam"}| end it 'performs the request' do expect(client_double.msearch_template(body: %Q|{"foo":"bar"}\n{"moo":"lam"}|)).to eq({}) end end context 'when an index is provided' do let(:url) do 'foo/_msearch/template' end let(:body) do '' end it 'performs the request' do expect(client_double.msearch_template(index: 'foo', body: [])) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/mtermvectors_spec.rb000066400000000000000000000011251361161326000327440ustar00rootroot00000000000000require 'spec_helper' describe 'client#mtermvectors' do let(:expected_args) do [ 'GET', 'my-index/my-type/_mtermvectors', { }, body ] end let(:body) do { ids: [1, 2, 3] } end it 'performs the request' do expect(client_double.mtermvectors(index: 'my-index', type: 'my-type', body: { ids: [1, 2, 3] })).to eq({}) end context 'when a list of ids is passed instead of a body' do it 'performs the request' do expect(client_double.mtermvectors(index: 'my-index', type: 'my-type', ids: [1, 2, 3])).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/nodes/000077500000000000000000000000001361161326000277645ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/nodes/hot_threads_spec.rb000066400000000000000000000014061361161326000336300ustar00rootroot00000000000000require 'spec_helper' describe 'client.nodes#hot_threads' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_nodes/hot_threads' end it 'performs the request' do expect(client_double.nodes.hot_threads).to eq({}) end context 'when the node id is specified' do let(:url) do '_nodes/foo/hot_threads' end it 'performs the request' do expect(client_double.nodes.hot_threads(node_id: 'foo')).to eq({}) end end context 'when the path must be URL-escaped' do let(:url) do '_nodes/foo%5Ebar/hot_threads' end it 'performs the request' do expect(client_double.nodes.hot_threads(node_id: 'foo^bar')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/nodes/info_spec.rb000066400000000000000000000026711361161326000322640ustar00rootroot00000000000000require 'spec_helper' describe 'client.nodes#info' do let(:expected_args) do [ 'GET', url, params, nil, nil ] end let(:url) do '_nodes' end it 'performs the request' do expect(client_double.nodes.info).to eq({}) end let(:params) do {} end context 'when the node id is specified' do let(:url) do '_nodes/foo' end it 'performs the request' do expect(client_double.nodes.info(node_id: 'foo')).to eq({}) end end context 'when multiple node ids are specified as a list' do let(:url) do '_nodes/A,B,C' end it 'performs the request' do expect(client_double.nodes.info(node_id: ['A', 'B', 'C'])).to eq({}) end end context 'when multiple node ids are specified as a String' do let(:url) do '_nodes/A,B,C' end it 'performs the request' do expect(client_double.nodes.info(node_id: 'A,B,C')).to eq({}) end end context 'when URL params are specified' do let(:url) do '_nodes' end let(:params) do { format: 'yaml' } end it 'performs the request' do expect(client_double.nodes.info(format: 'yaml')).to eq({}) end end context 'when metrics are specified' do let(:url) do '_nodes/http,network' end it 'performs the request' do expect(client_double.nodes.info(metric: ['http', 'network'])).to eq({}) end end end reload_secure_settings_spec.rb000066400000000000000000000026561361161326000360110ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/nodesrequire 'spec_helper' describe 'client#reload_secure_settings' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:params) do {} end let(:url) do '_nodes/reload_secure_settings' end it 'performs the request' do expect(client_double.nodes.reload_secure_settings()).to eq({}) end context 'when a node id is specified' do let(:url) do '_nodes/foo/reload_secure_settings' end it 'performs the request' do expect(client_double.nodes.reload_secure_settings(node_id: 'foo')).to eq({}) end end context 'when more than one node id is specified as a string' do let(:url) do '_nodes/foo,bar/reload_secure_settings' end it 'performs the request' do expect(client_double.nodes.reload_secure_settings(node_id: 'foo,bar', body: { foo: 'bar' })).to eq({}) end end context 'when more than one node id is specified as a list' do let(:url) do '_nodes/foo,bar/reload_secure_settings' end it 'performs the request' do expect(client_double.nodes.reload_secure_settings(node_id: ['foo', 'bar'], body: { foo: 'bar' })).to eq({}) end end context 'when a timeout param is specified' do let(:params) do { timeout: '30s'} end it 'performs the request' do expect(client_double.nodes.reload_secure_settings(timeout: '30s')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/nodes/shutdown_spec.rb000066400000000000000000000020711361161326000331760ustar00rootroot00000000000000require 'spec_helper' describe 'client.nodes#shutdown' do let(:expected_args) do [ 'POST', url, params, nil, nil ] end let(:url) do '_cluster/nodes/_shutdown' end it 'performs the request' do expect(client_double.nodes.shutdown).to eq({}) end let(:params) do {} end context 'when the node id is specified' do let(:url) do '_cluster/nodes/foo/_shutdown' end it 'performs the request' do expect(client_double.nodes.shutdown(node_id: 'foo')).to eq({}) end end context 'when multiple node ids are specified as a list' do let(:url) do '_cluster/nodes/A,B,C/_shutdown' end it 'performs the request' do expect(client_double.nodes.shutdown(node_id: ['A', 'B', 'C'])).to eq({}) end end context 'when multiple node ids are specified as a String' do let(:url) do '_cluster/nodes/A,B,C/_shutdown' end it 'performs the request' do expect(client_double.nodes.shutdown(node_id: 'A,B,C')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/nodes/stats_spec.rb000066400000000000000000000017751361161326000324730ustar00rootroot00000000000000require 'spec_helper' describe 'client.nodes#stats' do let(:expected_args) do [ 'GET', url, params, nil, nil ] end let(:url) do '_nodes/stats' end it 'performs the request' do expect(client_double.nodes.stats).to eq({}) end let(:params) do {} end context 'when the node id is specified' do let(:url) do '_nodes/foo/stats' end it 'performs the request' do expect(client_double.nodes.stats(node_id: 'foo')).to eq({}) end end context 'when metrics are specified' do let(:url) do '_nodes/stats/http,fs' end it 'performs the request' do expect(client_double.nodes.stats(metric: [:http, :fs])).to eq({}) end end context 'when index metric is specified' do let(:url) do '_nodes/stats/indices/filter_cache' end it 'performs the request' do expect(client_double.nodes.stats(metric: :indices, index_metric: :filter_cache)).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/percolate_spec.rb000066400000000000000000000025211361161326000321710ustar00rootroot00000000000000require 'spec_helper' describe 'client#percolate' do let(:expected_args) do [ 'GET', url, { }, body ] end let(:body) do { doc: { foo: 'bar' }} end let(:url) do 'foo/bar/_percolate' end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.percolate(type: 'bar', body: {}) }.to raise_exception(ArgumentError) end it 'requires the :type argument' do expect { client.percolate(index: 'foo', body: {}) }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.percolate(index: 'foo', type: 'bar', body: { doc: { foo: 'bar' } })).to eq({}) end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/_percolate' end it 'URL-escapes the parts' do expect(client_double.percolate(index: 'foo^bar', type: 'bar/bam', body: { doc: { foo: 'bar' } })).to eq({}) end end context 'when the document id needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/some%2Fid/_percolate' end let(:body) do nil end it 'URL-escapes the id' do expect(client_double.percolate(index: 'foo^bar', type: 'bar/bam', id: 'some/id')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/ping_spec.rb000066400000000000000000000021661361161326000311550ustar00rootroot00000000000000require 'spec_helper' describe 'client#ping' do let(:expected_args) do [ 'HEAD', '', { }, nil ] end it 'performs the request' do expect(client_double.ping).to eq(true) end context 'when the response is a 404' do let(:response_double) do double('response', status: 404, body: {}, headers: {}) end it 'returns false' do expect(client_double.ping).to eq(false) end end context 'when a 404 \'not found\' exception is raised' do before do allow(client).to receive(:perform_request).and_raise(StandardError.new('404 NotFound')) end let(:client) do Class.new { include Elasticsearch::API }.new end it 'returns false' do expect(client.ping).to eq(false) end end context 'when \'connection failed\' exception is raised' do before do allow(client).to receive(:perform_request).and_raise(StandardError.new('ConnectionFailed')) end let(:client) do Class.new { include Elasticsearch::API }.new end it 'returns false' do expect(client.ping).to eq(false) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/put_script_spec.rb000066400000000000000000000011171361161326000324070ustar00rootroot00000000000000require 'spec_helper' describe 'client#put_script' do let(:expected_args) do [ 'PUT', url, { }, { script: 'bar' } ] end let(:url) do '_scripts/groovy/foo' end it 'performs the request' do expect(client_double.put_script(lang: 'groovy', id: 'foo', body: { script: 'bar' })).to eq({}) end context 'when the lang parameter is not provided' do let(:url) do '_scripts/foo' end it 'performs the request' do expect(client_double.put_script(id: 'foo', body: { script: 'bar' })).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/put_template_spec.rb000066400000000000000000000004271361161326000327210ustar00rootroot00000000000000require 'spec_helper' describe 'client#put_template' do let(:expected_args) do [ 'POST', '_scripts/foo', { }, { } ] end it 'performs the request' do expect(client_double.put_template(id: 'foo', body: { })).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/reindex_spec.rb000066400000000000000000000003751361161326000316560ustar00rootroot00000000000000require 'spec_helper' describe 'client#reindex' do let(:expected_args) do [ 'POST', '_reindex', { }, { } ] end it 'performs the request' do expect(client_double.reindex(body: {})).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/remote/000077500000000000000000000000001361161326000301475ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/remote/info_spec.rb000066400000000000000000000004121361161326000324360ustar00rootroot00000000000000require 'spec_helper' describe 'client.remote#info' do let(:expected_args) do [ 'GET', '_remote/info', {}, nil, nil ] end it 'performs the request' do expect(client_double.remote.info).to eq({}) end end render_search_template_spec.rb000066400000000000000000000005161361161326000346350ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actionsrequire 'spec_helper' describe 'client#render_search_template' do let(:expected_args) do [ 'GET', '_render/template', { id: 'foo' }, { foo: 'bar' } ] end it 'performs the request' do expect(client_double.render_search_template(id: 'foo', body: { foo: 'bar' })).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/scoll_spec.rb000066400000000000000000000004451361161326000313320ustar00rootroot00000000000000require 'spec_helper' describe 'client#scroll' do let(:expected_args) do [ 'GET', '_search/scroll', { scroll_id: 'cXVlcn...' }, nil ] end it 'performs the request' do expect(client_double.scroll(scroll_id: 'cXVlcn...')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/search_exists_spec.rb000066400000000000000000000064461361161326000330710ustar00rootroot00000000000000module Elasticsearch module API module Actions # Return whether documents exists for a particular query # # @option arguments [List] :index A comma-separated list of indices to restrict the results # @option arguments [List] :type A comma-separated list of types to restrict the results # @option arguments [Hash] :body A query to restrict the results specified with the Query DSL (optional) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing or closed) # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves # into no concrete indices. # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices # that are open, closed or both. # (options: open, closed, none, all) # @option arguments [Number] :min_score Include only documents with a specific `_score` value in the result # @option arguments [String] :preference Specify the node or shard the operation should be performed on # (default: random) # @option arguments [String] :routing Specific routing value # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be # analyzed (default: false) # @option arguments [String] :default_operator The default operator for query string query (AND or OR) # (options: AND, OR) # @option arguments [String] :df The field to use as default where no field prefix is given # in the query string # @option arguments [Boolean] :lenient Specify whether format-based query failures # (such as providing text to a numeric field) should be ignored # @option arguments [Boolean] :lowercase_expanded_terms Specify whether query terms should be lowercased # # @see http://www.elastic.co/guide/en/elasticsearch/reference/master/search-exists.html # def search_exists(arguments={}) method = 'POST' path = "_search/exists" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:search_exists, [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :min_score, :preference, :routing, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :lowercase_expanded_terms ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/search_shards_spec.rb000066400000000000000000000004041361161326000330220ustar00rootroot00000000000000require 'spec_helper' describe 'client#search_shards' do let(:expected_args) do [ 'GET', '_search_shards', { }, nil ] end it 'performs the request' do expect(client_double.search_shards).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/search_spec.rb000066400000000000000000000037661361161326000314740ustar00rootroot00000000000000require 'spec_helper' describe 'client#search' do let(:expected_args) do [ 'GET', url, params, body ] end let(:body) do nil end let(:params) do {} end let(:url) do '_all/foo/_search' end it 'has a default value for index' do expect(client_double.search(type: 'foo')) end context 'when a request definition is specified' do let(:body) do { query: { match: {} } } end let(:url) do '_search' end it 'performs the request' do expect(client_double.search(body: { query: { match: {} } })) end end context 'when an index is specified' do let(:url) do 'foo/_search' end it 'performs the request' do expect(client_double.search(index: 'foo')) end end context 'when an index and type are specified' do let(:url) do 'foo/bar/_search' end it 'performs the request' do expect(client_double.search(index: 'foo', type: 'bar')) end end context 'when multiple indices are specified' do let(:url) do 'foo,bar/_search' end it 'performs the request' do expect(client_double.search(index: ['foo', 'bar'])) end end context 'when multiple indices and types are specified' do let(:url) do 'foo,bar/lam,bam/_search' end it 'performs the request' do expect(client_double.search(index: ['foo', 'bar'], type: ['lam', 'bam'])) end end context 'when there are URL params' do let(:url) do '_search' end let(:params) do { search_type: 'count' } end it 'performs the request' do expect(client_double.search(search_type: 'count')) end end context 'when there are invalid URL params' do let(:client) do Class.new { include Elasticsearch::API }.new end it 'raises an ArgumentError' do expect{ client.search(search_type: 'count', qwertypoiuy: 'asdflkjhg') }.to raise_exception(ArgumentError) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/search_template_spec.rb000066400000000000000000000004751361161326000333610ustar00rootroot00000000000000require 'spec_helper' describe 'client#search_template' do let(:expected_args) do [ 'GET', 'foo/_search/template', { }, { foo: 'bar' } ] end it 'performs the request' do expect(client_double.search_template(index: 'foo', body: { foo: 'bar' })).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshot/000077500000000000000000000000001361161326000305135ustar00rootroot00000000000000create_repository_spec.rb000066400000000000000000000013061361161326000355350ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshotrequire 'spec_helper' describe 'client.snapshot#create_repository' do let(:expected_args) do [ 'PUT', '_snapshot/foo', {}, {}, nil ] end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :body argument' do expect { client.snapshot.create_repository(repository: 'foo') }.to raise_exception(ArgumentError) end it 'requires the :repository argument' do expect { client.snapshot.create_repository(body: {}) }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.snapshot.create_repository(repository: 'foo', body: {})).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshot/create_spec.rb000066400000000000000000000013161361161326000333160ustar00rootroot00000000000000require 'spec_helper' describe 'client.snapshot#create' do let(:expected_args) do [ 'PUT', '_snapshot/foo/bar', {}, {}, nil ] end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :repository argument' do expect { client.snapshot.create(snapshot: 'bar', body: {}) }.to raise_exception(ArgumentError) end it 'requires the :snapshot argument' do expect { client.snapshot.create(repository: 'foo', body: {}) }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.snapshot.create(repository: 'foo', snapshot: 'bar', body: {})).to eq({}) end end delete_repository_spec.rb000066400000000000000000000011211361161326000355270ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshotrequire 'spec_helper' describe 'client.snapshot#delete_repository' do let(:expected_args) do [ 'DELETE', url, {}, nil, nil ] end let(:url) do '_snapshot/foo' end it 'performs the request' do expect(client_double.snapshot.delete_repository(repository: 'foo')).to eq({}) end context 'when multiple indices are specified' do let(:url) do '_snapshot/foo,bar' end it 'performs the request' do expect(client_double.snapshot.delete_repository(repository: ['foo','bar'])).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshot/delete_spec.rb000066400000000000000000000012641361161326000333170ustar00rootroot00000000000000require 'spec_helper' describe 'client.snapshot#delete' do let(:expected_args) do [ 'DELETE', '_snapshot/foo/bar', {}, nil, nil ] end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :snapshot argument' do expect { client.snapshot.delete(repository: 'foo') }.to raise_exception(ArgumentError) end it 'requires the :repository argument' do expect { client.snapshot.delete(snapshot: 'bar') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.snapshot.delete(repository: 'foo', snapshot: 'bar')).to eq({}) end end get_repository_spec.rb000066400000000000000000000004661361161326000350570ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshotrequire 'spec_helper' describe 'client.snapshot#get_repository' do let(:expected_args) do [ 'GET', '_snapshot/foo', {}, nil, nil ] end it 'performs the request' do expect(client_double.snapshot.get_repository(repository: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshot/get_spec.rb000066400000000000000000000012451361161326000326330ustar00rootroot00000000000000require 'spec_helper' describe 'client.snapshot#get' do let(:expected_args) do [ 'GET', '_snapshot/foo/bar', {}, nil, nil ] end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :snapshot argument' do expect { client.snapshot.get(repository: 'foo') }.to raise_exception(ArgumentError) end it 'requires the :repository argument' do expect { client.snapshot.get(snapshot: 'bar') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.snapshot.get(repository: 'foo', snapshot: 'bar')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshot/restore_spec.rb000066400000000000000000000012771361161326000335440ustar00rootroot00000000000000require 'spec_helper' describe 'client.snapshot#restore' do let(:expected_args) do [ 'POST', '_snapshot/foo/bar/_restore', {}, nil, nil ] end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :snapshot argument' do expect { client.snapshot.restore(repository: 'foo') }.to raise_exception(ArgumentError) end it 'requires the :repository argument' do expect { client.snapshot.restore(snapshot: 'bar') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.snapshot.restore(repository: 'foo', snapshot: 'bar')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshot/status_spec.rb000066400000000000000000000010701361161326000333730ustar00rootroot00000000000000require 'spec_helper' describe 'client.snapshot#status' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_snapshot/_status' end it 'performs the request' do expect(client_double.snapshot.status).to eq({}) end context 'when a repository and snapshot are specified' do let(:url) do '_snapshot/foo/bar/_status' end it 'performs the request' do expect(client_double.snapshot.status(repository: 'foo', snapshot: 'bar')).to eq({}) end end end verify_repository_spec.rb000066400000000000000000000005051361161326000355760ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/snapshotrequire 'spec_helper' describe 'client.snapshot#verify_repository' do let(:expected_args) do [ 'POST', '_snapshot/foo/_verify', {}, nil, nil ] end it 'performs the request' do expect(client_double.snapshot.verify_repository(repository: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/suggest_spec.rb000066400000000000000000000024341361161326000316770ustar00rootroot00000000000000require 'spec_helper' describe 'client#suggest' do let(:expected_args) do [ 'POST', url, params, body ] end let(:url) do '_suggest' end let(:params) do {} end let(:body) do {} end it 'performs the request' do expect(client_double.suggest(body: {})).to eq({}) end context 'when an index is specified' do let(:url) do 'foo/_suggest' end it 'performs the request' do expect(client_double.suggest(index: 'foo', body: {})) end end context 'when there are URL params specified' do let(:url) do 'foo/_suggest' end let(:params) do { routing: 'abc123' } end it 'performs the request' do expect(client_double.suggest(index: 'foo', routing: 'abc123', body: {})) end end context 'when the request must be URL-escaped' do let(:url) do 'foo%5Ebar/_suggest' end it 'performs the request' do expect(client_double.suggest(index: 'foo^bar', body: {})) end end context 'when the request definition is specified in the body' do let(:body) do { my_suggest: { text: 'test' } } end it 'performs the request' do expect(client_double.suggest(body: { my_suggest: { text: 'test' } } )) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/tasks/000077500000000000000000000000001361161326000300015ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/tasks/cancel_spec.rb000066400000000000000000000010011361161326000325550ustar00rootroot00000000000000require 'spec_helper' describe 'client.tasks#cancel' do let(:expected_args) do [ 'POST', url, {}, nil, nil ] end let(:url) do '_tasks/_cancel' end it 'performs the request' do expect(client_double.tasks.cancel).to eq({}) end context 'when a task id is specified' do let(:url) do '_tasks/foo/_cancel' end it 'performs the request' do expect(client_double.tasks.cancel(task_id: 'foo')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/tasks/get_spec.rb000066400000000000000000000004261361161326000321210ustar00rootroot00000000000000require 'spec_helper' describe 'client.tasks#get' do let(:expected_args) do [ 'GET', '_tasks/foo1', {}, nil, nil ] end it 'performs the request' do expect(client_double.tasks.get(task_id: 'foo1')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/tasks/list_spec.rb000066400000000000000000000007521361161326000323170ustar00rootroot00000000000000require 'spec_helper' describe 'client.tasks#list' do let(:expected_args) do [ 'GET', url, {}, nil, nil ] end let(:url) do '_tasks' end it 'performs the request' do expect(client_double.tasks.list).to eq({}) end context 'when a task id is specified' do let(:url) do '_tasks/foo' end it 'performs the request' do expect(client_double.tasks.list(task_id: 'foo')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/termvectors_spec.rb000066400000000000000000000020221361161326000325640ustar00rootroot00000000000000require 'spec_helper' describe 'client#termvectors' do let(:expected_args) do [ 'GET', url, params, body ] end let(:url) do 'foo/bar/123/_termvectors' end let(:params) do {} end let(:body) do {} end let(:client) do Class.new { include Elasticsearch::API }.new end it 'requires the :index argument' do expect { client.termvectors(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :type argument' do expect { client.termvectors(index: 'foo', id: '1') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.termvectors(index: 'foo', type: 'bar', id: '123', body: {})).to eq({}) end context 'when the older api name \'termvector\' is used' do let(:url) do 'foo/bar/123/_termvector' end it 'performs the request' do expect(client_double.termvector(index: 'foo', type: 'bar', id: '123', body: {})).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/update_by_query_spec.rb000066400000000000000000000004351361161326000334160ustar00rootroot00000000000000require 'spec_helper' describe 'client#update_by_query' do let(:expected_args) do [ 'POST', 'foo/_update_by_query', { }, nil ] end it 'performs the request' do expect(client_double.update_by_query(index: 'foo')).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/actions/update_document_spec.rb000066400000000000000000000044251361161326000334000ustar00rootroot00000000000000require 'spec_helper' describe 'client#update' do let(:expected_args) do [ 'POST', url, params, body ] end let(:body) do { doc: { } } end let(:url) do 'foo/bar/1/_update' end let(:client) do Class.new { include Elasticsearch::API }.new end let(:params) do {} end it 'requires the :index argument' do expect { client.update(type: 'bar', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :type argument' do expect { client.update(index: 'foo', id: '1') }.to raise_exception(ArgumentError) end it 'requires the :id argument' do expect { client.update(index: 'foo', type: 'bar') }.to raise_exception(ArgumentError) end it 'performs the request' do expect(client_double.update(index: 'foo', type: 'bar', id: '1', body: { doc: {} })).to eq({}) end context 'when URL parameters are provided' do let(:url) do 'foo/bar/1/_update' end let(:params) do { version: 100 } end let(:body) do {} end it 'performs the request' do expect(client_double.update(index: 'foo', type: 'bar', id: '1', version: 100, body: {})) end end context 'when invalid parameters are specified' do it 'raises an ArgumentError' do expect { client.update(index: 'foo', type: 'bar', id: '1', body: { doc: {} }, qwertypoiuy: 'asdflkjhg') }.to raise_exception(ArgumentError) end end context 'when the request needs to be URL-escaped' do let(:url) do 'foo%5Ebar/bar%2Fbam/1/_update' end let(:body) do {} end it 'escapes the parts' do expect(client_double.update(index: 'foo^bar', type: 'bar/bam', id: '1', body: {})) end end context 'when a NotFound exception is raised' do before do allow(client).to receive(:perform_request).and_raise(NotFound) end it 'raises it to the user' do expect { client.update(index: 'foo', type: 'bar', id: 'XXX') }.to raise_exception(NotFound) end context 'when the :ignore parameter is specified' do it 'does not raise the error to the user' do expect(client.update(index: 'foo', type: 'bar', id: 'XXX', ignore: 404)).to eq(false) end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/api_spec.rb000066400000000000000000000010301361161326000273160ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::API do describe '#settings' do it 'allows access to settings' do expect(described_class.settings).not_to be_nil end it 'has a default serializer' do expect(Elasticsearch::API.serializer).to eq(MultiJson) end context 'when settings are changed' do before do Elasticsearch::API.settings[:foo] = 'bar' end it 'changes the settings' do expect(Elasticsearch::API.settings[:foo]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/client_spec.rb000066400000000000000000000010011361161326000300210ustar00rootroot00000000000000require 'spec_helper' describe 'API Client' do let(:client) do Class.new { include Elasticsearch::API }.new end describe '#cluster' do it 'responds to the method' do expect(client.respond_to?(:cluster)).to be(true) end end describe '#indices' do it 'responds to the method' do expect(client.respond_to?(:indices)).to be(true) end end describe '#bulk' do it 'responds to the method' do expect(client.respond_to?(:bulk)).to be(true) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/elasticsearch/api/utils_spec.rb000066400000000000000000000264561361161326000277300ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::API::Utils do let(:utils) do Class.new { include Elasticsearch::API::Utils }.new end describe '#__escape' do it 'encodes Unicode characters' do expect(utils.__escape('中文')).to eq('%E4%B8%AD%E6%96%87') end it 'encodes special characters' do expect(utils.__escape('foo bar')).to eq('foo+bar') expect(utils.__escape('foo/bar')).to eq('foo%2Fbar') expect(utils.__escape('foo^bar')).to eq('foo%5Ebar') end it 'does not encode asterisks' do expect(utils.__escape('*')).to eq('*') end it 'users CGI.escape by default' do expect(CGI).to receive(:escape).and_call_original expect(utils.__escape('foo bar')).to eq('foo+bar') end it 'uses the escape_utils gem when available', unless: JRUBY do require 'escape_utils' expect(CGI).not_to receive(:escape) expect(EscapeUtils).to receive(:escape_url).and_call_original expect(utils.__escape('foo bar')).to eq('foo+bar') end end describe '#__listify' do it 'creates a list from a single value' do expect(utils.__listify('foo')).to eq('foo') end it 'creates a list from an array' do expect(utils.__listify(['foo', 'bar'])).to eq('foo,bar') end it 'creates a list from multiple arguments' do expect(utils.__listify('foo', 'bar')).to eq('foo,bar') end it 'ignores nil values' do expect(utils.__listify(['foo', nil, 'bar'])).to eq('foo,bar') end it 'ignores special characters' do expect(utils.__listify(['foo', 'bar^bam'])).to eq('foo,bar%5Ebam') end context 'when the escape option is set to false' do it 'does not escape the characters' do expect(utils.__listify(['foo', 'bar^bam'], :escape => false)).to eq('foo,bar^bam') end end end describe '#__pathify' do it 'creates a path from a single value' do expect(utils.__pathify('foo')).to eq('foo') end it 'creates a path from an array' do expect(utils.__pathify(['foo', 'bar'])).to eq('foo/bar') end it 'ignores nil values' do expect(utils.__pathify(['foo', nil, 'bar'])).to eq('foo/bar') end it 'ignores empty string values' do expect(utils.__pathify(['foo', '', 'bar'])).to eq('foo/bar') end end describe '#__bulkify' do context 'when the input is an array of hashes' do let(:result) do utils.__bulkify [ { :index => { :_index => 'myindexA', :_type => 'mytype', :_id => '1', :data => { :title => 'Test' } } }, { :update => { :_index => 'myindexB', :_type => 'mytype', :_id => '2', :data => { :doc => { :title => 'Update' } } } }, { :delete => { :_index => 'myindexC', :_type => 'mytypeC', :_id => '3' } } ] end let(:expected_string) do <<-PAYLOAD.gsub(/^\s+/, '') {"index":{"_index":"myindexA","_type":"mytype","_id":"1"}} {"title":"Test"} {"update":{"_index":"myindexB","_type":"mytype","_id":"2"}} {"doc":{"title":"Update"}} {"delete":{"_index":"myindexC","_type":"mytypeC","_id":"3"}} PAYLOAD end it 'serializes the hashes' do expect(result).to eq(expected_string) end end context 'when the input is an array of strings' do let(:result) do utils.__bulkify(['{"foo":"bar"}','{"moo":"bam"}']) end let(:expected_string) do <<-PAYLOAD.gsub(/^\s+/, '') {"foo":"bar"} {"moo":"bam"} PAYLOAD end it 'serializes the array of strings' do expect(result).to eq(expected_string) end end context 'when the input is an array of header/data pairs' do let(:result) do utils.__bulkify([{ foo: 'bar' }, { moo: 'bam' },{ foo: 'baz' }]) end let(:expected_string) do <<-PAYLOAD.gsub(/^\s+/, '') {"foo":"bar"} {"moo":"bam"} {"foo":"baz"} PAYLOAD end it 'serializes the array of strings' do expect(result).to eq(expected_string) end end context 'when the payload has the :data option' do let(:input) do { index: { foo: 'bar', data: { moo: 'bam' } } } end let(:result) do utils.__bulkify([input]) end let(:expected_string) do <<-PAYLOAD.gsub(/^\s+/, '') {"index":{"foo":"bar"}} {"moo":"bam"} PAYLOAD end it 'does not mutate the input' do expect(input[:index][:data]).to eq(moo: 'bam') end it 'serializes the array of strings' do expect(result).to eq(expected_string) end end context 'when the payload has nested :data options' do let(:data) do { data: { a: 'b', data: { c: 'd' } } } end let(:result) do utils.__bulkify([{ index: { foo: 'bar'} } , data]) end let(:lines) do result.split("\n") end let(:header) do MultiJson.load(lines.first) end let(:data_string) do MultiJson.load(lines.last) end it 'does not mutate the input' do expect(data[:data]).to eq(a: 'b', data: { c: 'd' }) end it 'serializes the array of strings' do expect(header['index']['foo']).to eq('bar') expect(data_string['data']['a']).to eq('b') expect(data_string['data']['data']['c']).to eq('d') end end end context '#__validate_and_extract_params' do it 'listify Arrays' do expect(utils.__validate_and_extract_params({ foo: ['a', 'b'] }, [:foo] )).to eq(foo: 'a,b') end it 'does not escape the parameters' do expect(utils.__validate_and_extract_params({ foo: ['a.*', 'b.*'] }, [:foo] )).to eq(foo: 'a.*,b.*') end context 'when the params are valid' do it 'extracts the valid params from the hash' do expect(utils.__validate_and_extract_params({ foo: 'qux' }, [:foo, :bar]) ).to eq(foo: 'qux') end end context 'when the params are invalid' do it 'raises an ArgumentError' do expect { utils.__validate_and_extract_params({ foo: 'qux', bam: 'mux' }, [:foo, :bar]) }.to raise_exception(ArgumentError) end end context 'when COMMON_PARAMS are provided' do it 'extracts the params' do expect(utils.__validate_and_extract_params({ index: 'foo'}, [:foo])).to eq({}) end end context 'when COMMON_QUERY_PARAMS are provided' do it 'extracts the params' do expect(utils.__validate_and_extract_params(format: 'yaml')).to eq(format: 'yaml') end end context 'when the :skip_paramter_validation option is set' do let(:result) do utils.__validate_and_extract_params( { foo: 'q', bam: 'm' }, [:foo, :bar], { skip_parameter_validation: true } ) end it 'skips parameter validation' do expect(result).to eq(foo: 'q', bam: 'm') end end context 'when the module has the setting to skip parameter validation' do around do |example| original_value = Elasticsearch::API.settings[:skip_parameter_validation] Elasticsearch::API.settings[:skip_parameter_validation] = true example.run Elasticsearch::API.settings[:skip_parameter_validation] = original_value end let(:result) do utils.__validate_and_extract_params( { foo: 'q', bam: 'm' }, [:foo, :bar]) end it 'applies the module setting' do expect(result).to eq(foo: 'q', bam: 'm') end end end describe '#__extract_parts' do it 'extracts parts with true value from a Hash' do expect(utils.__extract_parts({ foo: true, moo: 'blah' }, [:foo, :bar])).to eq(['foo']) end it 'extracts parts with string value from a Hash' do expect(utils.__extract_parts({ foo: 'qux', moo: 'blah' }, [:foo, :bar])).to eq(['qux']) end end context '#__rescue_from_not_found' do it 'returns false if exception class name contains \'NotFound\'' do expect(utils.__rescue_from_not_found { raise NotFound }).to be(false) end it 'returns false if exception message contains \'Not Found\'' do expect(utils.__rescue_from_not_found { raise StandardError.new "Not Found" }).to be(false) expect(utils.__rescue_from_not_found { raise StandardError.new "NotFound" }).to be(false) end it 'raises the exception if the class name and message do not include \'NotFound\'' do expect { utils.__rescue_from_not_found { raise StandardError.new "Any other exception" } }.to raise_exception(StandardError) end end context '#__report_unsupported_parameters' do context 'when the parameters are passed as Symbols' do let(:arguments) do { foo: 'bar', moo: 'bam', baz: 'qux' } end let(:unsupported_params) do [ :foo, :moo] end let(:message) do message = '' expect(Kernel).to receive(:warn) { |msg| message = msg } utils.__report_unsupported_parameters(arguments, unsupported_params) message end it 'prints the unsupported parameters' do expect(message).to match(/You are using unsupported parameter \[\:foo\]/) expect(message).to match(/You are using unsupported parameter \[\:moo\]/) end end context 'when the parameters are passed as Hashes' do let(:arguments) do { foo: 'bar', moo: 'bam', baz: 'qux' } end let(:unsupported_params) do [ :foo, :moo] end let(:message) do message = '' expect(Kernel).to receive(:warn) { |msg| message = msg } utils.__report_unsupported_parameters(arguments, unsupported_params) message end it 'prints the unsupported parameters' do expect(message).to match(/You are using unsupported parameter \[\:foo\]/) expect(message).to match(/You are using unsupported parameter \[\:moo\]/) end end context 'when the parameters are passed as a mix of Hashes and Symbols' do let(:arguments) do { foo: 'bar', moo: 'bam', baz: 'qux' } end let(:unsupported_params) do [ { :foo => { :explanation => 'NOT_SUPPORTED'} }, :moo ] end let(:message) do message = '' expect(Kernel).to receive(:warn) { |msg| message = msg } utils.__report_unsupported_parameters(arguments, unsupported_params) message end it 'prints the unsupported parameters' do expect(message).to match(/You are using unsupported parameter \[\:foo\]/) expect(message).to match(/You are using unsupported parameter \[\:moo\]/) expect(message).to match(/NOT_SUPPORTED/) end end context 'when unsupported parameters are unused' do let(:arguments) do { moo: 'bam', baz: 'qux' } end let(:unsupported_params) do [ :foo ] end it 'prints the unsupported parameters' do expect(Kernel).not_to receive(:warn) utils.__report_unsupported_parameters(arguments, unsupported_params) end end end describe '#__report_unsupported_method' do let(:message) do message = '' expect(Kernel).to receive(:warn) { |msg| message = msg } utils.__report_unsupported_method(:foo) message end it 'prints a warning' do expect(message).to match(/foo/) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/spec/spec_helper.rb000066400000000000000000000036211361161326000244510ustar00rootroot00000000000000require 'pry-nav' require 'elasticsearch-transport' require 'elasticsearch-api' require 'jbuilder' if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'jsonify' require 'ansi' tracer = ::Logger.new(STDERR) tracer.formatter = lambda { |s, d, p, m| "#{m.gsub(/^.*$/) { |n| ' ' + n }.ansi(:faint)}\n" } RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) unless defined?(ELASTICSEARCH_URL) ELASTICSEARCH_URL = ENV['ELASTICSEARCH_URL'] || ENV['TEST_ES_SERVER'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" end DEFAULT_CLIENT = Elasticsearch::Client.new host: ELASTICSEARCH_URL, tracer: (ENV['QUIET'] ? nil : tracer) module HelperModule def self.included(context) context.let(:client_double) do Class.new { include Elasticsearch::API }.new.tap do |client| expect(client).to receive(:perform_request).with(*expected_args).and_return(response_double) end end context.let(:client) do Class.new { include Elasticsearch::API }.new.tap do |client| expect(client).to receive(:perform_request).with(*expected_args).and_return(response_double) end end context.let(:response_double) do double('response', status: 200, body: {}, headers: {}) end end end RSpec.configure do |config| config.include(HelperModule) config.formatter = 'documentation' config.color = true end if ENV['COVERAGE'] && ENV['CI'].nil? && !RUBY_1_8 require 'simplecov' SimpleCov.start { add_filter "/test|test_/" } end if ENV['CI'] && !RUBY_1_8 require 'simplecov' require 'simplecov-rcov' SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start { add_filter "/test|test_" } end unless ENV["NOTURN"] || RUBY_1_8 require 'turn' if ENV['QUIET'] Turn.config.format = :outline Turn.config.trace = 1 end end class NotFound < StandardError; end elasticsearch-ruby-6.8.1/elasticsearch-api/test/000077500000000000000000000000001361161326000216565ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/test/integration/000077500000000000000000000000001361161326000242015ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/test/integration/yaml_test_runner.rb000066400000000000000000000471361361161326000301330ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) require 'pathname' require 'logger' require 'yaml' require 'active_support/inflector' require 'ansi' require 'turn' require 'elasticsearch' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/extensions/test/profiling' unless JRUBY # Skip features skip_features = 'stash_in_path,requires_replica,headers,warnings,default_shards' SKIP_FEATURES = ENV.fetch('TEST_SKIP_FEATURES', skip_features) # Turn configuration ENV['ansi'] = 'false' if ENV['CI'] Turn.config.format = :pretty # Launch test cluster # if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? Elasticsearch::Extensions::Test::Cluster.start end # Register `at_exit` handler for server shutdown. # MUST be called before requiring `test/unit`. # at_exit { Elasticsearch::Extensions::Test::Cluster.stop if ENV['SERVER'] and Elasticsearch::Extensions::Test::Cluster.running? } class String # Reset the `ansi` method on CI def ansi(*args) self end end if ENV['CI'] module CapturedLogger def self.included base base.class_eval do %w[ info error warn fatal debug ].each do |m| alias_method "#{m}_without_capture", m define_method m do |*args| @logdev.__send__ :puts, *(args.join("\n") + "\n") self.__send__ "#{m}_without_capture", *args end end end end end Logger.__send__ :include, CapturedLogger if ENV['CI'] logger = Logger.new($stderr) logger.progname = 'elasticsearch' logger.formatter = proc do |severity, datetime, progname, msg| color = case severity when /INFO/ then :green when /ERROR|WARN|FATAL/ then :red when /DEBUG/ then :cyan else :white end "#{severity[0]} ".ansi(color, :faint) + msg.ansi(:white, :faint) + "\n" end tracer = Logger.new($stdout) tracer.progname = 'elasticsearch.tracer' tracer.formatter = proc { |severity, datetime, progname, msg| "#{msg}\n" } # Set up the client for the test # # To set up your own client, just set the `$client` variable in a file, and then require it: # # ruby -I lib:test -r ./tmp/my_special_client.rb test/integration/yaml_test_runner.rb # url = ENV['TEST_CLUSTER_URL'] || ENV['TEST_ES_SERVER'] url = "http://localhost:#{ENV['TEST_CLUSTER_PORT'] || 9250}" unless url $client ||= Elasticsearch::Client.new url: url $helper_client ||= Elasticsearch::Client.new url: url $client.transport.logger = logger unless ENV['QUIET'] || ENV['CI'] # $client.transport.tracer = tracer if ENV['CI'] # Store Elasticsearch version # es_version_info = $client.info['version'] $es_version = es_version_info['number'] puts '-'*80, "Elasticsearch #{$es_version.ansi(:bold)} [#{es_version_info['build_hash'].to_s[0...7]}]".center(80), '-'*80 require 'test_helper' require 'test/unit' require 'shoulda/context' # Monkeypatch shoulda to remove "should" from test name # module Shoulda module Context class Context def create_test_from_should_hash(should) test_name = ["test:", full_name, "|", "#{should[:name]}"].flatten.join(' ').to_sym if test_methods[test_unit_class][test_name.to_s] then raise DuplicateTestError, "'#{test_name}' is defined more than once." end test_methods[test_unit_class][test_name.to_s] = true context = self test_unit_class.send(:define_method, test_name) do @shoulda_context = context begin context.run_parent_setup_blocks(self) should[:before].bind(self).call if should[:before] context.run_current_setup_blocks(self) should[:block].bind(self).call ensure context.run_all_teardown_blocks(self) end end end end end end module Elasticsearch module YamlTestSuite $last_response = '' $results = {} $stash = {} module Utils def titleize(word) word.to_s.gsub(/[^\w]+/, ' ').gsub(/\b('?[a-z])/) { $1.capitalize }.tr('_', ' ') end def symbolize_keys(object) if object.is_a? Hash object.reduce({}) { |memo,(k,v)| memo[k.to_s.to_sym] = symbolize_keys(v); memo } else object end end extend self end module Runner def perform_api_call(test, api, arguments=nil) namespace = api.split('.') replacer = lambda do |value| case value when Array value.map { |v| replacer.call(v) } when Hash Hash[ value.map { |v| replacer.call(v) } ] else fetch_or_return value end end timefixer = lambda do |value| if value.is_a?(Time) value.iso8601 else value end end arguments = Hash[ arguments.map do |key, value| replacement = replacer.call(value) replacement = timefixer.call(replacement) [key, replacement] end ] $stderr.puts "ARGUMENTS: #{arguments.inspect}" if ENV['DEBUG'] $last_response = namespace.reduce($client) do |memo, current| unless current == namespace.last memo = memo.send(current) else arguments ? memo = memo.send(current, arguments) : memo = memo.send(current) end memo end $results[test.hash] = $last_response end def evaluate(test, property, response=nil) response ||= $results[test.hash] property.gsub(/\\\./, '_____').split('.').reduce(response) do |memo, attr| if memo if attr attr = attr.gsub(/_____/, '.') attr = $stash[attr] if attr.start_with? '$' end memo = memo.is_a?(Hash) ? memo[attr] : memo[attr.to_i] end memo end end def in_context(name, &block) klass = Class.new(YamlTestCase) Object::const_set "%sTest" % name.split(/\s/).map { |d| d.capitalize }.join('').gsub(/[^\w]+/, ''), klass klass.context name, &block end def fetch_or_return(var) if var.is_a?(String) && var =~ /^\$(.+)/ $stash[var] else var end end def set(var, val) $stash["$#{var}"] = val end def skip?(actions) skip = actions.select { |a| a['skip'] }.first $stderr.puts "SKIP: #{skip.inspect}" if ENV['DEBUG'] def skip_version(skip) if skip && skip['skip']['version'] return skip['skip']['reason'] ? skip['skip']['reason'] : true if skip['skip']['version'] == 'all' min, max = skip['skip']['version'].split('-').map(&:strip) min_normalized = sprintf "%03d-%03d-%03d", *min.split('.') .map(&:to_i) .fill(0, min.split('.').length, 3-min.split('.').length) max_normalized = sprintf "%03d-%03d-%03d", *max.split('.') .map(&:to_i) .map(&:to_i) .fill(0, max.split('.').length, 3-max.split('.').length) es_normalized = sprintf "%03d-%03d-%03d", *$es_version.split('.').map(&:to_i) if ( min.empty? || min_normalized <= es_normalized ) && ( max.empty? || max_normalized >= es_normalized ) return skip['skip']['reason'] ? skip['skip']['reason'] : true end return false end end def skip_features(skip) if skip && skip['skip']['features'] skip_features = skip['skip']['features'].respond_to?(:split) ? skip['skip']['features'].split(',') : skip['skip']['features'] if ( skip_features & SKIP_FEATURES.split(',') ).size > 0 return skip['skip']['features'] end end end return skip_version(skip) || skip_features(skip) end extend self end class YamlTestCase < ::Test::Unit::TestCase; end end end include Elasticsearch::YamlTestSuite rest_api_test_source = $client.info['version']['number'] < '2' ? '../../../../tmp/elasticsearch/rest-api-spec/test' : '../../../../tmp/elasticsearch/rest-api-spec/src/main/resources/rest-api-spec/test' PATH = Pathname(ENV.fetch('TEST_REST_API_SPEC', File.expand_path(rest_api_test_source, __FILE__))) suites = Dir.glob(PATH.join('*')).map { |d| Pathname(d) } suites = suites.select { |s| s.to_s =~ Regexp.new(ENV['FILTER']) } if ENV['FILTER'] suites.each do |suite| name = Elasticsearch::YamlTestSuite::Utils.titleize(suite.basename) Elasticsearch::YamlTestSuite::Runner.in_context name do # --- Register context setup ------------------------------------------- # setup do $helper_client.indices.delete index: '_all', ignore: 404 $helper_client.indices.delete_template name: '*', ignore: 404 $helper_client.snapshot.delete repository: 'test_repo_create_1', snapshot: 'test_snapshot', ignore: 404 $helper_client.snapshot.delete repository: 'test_repo_restore_1', snapshot: 'test_snapshot', ignore: 404 $helper_client.snapshot.delete repository: 'test_cat_snapshots_1', snapshot: 'snap1', ignore: 404 $helper_client.snapshot.delete repository: 'test_cat_snapshots_1', snapshot: 'snap2', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_repo_create_1', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_repo_restore_1', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_repo_get_1', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_repo_get_2', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_repo_status_1', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_cat_repo_1', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_cat_repo_2', ignore: 404 $helper_client.snapshot.delete_repository repository: 'test_cat_snapshots_1', ignore: 404 # FIXME: This shouldn't be needed ------------- %w[ test_cat_repo_1_loc test_cat_repo_2_loc test_cat_snapshots_1_loc test_repo_get_1_loc test_repo_status_1_loc ].each do |d| FileUtils.rm_rf("/tmp/#{d}") end # --------------------------------------------- $results = {} $stash = {} end # --- Register context teardown ---------------------------------------- # teardown do $helper_client.indices.delete index: '_all', ignore: 404 end files = Dir[suite.join('*.{yml,yaml}')] files.each do |file| begin tests = YAML.load_stream File.new(file) rescue Exception => e $stderr.puts "ERROR [#{e.class}] while loading [#{file}] file".ansi(:red) # raise e next end # Extract setup actions setup_actions = tests.select { |t| t['setup'] }.first['setup'] rescue [] # Skip all the tests when `skip` is part of the `setup` part if features = Runner.skip?(setup_actions) $stdout.puts "#{'SKIP'.ansi(:yellow)} [#{name}] #{file.gsub(PATH.to_s, '').ansi(:bold)} (Feature not implemented: #{features})" next end # Remove setup actions from tests tests = tests.reject { |t| t['setup'] } # Add setup actions to each individual test tests.each { |t| t[t.keys.first] << { 'setup' => setup_actions } } tests.each do |test| context '' do test_name = test.keys.first.to_s + (ENV['QUIET'] ? '' : " | #{file.gsub(PATH.to_s, '').ansi(:bold)}") actions = test.values.first if reason = Runner.skip?(actions) $stdout.puts "#{'SKIP'.ansi(:yellow)} [#{name}] #{test_name} (Reason: #{reason})" next end # --- Register test setup ------------------------------------------- setup do setup_actions = actions.select { |a| a['setup'] } setup_actions.first['setup'].each do |action| if action['do'] api, arguments = action['do'].to_a.first arguments = Utils.symbolize_keys(arguments) Runner.perform_api_call((test.to_s + '___setup'), api, arguments) end if action['set'] stash = action['set'] property, variable = stash.to_a.first result = Runner.evaluate(test, property, $last_response) $stderr.puts "STASH: '$#{variable}' => #{result.inspect}" if ENV['DEBUG'] Runner.set variable, result end end unless setup_actions.empty? end teardown do teardown_actions = actions.select { |a| a['teardown'] } teardown_actions.first['teardown'].each do |action| if action['do'] api, arguments = action['do'].to_a.first arguments = Utils.symbolize_keys(arguments) Runner.perform_api_call((test.to_s + '___teardown'), api, arguments) end if action['set'] stash = action['set'] property, variable = stash.to_a.first result = Runner.evaluate(test, property, $last_response) $stderr.puts "STASH: '$#{variable}' => #{result.inspect}" if ENV['DEBUG'] Runner.set variable, result end end unless teardown_actions.empty? end # --- Register test method ------------------------------------------ should test_name do if ENV['CI'] ref = ENV['TEST_BUILD_REF'].to_s.gsub(/origin\//, '') || 'master' $stderr.puts "https://github.com/elasticsearch/elasticsearch/blob/#{ref}/rest-api-spec/test/" \ + file.gsub(PATH.to_s, ''), "" $stderr.puts YAML.dump(test) if ENV['DEBUG'] end actions.each do |action| $stderr.puts "ACTION: #{action.inspect}" if ENV['DEBUG'] # This check verifies that the YAML has correct indentation. # See https://github.com/elastic/elasticsearch/issues/21980 raise "INVALID YAML: #{action.inspect}" if action.keys.size != 1 case # --- Perform action ------------------------------------------ # when action['do'] catch_exception = action['do'].delete('catch') if action['do'] api, arguments = action['do'].to_a.first arguments = Utils.symbolize_keys(arguments) begin $results[test.hash] = Runner.perform_api_call(test, api, arguments) rescue Exception => e begin $results[test.hash] = MultiJson.load(e.message.match(/{.+}/, 1).to_s) rescue MultiJson::ParseError $stderr.puts "RESPONSE: Cannot parse JSON from error message: '#{e.message}'" if ENV['DEBUG'] end if catch_exception $stderr.puts "CATCH: '#{catch_exception}': #{e.inspect}" if ENV['DEBUG'] if 'param' == catch_exception assert_equal 'ArgumentError', e.class.to_s else if e.class.to_s =~ /Elasticsearch/ case catch_exception when 'missing' assert_match /\[404\]/, e.message when 'conflict' assert_match /\[409\]/, e.message when 'request' assert_match /\[4\d\d\]|\[5\d\d\]/, e.message when /\/.+\// assert_match Regexp.new(catch_exception.tr('/', '')), e.message end else raise e end end else raise e end end # --- Evaluate predicates ------------------------------------- # when property = action['is_true'] result = Runner.evaluate(test, property) $stderr.puts "CHECK: Expected '#{property}' to be true, is: #{result.inspect}" if ENV['DEBUG'] assert(result, "Property '#{property}' should be true, is: #{result.inspect}") when property = action['is_false'] result = Runner.evaluate(test, property) $stderr.puts "CHECK: Expected '#{property}' to be nil, false, 0 or empty string, is: #{result.inspect}" if ENV['DEBUG'] assert_block "Property '#{property}' should be nil, false, 0 or empty string, but is: #{result.inspect}" do result.nil? || result == false || result == 0 || result == '' end when a = action['match'] property, value = a.to_a.first if value.is_a?(String) && value =~ %r{\s*^/\s*.*\s*/$\s*}mx # Begins and ends with / pattern = Regexp.new(value.strip[1..-2], Regexp::EXTENDED|Regexp::MULTILINE) else value = Runner.fetch_or_return(value) end if property == '$body' result = $results[test.hash] else result = Runner.evaluate(test, property) end if pattern $stderr.puts "CHECK: Expected '#{property}' to match #{pattern}, is: #{result.inspect}" if ENV['DEBUG'] assert_match(pattern, result) else value = value.reduce({}) { |memo, (k,v)| memo[k] = Runner.fetch_or_return(v); memo } if value.is_a? Hash $stderr.puts "CHECK: Expected '#{property}' to be '#{value}', is: #{result.inspect}" if ENV['DEBUG'] assert_equal(value, result) end when a = action['length'] property, value = a.to_a.first result = Runner.evaluate(test, property) length = result.size $stderr.puts "CHECK: Expected '#{property}' to be #{value}, is: #{length.inspect}" if ENV['DEBUG'] assert_equal(value, length) when a = action['lt'] || action['gt'] || action['lte'] || action['gte'] property, value = a.to_a.first operator = case when action['lt'] '<' when action['gt'] '>' when action['lte'] '<=' when action['gte'] '>=' end result = Runner.evaluate(test, property) message = "Expected '#{property}' to be #{operator} #{value}, is: #{result.inspect}" $stderr.puts "CHECK: #{message}" if ENV['DEBUG'] assert_operator result, operator.to_sym, Runner.fetch_or_return(value).to_i when stash = action['set'] property, variable = stash.to_a.first result = Runner.evaluate(test, property) $stderr.puts "STASH: '$#{variable}' => #{result.inspect}" if ENV['DEBUG'] Runner.set variable, result end end end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/test/test_helper.rb000066400000000000000000000020421361161326000245170ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) if RUBY_1_8 and not ENV['BUNDLE_GEMFILE'] require 'rubygems' gem 'test-unit' end if ENV['COVERAGE'] && ENV['CI'].nil? && !RUBY_1_8 require 'simplecov' SimpleCov.start { add_filter "/test|test_/" } end if ENV['CI'] && !RUBY_1_8 require 'simplecov' require 'simplecov-rcov' SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start { add_filter "/test|test_" } end require 'test/unit' require 'shoulda-context' require 'mocha/setup' unless ENV["NOTURN"] || RUBY_1_8 require 'turn' if ENV['QUIET'] Turn.config.format = :outline Turn.config.trace = 1 end end require 'require-prof' if ENV["REQUIRE_PROF"] require 'elasticsearch/api' RequireProf.print_timing_infos if ENV["REQUIRE_PROF"] if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/extensions/test/profiling' unless JRUBY end elasticsearch-ruby-6.8.1/elasticsearch-api/utils/000077500000000000000000000000001361161326000220375ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/utils/Gemfile000066400000000000000000000002041361161326000233260ustar00rootroot00000000000000source 'https://rubygems.org' gem 'activesupport' gem 'rest-client' gem 'coderay' gem 'multi_json' gem 'thor' gem 'json' gem 'pry' elasticsearch-ruby-6.8.1/elasticsearch-api/utils/Thorfile000066400000000000000000000002151361161326000235340ustar00rootroot00000000000000require File.expand_path('./thor/generate_api') require File.expand_path('./thor/generate_source') require File.expand_path('./thor/lister') elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/000077500000000000000000000000001361161326000230135ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/generate_api.rb000066400000000000000000000153651361161326000257750ustar00rootroot00000000000000require 'thor' require 'pathname' require 'active_support/core_ext/hash/deep_merge' require 'active_support/inflector/methods' require 'rest_client' require 'json' require 'pry' module Elasticsearch module API module Utils # controller.registerHandler(RestRequest.Method.GET, "/_cluster/health", this); PATTERN_REST = /.*controller.registerHandler\(.*(?GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH)\s*,\s*"(?.*)"\s*,\s*.+\);/ # request.param("index"), request.paramAsBoolean("docs", indicesStatsRequest.docs()), etc PATTERN_URL_PARAMS = /request.param.*\("(?[a-z_]+)".*/ # controller.registerHandler(GET, "/{index}/_refresh", this) PATTERN_URL_PARTS = /\{(?[a-zA-Z0-9\_\-]+)\}/ # request.hasContent() PATTERN_HAS_BODY = /request\.hasContent()/ # Parses the Elasticsearch source code and returns a Hash of REST API information/specs. # # Example: # # { # "cluster.health" => [ # { "method" => "GET", # "path" => "/_cluster/health", # "parts" => ["index"], # "params" => ["index", "local", ... ], # "body" => false # } # def __parse_java_source(path) path += '/' unless path =~ /\/$/ # Add trailing slash if missing prefix = "src/main/java/org/elasticsearch/rest/action" java_rest_files = Dir["#{path}#{prefix}/**/*.java"] map = {} java_rest_files.sort.each do |file| content = File.read(file) parts = file.gsub(path+prefix, '').split('/') name = parts[0, parts.size-1].reject { |p| p =~ /^\s*$/ }.join('.') # Remove the `admin` namespace name.gsub! /admin\./, '' # Extract params url_params = content.scan(PATTERN_URL_PARAMS).map { |n| n.first }.sort # Extract parts url_parts = content.scan(PATTERN_URL_PARTS).map { |n| n.first }.sort # Extract if body allowed has_body = !!content.match(PATTERN_HAS_BODY) # Extract HTTP method and path content.scan(PATTERN_REST) do |method, path| (map[name] ||= []) << { 'method' => method, 'path' => path, 'parts' => url_parts, 'params' => url_params, 'body' => has_body } end end map end extend self end # Contains a generator which will parse the Elasticsearch *.java source files, # extract information about REST API endpoints (URLs, HTTP methods, URL parameters, etc), # and create a skeleton of the JSON API specification file for each endpoint. # # Usage: # # $ thor help api:generate:spec # # Example: # # time thor api:generate:spec \ # --force \ # --verbose \ # --crawl \ # --elasticsearch=/path/to/elasticsearch/source/code # # Features: # # * Extract the API name from the source filename (eg. `admin/cluster/health/RestClusterHealthAction.java` -> `cluster.health`) # * Extract the URLs from the `registerHandler` statements # * Extract the URL parts (eg. `{index}`) from the URLs # * Extract the URL parameters (eg. `{timeout}`) from the `request.param("ABC")` statements # * Detect whether HTTP body is allowed for the API from `request.hasContent()` statements # * Search the website to get proper documentation URLs # * Assemble the JSON format for the API spec # class JsonGenerator < Thor namespace 'api:spec' include Thor::Actions __root = Pathname( File.expand_path('../../..', __FILE__) ) # Usage: thor help api:generate:spec # desc "generate", "Generate JSON API spec files from Elasticsearch source code" method_option :force, type: :boolean, default: false, desc: 'Overwrite the output' method_option :verbose, type: :boolean, default: false, desc: 'Output more information' method_option :output, default: __root.join('tmp/out'), desc: 'Path to output directory' method_option :elasticsearch, default: __root.join('tmp/elasticsearch'), desc: 'Path to directory with Elasticsearch source code' method_option :crawl, type: :boolean, default: false, desc: 'Extract URLs from Elasticsearch website' def generate self.class.source_root File.expand_path('../', __FILE__) @output = Pathname(options[:output]) rest_actions = Utils.__parse_java_source(options[:elasticsearch].to_s) if rest_actions.empty? say_status 'ERROR', 'Cannot find Elasticsearch source in ' + options[:elasticsearch].to_s, :red exit(1) end rest_actions.each do |name, info| doc_url = "" parts = info.reduce([]) { |sum, n| sum |= n['parts']; sum }.reduce({}) { |sum, n| sum[n] = {}; sum } params = info.reduce([]) { |sum, n| sum |= n['params']; sum }.reduce({}) { |sum, n| sum[n] = {}; sum } if options[:crawl] begin response = RestClient.get "http://search.elasticsearch.org/elastic-search-website/guide/_search?q=#{URI.escape(name.gsub(/\./, ' '))}" hits = JSON.load(response)['hits']['hits'] if hit = hits.first if hit['_score'] > 0.2 doc_title = hit['fields']['title'] doc_url = "http://elasticsearch.org" + hit['fields']['url'] end end rescue Exception => e puts "[!] ERROR: #{e.inspect}" end end spec = { name => { 'documentation' => doc_url, 'methods' => info.map { |n| n['method'] }.uniq, 'url' => { 'path' => info.first['path'], 'paths' => info.map { |n| n['path'] }.uniq, 'parts' => parts, 'params' => params }, 'body' => info.first['body'] ? {} : nil } } json = JSON.pretty_generate(spec, indent: ' ', array_nl: '', object_nl: "\n", space: ' ', space_before: ' ') # Fix JSON array formatting json.gsub!(/\[\s+/, '[') json.gsub!(/, {2,}"/, ', "') create_file @output.join( "#{name}.json" ), json + "\n" if options[:verbose] lines = json.split("\n") say_status 'JSON', lines.first + "\n" + lines[1, lines.size].map { |l| ' '*14 + l }.join("\n") end end end private end end end elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/generate_source.rb000066400000000000000000000124561361161326000265220ustar00rootroot00000000000000# encoding: UTF-8 require 'thor' require 'pathname' require 'active_support/core_ext/hash/deep_merge' require 'active_support/inflector' require 'multi_json' require 'coderay' require 'pry' module Elasticsearch module API # A command line application based on [Thor](https://github.com/wycats/thor), # which will read the JSON API spec file(s), and generate # the Ruby source code (one file per API endpoint) with correct # module namespace, method names, and RDoc documentation, # as well as test files for each endpoint. # # Currently it only generates Ruby source, but can easily be # extended and adapted to generate source code for other # programming languages. # class SourceGenerator < Thor namespace 'api:code' include Thor::Actions __root = Pathname( File.expand_path('../../..', __FILE__) ) desc "generate ", "Generate source code and tests from the REST API JSON specification" method_option :language, default: 'ruby', desc: 'Programming language' method_option :force, type: :boolean, default: false, desc: 'Overwrite the output' method_option :verbose, type: :boolean, default: false, desc: 'Output more information' method_option :input, default: File.expand_path('../../../../tmp/elasticsearch/rest-api-spec/api/**/*.json', __FILE__), desc: 'Path to directory with JSON API specs' method_option :output, default: File.expand_path('../../../tmp/out', __FILE__), desc: 'Path to output directory' def generate(*files) self.class.source_root File.expand_path('../', __FILE__) @input = Pathname(options[:input]) @output = Pathname(options[:output]) # -- Test helper copy_file "templates/ruby/test_helper.rb", @output.join('test').join('test_helper.rb') if options[:language] == 'ruby' Dir[@input].each do |file| next if File.basename(file)[0] == '_' @path = Pathname(file) @json = MultiJson.load( File.read(@path) ) @spec = @json.values.first say_status 'json', @path, :yellow @spec['url'] ||= {} @spec['url']['parts'] ||= [] @spec['url']['params'] ||= {} # say_status 'JSON', @spec.inspect, options[:verbose] @full_namespace = @json.keys.first.split('.') @namespace_depth = @full_namespace.size > 0 ? @full_namespace.size-1 : 0 @module_namespace = @full_namespace[0, @namespace_depth] @method_name = @full_namespace.last @http_method = "Elasticsearch::API::HTTP_#{@spec['methods'].first}" @http_path = unless @spec['url']['parts'].empty? @spec['url']['path'] .split('/') .compact .reject { |p| p =~ /^\s*$/ } .map { |p| p =~ /\{/ ? "\#\{arguments[:#{p.tr('{}', '')}]\}" : p } .join('/') .gsub(/^\//, '') else @spec['url']['path'].gsub(/^\//, '') end # -- Ruby files @path_to_file = @output.join('api').join( @module_namespace.join('/') ).join("#{@method_name}.rb") empty_directory @output.join('api').join( @module_namespace.join('/') ) template "templates/#{options[:language]}/method.erb", @path_to_file if options[:verbose] colorized_output = CodeRay.scan_file(@path_to_file, :ruby).terminal lines = colorized_output.split("\n") say_status options[:language].downcase, lines.first + "\n" + lines[1, lines.size].map { |l| ' '*14 + l }.join("\n"), :yellow end # --- Test files @test_directory = @output.join('test/api').join( @module_namespace.join('/') ) @test_file = @test_directory.join("#{@method_name}_test.rb") empty_directory @test_directory template "templates/#{options[:language]}/test.erb", @test_file if options[:verbose] colorized_output = colorized_output = CodeRay.scan_file(@test_file, :ruby).terminal lines = colorized_output.split("\n") say_status options[:language].downcase, lines.first + "\n" + lines[1, lines.size].map { |l| ' '*14 + l }.join("\n"), :yellow say '▬'*terminal_width end end # -- Tree output if options[:verbose] && `which tree > /dev/null 2>&1; echo $?`.to_i < 1 lines = `tree #{@output}`.split("\n") say_status 'tree', lines.first + "\n" + lines[1, lines.size].map { |l| ' '*14 + l }.join("\n") end end private # Create the hierarchy of directories based on API namespaces # def __create_directories(key, value) unless value['documentation'] empty_directory @output.join(key) create_directory_hierarchy *value.to_a.first end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/lister.rb000066400000000000000000000017771361161326000246560ustar00rootroot00000000000000# encoding: UTF-8 require 'thor' require 'pathname' module Elasticsearch module API class Lister < Thor namespace 'api' desc "list ", "List all the REST API endpoints from the JSON specification" method_option :verbose, type: :boolean, default: false, desc: 'Output more information' method_option :format, default: 'text', desc: 'Output format (text, json)' def list(directory) input = Pathname(directory).join('*.json') apis = Dir[input.to_s].map do |f| File.basename(f, '.json') end.sort if options[:verbose] say_status 'Count', apis.size say '▬'*terminal_width end case options[:format] when 'text' apis.each { |a| puts "* #{a}" } when 'json' puts apis.inspect else puts "[!] ERROR: Unknown output format '#{options[:format]}'" exit(1) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/templates/000077500000000000000000000000001361161326000250115ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/templates/ruby/000077500000000000000000000000001361161326000257725ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/templates/ruby/method.erb000066400000000000000000000070771361161326000277570ustar00rootroot00000000000000module Elasticsearch module API <%- @module_namespace.each_with_index do |name, i| -%> <%= ' '*i %>module <%= name == 'xpack' ? 'XPack' : name.capitalize %> <%- end -%> <%= ' '*@namespace_depth %>module Actions <%= ' '*@namespace_depth %># <%= @spec['description'] || 'TODO: Description' %> <%= ' '*@namespace_depth %># <%# URL parts -%> <%- @spec['url']['parts'].each do |name,info| -%> <%- info['type'] = 'String' if info['type'] == 'enum' # Rename 'enums' to 'strings' -%> <%= ' '*@namespace_depth + "# @option arguments [#{info['type'] ? info['type'].capitalize : 'String'}] :#{name} #{info['description'] ? info['description'].strip : '[TODO]'}" + ( info['required'] ? ' (*Required*)' : '' ) -%><%= " (options: #{info['options'].join(', '.strip)})" if info['options'] -%> <%= "\n" -%> <%- end -%> <%# Body -%> <%= ' '*(@namespace_depth+3) + '# @option arguments [Hash] :body ' + (@spec['body']['description'] ? @spec['body']['description'].strip : 'TODO: Description') + (@spec['body']['required'] ? ' (*Required*)' : '') + "\n" if @spec['body'] -%> <%# URL parameters -%> <%- @spec['url']['params'].each do |name,info| -%> <%- info['type'] = 'String' if info['type'] == 'enum' # Rename 'enums' to 'strings' -%> <%= ' '*@namespace_depth + "# @option arguments [#{info['type'] ? info['type'].capitalize : 'String'}] :#{name} #{info['description'] ? info['description'].strip : '[TODO]'}" -%><%= " (options: #{info['options'].join(', ')})" if info['options'] -%> <%= "\n" -%> <%- end if @spec['url']['parts'] -%> <%= ' '*@namespace_depth -%># <%# Documentation link -%> <%= ' '*@namespace_depth %># @see <%= @spec['documentation'] ? @spec['documentation'] : "[TODO]" %> <%= ' '*@namespace_depth %># <%# Method definition -%> <%= ' '*@namespace_depth -%>def <%= @method_name %>(arguments={}) <%# Required arguments -%> <%- @spec['url']['parts'].select { |name, info| info['required'] }.each do |name, info| -%> <%= ' '*(@namespace_depth+1) + "raise ArgumentError, \"Required argument '#{name}' missing\" unless arguments[:#{name}]" + "\n" -%> <%- end -%> <%- if @spec['body'] && @spec['body']['required'] -%> <%= ' '*(@namespace_depth+1) + "raise ArgumentError, \"Required argument 'body' missing\" unless arguments[:body]" + "\n" -%> <%- end -%> <%# Method, path, params, body -%> <%= ' '*@namespace_depth %> method = <%= @http_method %> <%= ' '*@namespace_depth %> path = "<%= @http_path %>" <%- unless @spec['url']['params'].empty? -%> <%= ' '*@namespace_depth %> params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) <%- else -%> <%= ' '*@namespace_depth %> params = {} <%- end -%> <%= ' '*@namespace_depth %> body = <%= @spec['body'].nil? ? 'nil' : 'arguments[:body]' %> <%# Perform request %> <%= ' '*@namespace_depth %> perform_request(method, path, params, body).body <%= ' '*@namespace_depth %>end <%- @namespace_depth.downto(1) do |i| -%> <%= ' '*(i-1) %>end <%- end if @namespace_depth > 0 -%> <%= ' '*@namespace_depth -%># Register this action with its valid params when the module is loaded. <%= ' '*@namespace_depth -%># <%= ' '*@namespace_depth -%># @since 6.2.0 <%= ' '*@namespace_depth -%>ParamsRegistry.register(:<%= @method_name -%>, [ <%= ' '*(@namespace_depth +2) + @spec['url']['params'].keys.map { |k| ":#{k}" }.join(",\n#{' '*(@namespace_depth+5)}") %> ].freeze) end end end elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/templates/ruby/test.erb000066400000000000000000000017721361161326000274520ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class <%= @module_namespace.map {|n| n.capitalize}.map { |n| n == 'Xpack' ? 'XPack' : n }.join('') + @method_name.camelize %>Test < ::Test::Unit::TestCase context "<%= @module_namespace.map {|n| n.capitalize}.map { |n| n == 'Xpack' ? 'XPack' : n }.join(' ') + ': ' %><%= @method_name.humanize %>" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'FAKE', method assert_equal 'test', url assert_equal Hash.new, params <%= @spec['body'].nil? ? 'assert_nil body' : 'assert_equal Hash.new, body' %> true end.returns(FakeResponse.new) subject.<%= @full_namespace.join('.') %> <%= @spec['url']['parts'].select { |name, info| info['required'] }.keys.map { |d| ":#{d} => 'foo'" }.join(', ') rescue '' %> end end end end end elasticsearch-ruby-6.8.1/elasticsearch-api/utils/thor/templates/ruby/test_helper.rb000066400000000000000000000034201361161326000306340ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' require 'rubygems' if RUBY_1_8 require 'simplecov' and SimpleCov.start { add_filter "/test|test_/" } if ENV["COVERAGE"] require 'test/unit' require 'shoulda-context' require 'mocha/setup' require 'turn' unless ENV["TM_FILEPATH"] || ENV["NOTURN"] || RUBY_1_8 require 'require-prof' if ENV["REQUIRE_PROF"] Dir[ File.expand_path('../../lib/elasticsearch/api/**/*.rb', __FILE__) ].each do |f| puts 'Loading: ' + f.to_s if ENV['DEBUG'] require f end RequireProf.print_timing_infos if ENV["REQUIRE_PROF"] module Elasticsearch module Utils def __validate_and_extract_params(*args) {} end extend self end module Test def __full_namespace(o) o.constants.inject([o]) do |sum, c| m = o.const_get(c.to_s.to_sym) sum << __full_namespace(m).flatten if m.is_a?(Module) sum end.flatten end; module_function :__full_namespace module Namespace def cluster self end end class FakeClient # Include all "Actions" modules into the fake client Elasticsearch::Test.__full_namespace(Elasticsearch::API).select { |m| m.to_s =~ /Actions$/ }.each do |m| puts "Including: #{m}" if ENV['DEBUG'] include m end # Include the fake "namespace" methods in the client include Namespace def perform_request(method, path, params, body) puts "PERFORMING REQUEST:", "--> #{method.to_s.upcase} #{path} #{params} #{body}" FakeResponse.new(200, 'FAKE', {}) end end FakeResponse = Struct.new(:status, :body, :headers) do def status values[0] || 200 end def body values[1] || '{}' end def headers values[2] || {} end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/000077500000000000000000000000001361161326000207105ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/.gitignore000066400000000000000000000002321361161326000226750ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp elasticsearch-ruby-6.8.1/elasticsearch-dsl/Gemfile000066400000000000000000000016531361161326000222100ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-dsl.gemspec gemspec if File.exist? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-transport", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => true end if File.exist? File.expand_path("../../elasticsearch-api", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end group :development do gem 'rspec' gem 'pry-nav' end elasticsearch-ruby-6.8.1/elasticsearch-dsl/LICENSE.txt000066400000000000000000000010561361161326000225350ustar00rootroot00000000000000Copyright (c) 2014 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-dsl/README.md000066400000000000000000000210331361161326000221660ustar00rootroot00000000000000# Elasticsearch::DSL The `elasticsearch-dsl` library provides a Ruby API for the [Elasticsearch Query DSL](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html). The library is compatible with Ruby 1.9 or higher and Elasticsearch 1.0 and higher. ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch-dsl To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch-dsl', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git' or install it from a source code checkout: git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch-dsl bundle install rake install ## Usage The library is designed as a group of standalone Ruby modules, classes and DSL methods, which provide an idiomatic way to build complex [search definitions](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html). Let's have a simple example using the declarative variant: ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search do query do match title: 'test' end end definition.to_hash # => { query: { match: { title: "test"} } } require 'elasticsearch' client = Elasticsearch::Client.new trace: true client.search body: definition # curl -X GET 'http://localhost:9200/test/_search?pretty' -d '{ # "query":{ # "match":{ # "title":"test" # } # } # }' # ... # => {"took"=>10, "hits"=> {"total"=>42, "hits"=> [...] } } ``` Let's build the same definition in a more imperative fashion: ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = Search::Search.new definition.query = Search::Queries::Match.new title: 'test' definition.to_hash # => { query: { match: { title: "test"} } } ``` The library doesn't depend on an Elasticsearch client -- its sole purpose is to facilitate building search definitions in Ruby. This makes it possible to use it with any Elasticsearch client: ```ruby require 'elasticsearch/dsl' include Elasticsearch::DSL definition = search { query { match title: 'test' } } require 'json' require 'faraday' client = Faraday.new(url: 'http://localhost:9200') response = JSON.parse( client.post( '/_search', JSON.dump(definition.to_hash), { 'Accept' => 'application/json', 'Content-Type' => 'application/json' } ).body ) # => {"took"=>10, "hits"=> {"total"=>42, "hits"=> [...] } } ``` ## Features Overview The library allows to programatically build complex search definitions for Elasticsearch in Ruby, which are translated to Hashes, and ultimately, JSON, the language of Elasticsearch. All Elasticsearch DSL features are supported, namely: * [Queries](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-queries.html) * [Filters](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filters.html) * [Aggregations](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations.html) * [Suggestions](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html) * [Sorting](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html) * [Pagination](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-from-size.html) * [Options](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html) (source filtering, highlighting, etc) An example of a complex search definition is below. **NOTE:** In order to run the example, you have to allow restoring from the `data.elasticsearch.org` repository by adding the following configuration line to your `elasticsearch.yml`: ```yaml repositories.url.allowed_urls: ["https://s3.amazonaws.com/data.elasticsearch.org/*"] ``` ```ruby require 'awesome_print' require 'elasticsearch' require 'elasticsearch/dsl' include Elasticsearch::DSL client = Elasticsearch::Client.new transport_options: { request: { timeout: 3600, open_timeout: 3600 } } puts "Recovering the 'bicycles.stackexchange.com' index...".yellow client.indices.delete index: 'bicycles.stackexchange.com', ignore: 404 client.snapshot.create_repository repository: 'data.elasticsearch.org', body: { type: 'url', settings: { url: 'https://s3.amazonaws.com/data.elasticsearch.org/bicycles.stackexchange.com/' } } client.snapshot.restore repository: 'data.elasticsearch.org', snapshot: 'bicycles.stackexchange.com', body: { indices: 'bicycles.stackexchange.com' } until client.cluster.health(level: 'indices')['indices']['bicycles.stackexchange.com']['status'] == 'green' r = client.indices.recovery(index: 'bicycles.stackexchange.com', human: true)['bicycles.stackexchange.com']['shards'][0] rescue nil print "\r#{r['index']['size']['recovered'] rescue '0b'} of #{r['index']['size']['total'] rescue 'N/A'}".ljust(52).gray sleep 1 end; puts # The search definition # definition = search { query do # Use a `function_score` query to modify the default score # function_score do query do filtered do # Use a `multi_match` query for the fulltext part of the search # query do multi_match do query 'fixed fixie' operator 'or' fields %w[ title^10 body ] end end # Use a `range` filter on the `creation_date` field # filter do range :creation_date do gte '2013-01-01' end end end end # Multiply the default `_score` by the document rating # functions << { script_score: { script: '_score * doc["rating"].value' } } end end # Calculate the most frequently used tags # aggregation :tags do terms do field 'tags' # Calculate average view count per tag (inner aggregation) # aggregation :avg_view_count do avg field: 'view_count' end end end # Calculate the posting frequency # aggregation :frequency do date_histogram do field 'creation_date' interval 'month' format 'yyyy-MM' # Calculate the statistics on comment count per day (inner aggregation) # aggregation :comments do stats field: 'comment_count' end end end # Calculate the statistical information about the number of comments # aggregation :comment_count_stats do stats field: 'comment_count' end # Highlight the `title` and `body` fields # highlight fields: { title: { fragment_size: 50 }, body: { fragment_size: 50 } } # Return only a selection of the fields # source ['title', 'tags', 'creation_date', 'rating', 'user.location', 'user.display_name'] } puts "Search definition #{'-'*63}\n".yellow ap definition.to_hash # Execute the search request # response = client.search index: 'bicycles.stackexchange.com', type: ['question','answer'], body: definition puts "\nSearch results #{'-'*66}\n".yellow ap response ``` NOTE: You have to enable dynamic scripting to be able to execute the `function_score` query, either by adding `script.disable_dynamic: false` to your elasticsearch.yml or command line parameters. **Please see the extensive RDoc examples in the source code and the integration tests.** ## Development To work on the code, clone the repository and install the dependencies: ``` git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch-dsl/ bundle install ``` Use the Rake tasks to run the test suites: ``` bundle exec rake test:unit bundle exec rake test:integration ``` To launch a separate Elasticsearch server for integration tests, see instructions in the main [README](../README.md#development). ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2015 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-dsl/Rakefile000066400000000000000000000161131361161326000223570ustar00rootroot00000000000000require "bundler/gem_tasks" task(:default) { system "rake --tasks" } task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' require 'rspec/core/rake_task' namespace :test do RSpec::Core::RakeTask.new(:spec) desc "Wait for Elasticsearch to be in a green state" task :wait_for_green do sh '../scripts/wait-cluster.sh' end Rake::TestTask.new(:unit) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] test.deps = [ :spec ] test.verbose = false test.warning = false end Rake::TestTask.new(:integration) do |test| test.deps = [ :wait_for_green ] test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/**/*_test.rb"] test.verbose = false test.warning = false end desc "Run unit and integration tests" Rake::TestTask.new(:all) do |test| test.deps = [ :unit, :integration ] end namespace :cluster do desc "Start Elasticsearch nodes for tests" task :start do $LOAD_PATH << File.expand_path('../../elasticsearch-transport/lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start end desc "Stop Elasticsearch nodes for tests" task :stop do $LOAD_PATH << File.expand_path('../../elasticsearch-transport/lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.stop end end end # ----- Documentation tasks --------------------------------------------------- require 'yard' YARD::Rake::YardocTask.new(:doc) do |t| t.options = %w| --embed-mixins --markup=markdown | end # ----- Code analysis tasks --------------------------------------------------- require 'cane/rake_task' Cane::RakeTask.new(:quality) do |cane| cane.abc_max = 15 cane.no_style = true end # ----- Generating the source code -------------------------------------------- require 'net/http' require 'json' require 'coderay' namespace :generate do desc <<-DESC.gsub(/^ /, '') Generate Ruby source and tests for query/filter/aggregation Pass the type of the component, the name, and any option methods as Rake task arguments. Example: $ rake generate:source[query,boosting] Source: /.../elasticsearch-ruby/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/boosting.rb ... Test: /.../elasticsearch-ruby/elasticsearch-dsl/test/unit/queries/boosting_test.rb ... $ rake generate:source[query,common,query/cutoff_frequency/low_freq_operator/...] Source: /.../elasticsearch-ruby/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/common.rb ... Test: /.../elasticsearch-ruby/elasticsearch-dsl/test/unit/queries/common_test.rb ... DESC task :source, [:type, :name, :option_methods] do |task, options| begin query = URI.escape("#{options[:name]} #{options[:type]}") response = Net::HTTP.get('search.elasticsearch.org', "/search/?q=#{query}") hits = JSON.load(response)['hits']['hits'] if hit = hits.first doc_url = ("http://elasticsearch.org" + hit['fields']['url']).gsub(/#.+$/, '') if hit['_score'] > 0.2 end rescue Exception => e puts "[!] ERROR: #{e.inspect}" end unless ENV['NOCRAWL'] case options[:type] when /query/ module_name = 'Queries' path_name = 'queries' include_module = 'BaseComponent' when /filter/ module_name = 'Filters' path_name = 'filters' include_module = 'BaseComponent' when /agg/ module_name = 'Aggregations' path_name = 'aggregations' include_module = 'BaseAggregationComponent' else raise ArgumentError, "Unknown DSL type [#{options[:type]}]" end name = options[:name].downcase class_name = options[:name].split('_').map(&:capitalize).join option_methods = options[:option_methods].to_s.split('/').reduce('') do |sum, item| sum << " " sum << "option_method :#{item}" sum << "\n" unless item == options[:option_methods].to_s.split('/').last sum end option_methods = "\n\n#{option_methods}" unless option_methods.empty? source = <<-RUBY.gsub(/^ /, '') module Elasticsearch module DSL module Search module #{module_name} # #{class_name} #{options[:type]} # # @example # # @see #{doc_url} # class #{class_name} include #{include_module}#{option_methods} end end end end end RUBY if options[:option_methods].to_s.empty? test_option_methods = '' else setup = "\n" + options[:option_methods].to_s.split('/').reduce('') do |sum,item| sum << " subject.#{item} 'bar'\n"; sum end asserts = "\n assert_equal %w[ #{options[:option_methods].to_s.split('/').sort.join(' ')} ],\n subject.to_hash[:#{name}][:foo].keys.map(&:to_s).sort" asserts << "\n assert_equal 'bar', subject.to_hash[:#{name}][:foo][:#{options[:option_methods].to_s.split('/').first}]" test_option_methods = <<-RUBY.gsub(/^ /, '') should "have option methods" do subject = #{class_name}.new :foo #{setup}#{asserts} end should "take a block" do subject = #{class_name}.new :foo do #{options[:option_methods].to_s.split('/').first} 'bar' end assert_equal({#{name}: { foo: { #{options[:option_methods].to_s.split('/').first}: 'bar' } }}, subject.to_hash) end RUBY end test = <<-RUBY.gsub(/^ /, '') require 'test_helper' module Elasticsearch module Test module #{module_name} class #{class_name}Test < ::Elasticsearch::Test::UnitTestCase include Elasticsearch::DSL::Search::#{module_name} context "#{class_name} #{options[:type]}" do subject { #{class_name}.new } should "be converted to a Hash" do assert_equal({ #{name}: {} }, subject.to_hash) end #{test_option_methods.empty? ? '' : test_option_methods.split("\n").map { |l| ' ' + l }.join("\n")} end end end end end RUBY source_full_path = File.expand_path("../lib/elasticsearch/dsl/search/#{path_name}/#{name}.rb", __FILE__) test_full_path = File.expand_path("../test/unit/#{path_name}/#{name}_test.rb", __FILE__) puts '-'*80, "Source: #{source_full_path}", '-'*80, "\n", CodeRay.scan(source, :ruby).terminal, "\n\n" puts '-'*80, "Test: #{test_full_path}", '-'*80, "\n", CodeRay.scan(test, :ruby).terminal, "\n" File.open(source_full_path, 'w') { |file| file << source } File.open(test_full_path, 'w') { |file| file << test } end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/elasticsearch-dsl.gemspec000066400000000000000000000030701361161326000256470ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/dsl/version' Gem::Specification.new do |s| s.name = "elasticsearch-dsl" s.version = Elasticsearch::DSL::VERSION s.authors = ["Karel Minarik"] s.email = ["karel.minarik@elasticsearch.com"] s.description = %q{A Ruby DSL builder for Elasticsearch} s.summary = s.description s.homepage = "https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-dsl" s.license = "Apache-2.0" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] s.extra_rdoc_files = [ "README.md", "LICENSE.txt" ] s.rdoc_options = [ "--charset=UTF-8" ] s.required_ruby_version = '>= 1.9' s.add_development_dependency "bundler" s.add_development_dependency "rake", "~> 11.1" s.add_development_dependency "elasticsearch" s.add_development_dependency "elasticsearch-extensions" s.add_development_dependency 'shoulda-context' s.add_development_dependency 'mocha' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-reporters' s.add_development_dependency 'simplecov' s.add_development_dependency 'yard' s.add_development_dependency 'cane' s.add_development_dependency 'pry' if defined?(RUBY_VERSION) && RUBY_VERSION > '2.2' s.add_development_dependency "test-unit", '~> 2' end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/000077500000000000000000000000001361161326000214565ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch-dsl.rb000066400000000000000000000000341361161326000253720ustar00rootroot00000000000000require 'elasticsearch/dsl' elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/000077500000000000000000000000001361161326000242705ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl.rb000066400000000000000000000027311361161326000254020ustar00rootroot00000000000000require 'elasticsearch/dsl/version' require 'elasticsearch/dsl/utils' require 'elasticsearch/dsl/search/base_component' require 'elasticsearch/dsl/search/base_compound_filter_component' require 'elasticsearch/dsl/search/base_aggregation_component' require 'elasticsearch/dsl/search/query' require 'elasticsearch/dsl/search/filter' require 'elasticsearch/dsl/search/aggregation' require 'elasticsearch/dsl/search/highlight' require 'elasticsearch/dsl/search/sort' require 'elasticsearch/dsl/search/options' require 'elasticsearch/dsl/search/suggest' Dir[ File.expand_path('../dsl/search/queries/**/*.rb', __FILE__) ].each { |f| require f } Dir[ File.expand_path('../dsl/search/filters/**/*.rb', __FILE__) ].each { |f| require f } Dir[ File.expand_path('../dsl/search/aggregations/**/*.rb', __FILE__) ].each { |f| require f } require 'elasticsearch/dsl/search' module Elasticsearch # The main module, which can be included into your own class or namespace, # to provide the DSL methods. # # @example # # include Elasticsearch::DSL # # definition = search do # query do # match title: 'test' # end # end # # definition.to_hash # # => { query: { match: { title: "test"} } } # # @see Search # @see http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/query-dsl-intro.html # module DSL def self.included(base) base.__send__ :include, Elasticsearch::DSL::Search end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/000077500000000000000000000000001361161326000250525ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search.rb000066400000000000000000000154221361161326000266500ustar00rootroot00000000000000module Elasticsearch module DSL # Provides DSL methods for building the search definition # (queries, filters, aggregations, sorting, etc) # module Search # Initialize a new Search object # # @example Building a search definition declaratively # # definition = search do # query do # match title: 'test' # end # end # definition.to_hash # => {:query=>{:match=>{:title=>"test"}}} # # @example Using the class imperatively # # definition = Search.new # query = Queries::Match.new title: 'test' # definition.query query # definition.to_hash # # => {:query=>{:match=>{:title=>"test"}}} # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search.html # def search(*args, &block) Search.new(*args, &block) end extend self # Wraps the whole search definition (queries, filters, aggregations, sorting, etc) # class Search attr_reader :aggregations def initialize(*args, &block) @options = Options.new *args block.arity < 1 ? self.instance_eval(&block) : block.call(self) if block end # DSL method for building or accessing the `query` part of a search definition # # @return [self, {Query}] # def query(*args, &block) case when block @query = Query.new(*args, &block) self when !args.empty? @query = args.first self else @query end end # Set the query part of a search definition # def query=(value) query value end # DSL method for building the `filter` part of a search definition # # @return [self] # def filter(*args, &block) case when block @filter = Filter.new(*args, &block) self when !args.empty? @filter = args.first self else @filter end end # Set the filter part of a search definition # def filter=(value) filter value end # DSL method for building the `post_filter` part of a search definition # # @return [self] # def post_filter(*args, &block) case when block @post_filter = Filter.new(*args, &block) self when !args.empty? @post_filter = args.first self else @post_filter end end # Set the post_filter part of a search definition # def post_filter=(value) post_filter value end # DSL method for building the `aggregations` part of a search definition # # @return [self] # def aggregation(*args, &block) @aggregations ||= AggregationsCollection.new if block @aggregations.update args.first => Aggregation.new(*args, &block) else name = args.shift @aggregations.update name => args.shift end self end # Set the aggregations part of a search definition # def aggregations=(value) @aggregations = value end # DSL method for building the `highlight` part of a search definition # # @return [self] # def highlight(*args, &block) if !args.empty? || block @highlight = Highlight.new(*args, &block) self else @highlight end end # DSL method for building the `sort` part of a search definition # # @return [self] # def sort(*args, &block) if !args.empty? || block @sort = Sort.new(*args, &block) self else @sort end end # DSL method for building the `stored_fields` part of a search definition # # @return [self] # def stored_fields(value=nil) if value @stored_fields = value self else @stored_fields end end; alias_method :stored_fields=, :stored_fields # DSL method for building the `size` part of a search definition # # @return [self] # def size(value=nil) if value @size = value self else @size end end; alias_method :size=, :size # DSL method for building the `from` part of a search definition # # @return [self] # def from(value=nil) if value @from = value self else @from end end; alias_method :from=, :from # DSL method for building the `suggest` part of a search definition # # @return [self] # def suggest(*args, &block) if !args.empty? || block @suggest ||= {} key, options = args @suggest.update key => Suggest.new(key, options, &block) self else @suggest end end # Set the suggest part of a search definition # def suggest=(value) @suggest = value end # Delegates to the methods provided by the {Options} class # def method_missing(name, *args, &block) if @options.respond_to? name @options.__send__ name, *args, &block self else super end end # Converts the search definition to a Hash # # @return [Hash] # def to_hash hash = {} hash.update(query: @query.to_hash) if @query hash.update(filter: @filter.to_hash) if @filter hash.update(post_filter: @post_filter.to_hash) if @post_filter hash.update(aggregations: @aggregations.reduce({}) { |sum,item| sum.update item.first => item.last.to_hash }) if @aggregations hash.update(sort: @sort.to_hash) if @sort hash.update(size: @size) if @size hash.update(stored_fields: @stored_fields) if @stored_fields hash.update(from: @from) if @from hash.update(suggest: @suggest.reduce({}) { |sum,item| sum.update item.last.to_hash }) if @suggest hash.update(highlight: @highlight.to_hash) if @highlight hash.update(@options) unless @options.empty? hash end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/000077500000000000000000000000001361161326000263175ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregation.rb000066400000000000000000000041451361161326000311370ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Contains the classes for Elasticsearch aggregations # module Aggregations;end class AggregationsCollection < Hash def to_hash @hash ||= Hash[map { |k,v| [k, v.to_hash] }] end end # Wraps the `aggregations` part of a search definition # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations.html # class Aggregation def initialize(*args, &block) @block = block end # Looks up the corresponding class for a method being invoked, and initializes it # # @raise [NoMethodError] When the corresponding class cannot be found # def method_missing(name, *args, &block) klass = Utils.__camelize(name) if Aggregations.const_defined? klass @value = Aggregations.const_get(klass).new *args, &block else raise NoMethodError, "undefined method '#{name}' for #{self}" end end # Defines an aggregation nested in another one # def aggregation(*args, &block) call @value.__send__ :aggregation, *args, &block end # Returns the aggregations # def aggregations call @value.__send__ :aggregations end # Evaluates the block passed to initializer, ensuring it is called just once # # @return [self] # # @api private # def call @block.arity < 1 ? self.instance_eval(&@block) : @block.call(self) if @block && ! @_block_called @_block_called = true self end # Converts the object to a Hash # # @return [Hash] # def to_hash(options={}) call if @value case when @value.respond_to?(:to_hash) @value.to_hash else @value end else {} end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/000077500000000000000000000000001361161326000307715ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/avg.rb000066400000000000000000000011161361161326000320720ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-value metric aggregation which returns the average of numeric values # # @example # # search do # aggregation :avg_clicks do # avg field: 'clicks' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html # class Avg include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/cardinality.rb000066400000000000000000000014611361161326000336230ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-value metric aggregation which returns the approximate count of distinct values # # @example # # search do # aggregation :authors do # cardinality do # field 'author' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html # class Cardinality include BaseComponent option_method :field option_method :precision_threshold option_method :rehash option_method :script option_method :params end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/children.rb000066400000000000000000000021451361161326000331100ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-bucket aggregation which allows to aggregate from buckets on parent documents # to buckets on the children documents # # @example Return the top commenters per article category # # search do # aggregation :top_categories do # terms field: 'category' do # aggregation :comments do # children type: 'comment' do # aggregation :top_authors do # terms field: 'author' # end # end # end # end # end # end # # # See the integration test for a full example. # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-children-aggregation.html # class Children include BaseAggregationComponent option_method :type end end end end end date_histogram.rb000066400000000000000000000021451361161326000342330ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns a histogram for date fields # # @example # # search do # aggregation :daily do # field 'published_at' # interval 'day' # format 'yyyy-MM-dd' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html # class DateHistogram include BaseAggregationComponent option_method :field option_method :interval option_method :pre_zone option_method :post_zone option_method :time_zone option_method :pre_zone_adjust_large_interval option_method :pre_offset option_method :post_offset option_method :format option_method :min_doc_count option_method :extended_bounds option_method :order end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/date_range.rb000066400000000000000000000016641361161326000334160ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns document counts for custom date ranges # # @example # # search do # aggregation :compare_to_last_year do # date_range do # field 'published_at' # ranges [ # { from: 'now-1M/M', to: 'now/M' }, # { from: 'now-13M/M', to: 'now-12M/M' } # ] # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-daterange-aggregation.html # class DateRange include BaseAggregationComponent option_method :field option_method :format option_method :ranges end end end end end extended_stats.rb000066400000000000000000000012141361161326000342530ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule Elasticsearch module DSL module Search module Aggregations # A multi-value metrics aggregation which returns the extended statistical information on numeric values # # @example # # search do # aggregation :clicks_stats do # extended_stats field: 'clicks' # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-extendedstats-aggregation.html # class ExtendedStats include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/filter.rb000066400000000000000000000014461361161326000326100ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # Defines a single bucket with documents matching the provided filter, # usually to define scope for a nested aggregation # # @example # # search do # aggregation :clicks_for_tag_one do # filter terms: { tags: ['one'] } do # aggregation :sum_clicks do # sum field: 'clicks' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filters-aggregation.html # class Filter include BaseAggregationComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/filters.rb000066400000000000000000000017171361161326000327740ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which defines multiple buckets matching the provided filters, # usually to define scope for a nested aggregation # # @example # # search do # aggregation :avg_clicks_per_tag_one_and_two do # filters do # filters one: { terms: { tags: ['one'] } }, # two: { terms: { tags: ['two'] } } # # aggregation :avg do # avg field: 'clicks' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filters-aggregation.html # class Filters include BaseAggregationComponent option_method :filters end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/geo_bounds.rb000066400000000000000000000022071361161326000334430ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # An aggregation which will calculate the smallest bounding box required to encapsulate # all of the documents matching the query # # @example # # search do # query do # filtered do # filter do # geo_bounding_box :location do # top_left "40.8,-74.1" # bottom_right "40.4,-73.9" # end # end # end # end # # aggregation :new_york do # geohash_grid field: 'location' # end # # aggregation :map_zoom do # geo_bounds field: 'location' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geo-bounds-agg.html # class GeoBounds include BaseComponent option_method :field option_method :wrap_longitude end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/geo_distance.rb000066400000000000000000000020721361161326000337430ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which will return document counts for distance perimeters, # defined as ranges # # @example # # search do # aggregation :venue_distances do # geo_distance do # field :location # origin '38.9126352,1.4350621' # unit 'km' # ranges [ { to: 1 }, { from: 1, to: 5 }, { from: 5, to: 10 }, { from: 10 } ] # end # end # end # # See the integration test for a full example. # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geo-distance-agg.html # class GeoDistance include BaseAggregationComponent option_method :field option_method :origin option_method :ranges option_method :unit option_method :distance_type end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/geohash_grid.rb000066400000000000000000000015611361161326000337440ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which will return document counts for geohash grid cells # # @example # # search do # aggregation :venue_distributions do # geohash_grid do # field :location # precision 5 # end # end # end # # See the integration test for a full example. # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geohash-grid-agg.html # class GeohashGrid include BaseAggregationComponent option_method :field option_method :precision option_method :size option_method :shard_size end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/global.rb000066400000000000000000000013141361161326000325550ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # Defines a single bucket of all the documents matching a query # # @example # # search do # aggregation :all_documents do # global do # aggregation :avg_clicks do # avg field: 'clicks' # end # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-global-aggregation.html # class Global include BaseAggregationComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/histogram.rb000066400000000000000000000016011361161326000333110ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns document counts for a defined numerical interval # # @example # # search do # aggregation :age do # histogram do # field 'age' # interval 5 # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-histogram-aggregation.html # class Histogram include BaseAggregationComponent option_method :field option_method :interval option_method :min_doc_count option_method :extended_bounds option_method :order option_method :keyed end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/ip_range.rb000066400000000000000000000014311361161326000331010ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns document counts for defined IP ranges # # @example # # search do # aggregation :ips do # ip_range do # field 'ip' # ranges [ { mask: '10.0.0.0/25' }, { mask: '10.0.0.127/25' } ] # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-iprange-aggregation.html # class IpRange include BaseAggregationComponent option_method :field option_method :ranges end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/max.rb000066400000000000000000000011261361161326000321030ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-value metric aggregation which returns the maximum value from numeric values # # @example # # search do # aggregation :max_clicks do # max field: 'clicks' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-max-aggregation.html # class Max include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/min.rb000066400000000000000000000011261361161326000321010ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-value metric aggregation which returns the minimum value from numeric values # # @example # # search do # aggregation :min_clicks do # min field: 'clicks' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-min-aggregation.html # class Min include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/missing.rb000066400000000000000000000016551361161326000327760ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single bucket aggregation that creates a bucket of all documents # which are missing a value for the field # # @example Passing the options as a Hash # # aggregation :articles_without_tags do # missing field: 'tags' # end # # @example Passing the options as a block # # search do # aggregation :articles_without_tags do # missing do # field 'tags' # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/master/search-aggregations-bucket-missing-aggregation.html # class Missing include BaseAggregationComponent option_method :field end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/nested.rb000066400000000000000000000015211361161326000325770ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-bucket aggregation which allows to aggregate on nested fields # # @example # # search do # aggregation :offers do # nested do # path 'offers' # aggregation :min_price do # min field: 'offers.price' # end # end # end # end # # See the integration test for a full example. # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html # class Nested include BaseAggregationComponent option_method :path end end end end end percentile_ranks.rb000066400000000000000000000015751361161326000345770ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule Elasticsearch module DSL module Search module Aggregations # A multi-value metrics aggregation which calculates percentile ranks on numeric values # # @example # # search do # aggregation :load_time_outliers do # percentile_ranks do # field 'load_time' # values [ 15, 30 ] # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-rank-aggregation.html # class PercentileRanks include BaseComponent option_method :field option_method :values option_method :script option_method :params option_method :compression end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/percentiles.rb000066400000000000000000000015061361161326000336350ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-value metrics aggregation which calculates percentiles on numeric values # # @example # # search do # aggregation :load_time_outliers do # percentiles do # field 'load_time' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-aggregation.html # class Percentiles include BaseComponent option_method :field option_method :percents option_method :script option_method :params option_method :compression end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipeline/000077500000000000000000000000001361161326000325765ustar00rootroot00000000000000avg_bucket.rb000066400000000000000000000017751361161326000351700ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which calculates the (mean) average value of a specified metric in a sibling aggregation. # # @example Passing the options as a Hash # # aggregation :avg_monthly_sales do # avg_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :avg_monthly_sales do # avg_bucket do # buckets_path 'sales_per_month>sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-avg-bucket-aggregation.html # class AvgBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end bucket_script.rb000066400000000000000000000023711361161326000357100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A parent pipeline aggregation which executes a script which can perform per bucket computations on specified metrics in the parent multi-bucket aggregation. # # @example Passing the options as a Hash # # aggregation :t-shirt-percentage do # bucket_script buckets_path: { tShirtSales: 't-shirts>sales', totalSales: 'total_sales' }, script: 'tShirtSales / totalSales * 100' # end # # @example Passing the options as a block # # aggregation :t-shirt-percentage do # bucket_script do # buckets_path tShirtSales: 't-shirts>sales', totalSales: 'total_sales' # script 'tShirtSales / totalSales * 100' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html # class BucketScript include BaseAggregationComponent option_method :buckets_path option_method :script option_method :gap_policy option_method :format end end end end end bucket_selector.rb000066400000000000000000000022071361161326000362220ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A parent pipeline aggregation which executes a script which determines whether the current bucket will be retained in the parent multi-bucket aggregation. # # @example Passing the options as a Hash # # aggregation :sales_bucket_filter do # bucket_selector buckets_path: { totalSales: 'total_sales' }, script: 'totalSales <= 50' # end # # @example Passing the options as a block # # aggregation :sales_bucket_filter do # bucket_selector do # buckets_path totalSales: 'total_sales' # script 'totalSales <= 50' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-selector-aggregation.html # class BucketSelector include BaseAggregationComponent option_method :buckets_path option_method :script option_method :gap_policy end end end end end cumulative_sum.rb000066400000000000000000000017361361161326000361150ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A parent pipeline aggregation which calculates the cumulative sum of a specified metric in a parent histogram (or date_histogram) aggregation. # # @example Passing the options as a Hash # # aggregation :cumulative_sales do # cumulative_sum buckets_path: 'sales' # end # # @example Passing the options as a block # # aggregation :cumulative_sales do # cumulative_sum do # buckets_path 'sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-cumulative-sum-aggregation.html # class CumulativeSum include BaseAggregationComponent option_method :buckets_path option_method :format end end end end end derivative.rb000066400000000000000000000017441361161326000352140ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A parent pipeline aggregation which calculates the derivative of a specified metric in a parent histogram (or date_histogram) aggregation. # # @example Passing the options as a Hash # # aggregation :sales_deriv do # derivative buckets_path: 'sales' # end # # @example Passing the options as a block # # aggregation :sales_deriv do # derivative do # buckets_path 'sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-derivative-aggregation.html # class Derivative include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end extended_stats_bucket.rb000066400000000000000000000022351361161326000374210ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which calculates a variety of stats across all bucket of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation. # # @example Passing the options as a Hash # # aggregation :stats_monthly_sales do # extended_stats_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :stats_monthly_sales do # extended_stats_bucket do # buckets_path 'sales_per_month>sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-extended-stats-bucket-aggregation.html # class ExtendedStatsBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end max_bucket.rb000066400000000000000000000021041361161326000351630ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which identifies the bucket(s) with the maximum value of a specified metric in a sibling aggregation and outputs both the value and the key(s) of the bucket(s). # # @example Passing the options as a Hash # # aggregation :max_monthly_sales do # max_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :max_monthly_sales do # max_bucket do # buckets_path 'sales_per_month>sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-max-bucket-aggregation.html # class MaxBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end min_bucket.rb000066400000000000000000000021041361161326000351610ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which identifies the bucket(s) with the minimum value of a specified metric in a sibling aggregation and outputs both the value and the key(s) of the bucket(s). # # @example Passing the options as a Hash # # aggregation :min_monthly_sales do # min_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :min_monthly_sales do # min_bucket do # buckets_path 'sales_per_month>sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-min-bucket-aggregation.html # class MinBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end moving_avg.rb000066400000000000000000000023711361161326000352030ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # Given an ordered series of data, the Moving Average aggregation will slide a window across the data and emit the average value of that window. # # @example Passing the options as a Hash # # aggregation :the_movavg do # moving_avg buckets_path: 'the_sum' # end # # @example Passing the options as a block # # aggregation :the_movavg do # moving_avg do # buckets_path 'the_sum' # model 'holt' # window 5 # gap_policy 'insert_zero' # settings({ alpha: 0.5 }) # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-movavg-aggregation.html # class MovingAvg include BaseAggregationComponent option_method :buckets_path option_method :model option_method :gap_policy option_method :window option_method :format option_method :minimize option_method :settings end end end end end percentiles_bucket.rb000066400000000000000000000021611361161326000367160ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which calculates percentiles across all bucket of a specified metric in a sibling aggregation. # # @example Passing the options as a Hash # # aggregation :sum_monthly_sales do # percentiles_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :sum_monthly_sales do # percentiles_bucket do # buckets_path 'sales_per_month>sales' # percents [25.0 50.0 75.0] # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-percentiles-bucket-aggregation.html # class PercentilesBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format option_method :percents end end end end end serial_diff.rb000066400000000000000000000020461361161326000353150ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # Serial differencing is a technique where values in a time series are subtracted from itself at different time lags or periods. # # @example Passing the options as a Hash # # aggregation :thirtieth_difference do # serial_diff buckets_path: 'the_sum' # end # # @example Passing the options as a block # # aggregation :thirtieth_difference do # serial_diff do # buckets_path 'the_sum' # lag 30 # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-serialdiff-aggregation.html # class SerialDiff include BaseAggregationComponent option_method :buckets_path option_method :lag option_method :gap_policy option_method :format end end end end end stats_bucket.rb000066400000000000000000000020251361161326000355360ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which calculates a variety of stats across all bucket of a specified metric in a sibling aggregation. # # @example Passing the options as a Hash # # aggregation :stats_monthly_sales do # stats_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :stats_monthly_sales do # stats_bucket do # buckets_path 'sales_per_month>sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-stats-bucket-aggregation.html # class StatsBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end sum_bucket.rb000066400000000000000000000017761361161326000352200ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/pipelinemodule Elasticsearch module DSL module Search module Aggregations # A sibling pipeline aggregation which calculates the sum across all bucket of a specified metric in a sibling aggregation. # # @example Passing the options as a Hash # # aggregation :sum_monthly_sales do # sum_bucket buckets_path: 'sales_per_month>sales' # end # # @example Passing the options as a block # # aggregation :sum_monthly_sales do # sum_bucket do # buckets_path 'sales_per_month>sales' # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-sum-bucket-aggregation.html # class SumBucket include BaseAggregationComponent option_method :buckets_path option_method :gap_policy option_method :format end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/range.rb000066400000000000000000000030701361161326000324120ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns document counts for custom numerical ranges, # which define the buckets # # @example # # search do # aggregation :clicks do # range field: 'clicks', # ranges: [ # { to: 10 }, # { from: 10, to: 20 } # ] # end # end # # @example Using custom names for the ranges # # search do # aggregation :clicks do # range do # field 'clicks' # key :low, to: 10 # key :mid, from: 10, to: 20 # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-range-aggregation.html class Range include BaseAggregationComponent option_method :field option_method :script option_method :params option_method :keyed def key(key, value) @hash[name].update(@args) if @args @hash[name][:keyed] = true unless @hash[name].has_key?(:keyed) @hash[name][:ranges] ||= [] @hash[name][:ranges] << value.merge(key: key) unless @hash[name][:ranges].any? { |i| i[:key] == key } self end end end end end end reverse_nested.rb000066400000000000000000000017551361161326000342640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule Elasticsearch module DSL module Search module Aggregations # A single-bucket aggregation which allows to aggregate on "parent" documents # from the nested documents # # @example # # search do # aggregation :offers do # nested do # path 'offers' # aggregation :top_categories do # reverse_nested do # aggregation :top_category_per_offer do # terms field: 'category' # end # end # end # end # end # end # # See the integration test for a full example. # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/nested-aggregation.html # class ReverseNested include BaseAggregationComponent end end end end end scripted_metric.rb000066400000000000000000000023631361161326000344230ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule Elasticsearch module DSL module Search module Aggregations # A metric aggregation which uses scripts for the computation # # @example # # search do # aggregation :clicks_for_one do # scripted_metric do # init_script "_agg['transactions'] = []" # map_script "if (doc['tags'].value.contains('one')) { _agg.transactions.add(doc['clicks'].value) }" # combine_script "sum = 0; for (t in _agg.transactions) { sum += t }; return sum" # reduce_script "sum = 0; for (a in _aggs) { sum += a }; return sum" # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-scripted-metric-aggregation.html # # See the integration test for a full example. # class ScriptedMetric include BaseComponent option_method :init_script option_method :map_script option_method :combine_script option_method :reduce_script option_method :params option_method :lang end end end end end significant_terms.rb000066400000000000000000000023371361161326000347540ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation that returns interesting or unusual occurrences of terms in a set # # @example # # search do # query do # match :title do # query 'fink' # end # end # # aggregation :interesting_terms do # significant_terms do # field :body # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-significantterms-aggregation.html # class SignificantTerms include BaseAggregationComponent option_method :field option_method :size option_method :shard_size option_method :min_doc_count option_method :shard_min_doc_count option_method :include option_method :exclude option_method :background_filter option_method :mutual_information option_method :chi_square option_method :gnd end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/stats.rb000066400000000000000000000017031361161326000324550ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-value metrics aggregation which returns statistical information on numeric values # # @example Passing the options as a Hash # # search do # aggregation :clicks_stats do # stats field: 'clicks' # end # end # # @example Passing the options as a block # # search do # aggregation :clicks_stats do # stats do # field 'clicks' # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-stats-aggregation.html # class Stats include BaseComponent option_method :field option_method :script end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/sum.rb000066400000000000000000000011121361161326000321150ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-value metric aggregation which returns the sum of numeric values # # @example # # search do # aggregation :sum_clicks do # sum field: 'clicks' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html # class Sum include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/terms.rb000066400000000000000000000022011361161326000324430ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns the collection of terms and their document counts # # @example Passing the options as a Hash # # aggregation :tags do # terms field: 'tags' # end # # @example Passing the options as a block # # search do # aggregation :tags do # terms do # field 'tags' # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html # class Terms include BaseAggregationComponent option_method :field option_method :size option_method :shard_size option_method :order option_method :min_doc_count option_method :shard_min_doc_count option_method :script option_method :include option_method :exclude end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/top_hits.rb000066400000000000000000000016041361161326000331500ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A metric aggregator which returns the most relevant documents per bucket # # @example # # search do # aggregation :tags do # terms do # field 'tags' # # aggregation :top_hits do # top_hits sort: [ clicks: { order: 'desc' } ], _source: { include: 'title' } # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html # class TopHits include BaseComponent option_method :from option_method :size option_method :sort end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/value_count.rb000066400000000000000000000011661361161326000336460ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A single-value metric aggregation which returns the number of values for the aggregation scope # # @example # # search do # aggregation :value_count do # value_count field: 'clicks' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html # class ValueCount include BaseComponent end end end end end base_aggregation_component.rb000066400000000000000000000033241361161326000341320ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/searchmodule Elasticsearch module DSL module Search # Module containing common functionality for aggregation DSL classes # module BaseAggregationComponent def self.included(base) base.__send__ :include, BaseComponent base.__send__ :include, InstanceMethods end module InstanceMethods attr_reader :aggregations # Looks up the corresponding class for a method being invoked, and initializes it # # @raise [NoMethodError] When the corresponding class cannot be found # def method_missing(name, *args, &block) klass = Utils.__camelize(name) if Aggregations.const_defined? klass @value = Aggregations.const_get(klass).new *args, &block else raise NoMethodError, "undefined method '#{name}' for #{self}" end end # Adds a nested aggregation into the aggregation definition # # @return [self] # def aggregation(*args, &block) @aggregations ||= AggregationsCollection.new @aggregations.update args.first => Aggregation.new(*args, &block) self end # Convert the aggregations to a Hash # # A default implementation, DSL classes can overload it. # # @return [Hash] # def to_hash(options={}) call @hash = { name => @args } unless @hash && @hash[name] && ! @hash[name].empty? if @aggregations @hash[:aggregations] = @aggregations.to_hash end @hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/base_component.rb000066400000000000000000000125101361161326000316370ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Module containing common functionality for DSL classes # module BaseComponent def self.included(base) base.__send__ :extend, ClassMethods base.__send__ :include, InstanceMethods base.instance_eval do # Defines an "inner" method for DSL classes # # @example Define a method `bar` for the MyQuery class which updates the query definition # # class MyQuery # include BaseComponent # # option_method :bar # end # # q = MyQuery.new :foo do # bar 'TEST' # end # # q.to_hash # # => {:myquery=>{:foo=>{:bar=>"TEST"}}} # # @example Define a method `bar` with custom logic for updating the Hash with query definition # # class MyCustomQuery # include BaseComponent # # option_method :bar, lambda { |*args| @hash[self.name.to_sym][@args].update custom: args.pop } # end # # q = MyCustomQuery.new :foo do # bar 'TEST' # end # # q.to_hash # # => {:mycustomquery=>{:foo=>{:custom=>"TEST"}}} # def option_method(name, block=nil) option_methods << name if block self.__send__ :define_method, name, &block else self.__send__ :define_method, name do |*args| # 1. Component has empty @args (ie. no user supplied name or @hash value) if @args && @args.respond_to?(:to_hash) && @args.empty? @hash[self.name.to_sym].update name.to_sym => args.first # 2. Component user-supplied name or @hash value passed in @args else @hash[self.name.to_sym] = { @args => {} } unless @hash[self.name.to_sym][@args] @hash[self.name.to_sym][@args].update name.to_sym => args.first end end end end end end def initialize(*args, &block) @hash = { name => {} } @args = args.first || {} @options = args.size > 1 ? args.last : {} @block = block end module ClassMethods # Get or set the name for the DSL class # # @example Set the index name for the `Article` model and re-evaluate it on each call # # class MyQuery # include BaseComponent # name :my_special_query # end # # MyQuery.name # # => :my_special_query # def name(value=nil) if value @name = value.to_sym else @name ||= begin value = self.to_s.split('::').last value.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') value.gsub!(/([a-z\d])([A-Z])/,'\1_\2') value.tr!("-", "_") value.downcase! value.to_sym end end end # Set the name for the DSL class # def name=(value) @name = value.to_sym end def option_methods @option_methods ||= [] end end module InstanceMethods # Return the name for instance of the DSL class # # @return [String] # def name self.class.name end # Evaluates any block passed to the query # # @return [self] # def call @block.arity < 1 ? self.instance_eval(&@block) : @block.call(self) if @block self end # Return true when the component definition is empty # def empty? to_hash[name].respond_to?(:empty?) && to_hash[name].empty? end # Convert the query definition to a Hash # # A default implementation, DSL classes can overload it. # # @return [Hash] # def to_hash(options={}) case # 1. Create hash from the block when @block @hash = (@args && ! @args.empty?) ? { name => { @args => {} } } : { name => {} } call @hash[self.name.to_sym].update @options unless @options.empty? @hash # 2. Hash created with option methods when @hash[self.name.to_sym] && ! @args.is_a?(Hash) && @hash[self.name.to_sym][@args] @hash[self.name.to_sym].update @options unless @options.empty? @hash # 3. Hash passsed as @args when @hash[self.name.to_sym] && @args.respond_to?(:to_hash) && ! @args.empty? { name => @args.to_hash } # 4. Hash already built else @hash end end end end end end end base_compound_filter_component.rb000066400000000000000000000050351361161326000350350ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/searchmodule Elasticsearch module DSL module Search # Module containing common functionality for a "compound" (wrapping) filters, such as `and`, `or`, `not` # module BaseCompoundFilterComponent include Enumerable def initialize(*args, &block) super @value = [] end def self.included(base) base.__send__ :include, InstanceMethods base.__send__ :include, EnumerableMethods base.__send__ :include, MethodDelegation end # Common functionality for the compound filter components # module InstanceMethods # Evaluates the block passed to initializer, ensuring it is called just once # # @return [self] # # @api private # def call @block.arity < 1 ? self.instance_eval(&@block) : @block.call(self) if @block && ! @_block_called @_block_called = true self end # Convert the component to a Hash # # A default implementation, DSL classes can overload it. # # @return [Hash] # def to_hash(options={}) case when @value.empty? && ! @block @hash = super when @block call @hash = { name.to_sym => @value.map { |i| i.to_hash } } else @hash = { name.to_sym => @value } end @hash end end # Implements the {Enumerable} methods # module EnumerableMethods def each(&block) @value.each(&block) end def slice(*args) @value.slice(*args) end; alias :[] :slice def size @value.size end def <<(value) @value << value end def empty? @value.empty? end end module MethodDelegation # Looks up the corresponding class for a method being invoked, and initializes it # # @raise [NoMethodError] When the corresponding class cannot be found # def method_missing(name, *args, &block) klass = Utils.__camelize(name) if Filters.const_defined? klass @value << Filters.const_get(klass).new(*args, &block) else raise NoMethodError, "undefined method '#{name}' for #{self}" end end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filter.rb000066400000000000000000000026301361161326000301320ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Contains the classes for Elasticsearch filters # module Filters;end # Wraps the `filter` part of a search definition, aggregation, etc # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filters.html # class Filter def initialize(*args, &block) @block = block end # Looks up the corresponding class for a method being invoked, and initializes it # # @raise [NoMethodError] When the corresponding class cannot be found # def method_missing(name, *args, &block) klass = Utils.__camelize(name) if Filters.const_defined? klass @value = Filters.const_get(klass).new *args, &block else raise NoMethodError, "undefined method '#{name}' for #{self}" end end # Evaluates any block passed to the query # # @return [self] # def call @block.arity < 1 ? self.instance_eval(&@block) : @block.call(self) if @block self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash(options={}) call if @value @value.to_hash else {} end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/000077500000000000000000000000001361161326000277675ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/and.rb000066400000000000000000000023741361161326000310640ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A compound filter which matches documents by an intersection of individual filters. # # @note Since `and` is a keyword in Ruby, use the `_and` method in DSL definitions # # @example Pass the filters as a Hash # search do # query do # filtered do # filter do # _and filters: [ {term: { color: 'red' }}, {term: { size: 'xxl' }} ] # end # end # end # end # # @example Define the filters with a block # # search do # query do # filtered do # filter do # _and do # term color: 'red' # term size: 'xxl' # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-and-filter.html # class And include BaseComponent include BaseCompoundFilterComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/bool.rb000066400000000000000000000044021361161326000312470ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A compound filter which matches documents based on combinations of filters # # @example Defining a bool filter with multiple conditions # # search do # query do # filtered do # filter do # bool do # must do # term category: 'men' # end # # must do # term size: 'xxl' # end # # should do # term color: 'red' # end # # must_not do # term manufacturer: 'evil' # end # end # end # end # end # end # # See the integration test for a working example. # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-filter.html # class Bool include BaseComponent def must(*args, &block) @hash[name][:must] ||= [] value = Filter.new(*args, &block).to_hash @hash[name][:must].push(value).flatten! unless @hash[name][:must].include?(value) self end def must_not(*args, &block) @hash[name][:must_not] ||= [] value = Filter.new(*args, &block).to_hash @hash[name][:must_not].push(value).flatten! unless @hash[name][:must_not].include?(value) self end def should(*args, &block) @hash[name][:should] ||= [] value = Filter.new(*args, &block).to_hash @hash[name][:should].push(value).flatten! unless @hash[name][:should].include?(value) self end def to_hash @hash[name].update(@args.to_hash) if @args.respond_to?(:to_hash) if @block call else @hash[name] = @args unless @args.nil? || @args.empty? end @hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/exists.rb000066400000000000000000000013671361161326000316420ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents which have a non-`null` value in the specified field # (ie. the reverse of the `missing` filter) # # @example # # search do # query do # filtered do # filter do # exists field: 'occupation' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-exists-filter.html # class Exists include BaseComponent option_method :field end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_bounding_box.rb000066400000000000000000000024021361161326000336210ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents which fall into a "box" of the specified geographical coordinates # # @example # # search do # query do # filtered do # filter do # geo_bounding_box :location do # top_right "50.1815123678,14.7149200439" # bottom_left "49.9415476869,14.2162566185" # end # end # end # end # end # # See the integration test for a working example. # # Use eg. to visually define the bounding box. # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geo-bounding-box.html # class GeoBoundingBox include BaseComponent option_method :top_left option_method :bottom_right option_method :top_right option_method :bottom_left option_method :top option_method :left option_method :bottom option_method :right end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_distance.rb000066400000000000000000000034641361161326000327470ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents which fall into a specified geographical distance # # @example Define the filter with a hash # # search do # query do # filtered do # filter do # geo_distance location: '50.090223,14.399590', distance: '5km' # end # end # end # end # # @example Define the filter with a block # # search do # query do # filtered do # filter do # geo_distance :location do # lat '50.090223' # lon '14.399590' # distance '5km' # end # end # end # end # end # # See the integration test for a working example. # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geo-distance.html # class GeoDistance include BaseComponent option_method :distance, lambda { |*args| @hash[self.name.to_sym].update distance: args.pop } option_method :distance_type, lambda { |*args| @hash[self.name.to_sym].update distance_type: args.pop } option_method :lat, lambda { |*args| @hash[self.name.to_sym][@args].update lat: args.pop } option_method :lon, lambda { |*args| @hash[self.name.to_sym][@args].update lon: args.pop } def initialize(*args, &block) super @hash[self.name.to_sym] = { @args => {} } unless @args.empty? end end end end end end geo_distance_range.rb000066400000000000000000000014441361161326000340400ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filtersmodule Elasticsearch module DSL module Search module Filters # A filter which returns documents which fall into a specified geographical distance range # # @example Define the filter with a hash # # search do # query do # filtered do # filter do # geo_distance location: '50.090223,14.399590', gte: '2km', lte: '5km' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geo-distance.html # class GeoDistanceRange include BaseComponent option_method :lat option_method :lon end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_polygon.rb000066400000000000000000000021311361161326000326320ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents which fall into a specified geographical polygon # # @example # # search do # query do # filtered do # filter do # geo_polygon :location do # points [ # [14.2244355,49.9419006], # [14.2244355,50.1774301], # [14.7067869,50.1774301], # [14.7067869,49.9419006], # [14.2244355,49.9419006] # ] # end # end # end # end # end # # See the integration test for a working example. # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-geo-polygon-filter.html # class GeoPolygon include BaseComponent option_method :points end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_shape.rb000066400000000000000000000016311361161326000322470ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents which fall into a specified geographical shape # # @example # # search do # query do # filtered do # filter do # geo_shape :location do # shape type: 'envelope', # coordinates: [[14.2162566185,49.9415476869], [14.7149200439,50.1815123678]] # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-geo-shape-filter.html # class GeoShape include BaseComponent option_method :shape option_method :indexed_shape end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geohash_cell.rb000066400000000000000000000030171361161326000327320ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which translates lat/lon values into a geohash with the specified precision # and returns all documents which fall into it # # @example # # search do # query do # filtered do # filter do # geohash_cell :location do # lat '50.090223' # lon '14.399590' # precision '5km' # neighbors true # end # end # end # end # end # # See the integration test for a working example. # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/geohash-cell-filter.html # class GeohashCell include BaseComponent option_method :precision, lambda { |*args| @hash[self.name.to_sym].update precision: args.pop } option_method :lat, lambda { |*args| @hash[self.name.to_sym][@args].update lat: args.pop } option_method :lon, lambda { |*args| @hash[self.name.to_sym][@args].update lon: args.pop } option_method :neighbors, lambda { |*args| @hash[self.name.to_sym].update neighbors: args.pop } def initialize(*args, &block) super @hash[self.name.to_sym] = { @args => {} } unless @args.empty? end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/has_child.rb000066400000000000000000000040661361161326000322400ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns parent documents for children documents matching a query or a filter # # @example Return articles where John has commented # # search do # query do # filtered do # filter do # has_child do # type 'comment' # query do # match author: 'John' # end # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-has-child-filter.html # class HasChild include BaseComponent option_method :type option_method :min_children option_method :max_children # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? Elasticsearch::DSL::Search::Query.new(*args, &block) : args.first self end # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Elasticsearch::DSL::Search::Filter.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/has_parent.rb000066400000000000000000000040371361161326000324440ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns children documents for parent documents matching a query or a filter # # @example Return comments for articles about Ruby # # search do # query do # filtered do # filter do # has_parent do # type 'article' # query do # match title: 'Ruby' # end # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-has-parent-filter.html # class HasParent include BaseComponent option_method :parent_type option_method :score_mode # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Elasticsearch::DSL::Search::Query.new(*args, &block) : args.first self end # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Elasticsearch::DSL::Search::Filter.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/ids.rb000066400000000000000000000012751361161326000311000ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents matching the specified IDs # # @example # # search do # query do # filtered do # filter do # ids values: [1, 2, 3] # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-ids-filter.html # class Ids include BaseComponent option_method :type option_method :values end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/indices.rb000066400000000000000000000043231361161326000317340ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which executes a custom filter only for documents in specified indices, # and optionally another filter for documents in other indices # # @example # # search do # query do # filtered do # filter do # indices do # indices ['audio', 'video'] # # filter do # terms tags: ['music'] # end # # no_match_filter do # terms tags: ['music', 'audio', 'video'] # end # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-indices-filter.html # class Indices include BaseComponent option_method :indices # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Filter.new(*args, &block) : args.first self end # DSL method for building the `no_match_filter` part of the query definition # # @return [self] # def no_match_filter(*args, &block) @no_match_filter = block ? Filter.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end if @no_match_filter _no_match_filter = @no_match_filter.respond_to?(:to_hash) ? @no_match_filter.to_hash : @no_match_filter hash[self.name].update(no_match_filter: _no_match_filter) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/limit.rb000066400000000000000000000012331361161326000314310ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which limits the number of documents to evaluate # # @example # # search do # query do # filtered do # filter do # limit value: 100 # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-limit-filter.html # class Limit include BaseComponent option_method :value end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/match_all.rb000066400000000000000000000011551361161326000322420ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which matches on all documents # # @example # # search do # query do # filtered do # filter do # match_all # end # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-match-all-filter.html # class MatchAll include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/missing.rb000066400000000000000000000014741361161326000317730ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents which have a `null` value in the specified field # (ie. the reverse of the `exists` filter) # # @example # # search do # query do # filtered do # filter do # missing field: 'occupation' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-missing-filter.html # class Missing include BaseComponent option_method :field option_method :existence option_method :null_value end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/nested.rb000066400000000000000000000027171361161326000316050ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which executes another filter in the context of a nested document # # @example # # search do # query do # filtered do # filter do # nested do # path 'comments' # filter do # term 'comments.title' => 'Ruby' # end # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-nested-filter.html # class Nested include BaseComponent option_method :path # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Filter.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/not.rb000066400000000000000000000041011361161326000311100ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which takes out documents matching a filter from the results # # @note Since `not` is a keyword in Ruby, use the `_not` method in DSL definitions # # @example Pass the filter as a Hash # search do # query do # filtered do # filter do # _not term: { color: 'red' } # end # end # end # end # # @example Define the filter with a block # # search do # query do # filtered do # filter do # _not do # term color: 'red' # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-not-filter.html # class Not include BaseComponent # Looks up the corresponding class for a method being invoked, and initializes it # # @raise [NoMethodError] When the corresponding class cannot be found # def method_missing(name, *args, &block) klass = Utils.__camelize(name) if Filters.const_defined? klass @value = Filters.const_get(klass).new(*args, &block) else raise NoMethodError, "undefined method '#{name}' for #{self}" end end # Convert the component to a Hash # # A default implementation, DSL classes can overload it. # # @return [Hash] # def to_hash(options={}) case when (! @value || @value.empty?) && ! @block @hash = super when @block call @hash = { name.to_sym => @value.to_hash } end @hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/or.rb000066400000000000000000000023561361161326000307420ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A compound filter which matches documents by a union of individual filters. # # @note Since `or` is a keyword in Ruby, use the `_or` method in DSL definitions # # @example Pass the filters as a Hash # search do # query do # filtered do # filter do # _or filters: [ {term: { color: 'red' }}, {term: { size: 'xxl' }} ] # end # end # end # end # # @example Define the filters with a block # # search do # query do # filtered do # filter do # _or do # term color: 'red' # term size: 'xxl' # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-or-filter.html # class Or include BaseComponent include BaseCompoundFilterComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/prefix.rb000066400000000000000000000012261361161326000316120ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents where the field value a specified prefix # # @example # # search do # query do # filtered do # filter do # prefix path: '/usr/local' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-prefix-filter.html # class Prefix include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/query.rb000066400000000000000000000024661361161326000314710ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which wraps a query so it can be used as a filter # # @example # # search do # query do # filtered do # filter do # query do # query_string :title do # query 'Ruby OR Python' # end # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-filter.html # class Query include BaseComponent def initialize(*args, &block) super if block @query = Elasticsearch::DSL::Search::Query.new(*args, &block) @block = nil end end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(_query) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/range.rb000066400000000000000000000016651361161326000314200ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents that have terms in a specified range # # @example # # search do # query do # filtered do # filter do # range :age do # gte 10 # lte 20 # end # end # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-range-filter.html # class Range include BaseComponent option_method :gte option_method :gt option_method :lte option_method :lt option_method :boost option_method :time_zone option_method :format end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/regexp.rb000066400000000000000000000014241361161326000316070ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents matching the specified regular expression # # @example # # search do # query do # filtered do # filter do # regexp :path do # value '^/usr/?.*/var' # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-regexp-filter.html # class Regexp include BaseComponent option_method :value option_method :flags end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/script.rb000066400000000000000000000013561361161326000316250ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents matching the criteria defined with a script # # @example # # search do # query do # filtered do # filter do # script script: "doc['clicks'].value % 4 == 0" # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-script-filter.html # class Script include BaseComponent option_method :script option_method :params end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/term.rb000066400000000000000000000014251361161326000312650ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents matching the specified terms # # @example # # search do # query do # filtered do # filter do # term color: 'red' # end # end # end # end # # @note The specified terms are *not analyzed* (lowercased, stemmed, etc), # so they must match the indexed terms. # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-term-filter.html # class Term include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/terms.rb000066400000000000000000000014731361161326000314530ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents matching any term from the specified list of terms # # @example # # search do # query do # filtered do # filter do # terms tags: ['ruby', 'development'] # end # end # end # end # # @note The specified terms are *not analyzed* (lowercased, stemmed, etc), # so they must match the indexed terms. # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-filter.html # class Terms include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/type.rb000066400000000000000000000013371361161326000313010ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Filters # A filter which returns documents matching the specified type # # @example # # search do # query do # filtered do # filter do # type do # value 'article' # end # end # end # end # end # # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-type-filter.html # class Type include BaseComponent option_method :value end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/highlight.rb000066400000000000000000000045321361161326000306170ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Wraps the `highlight` part of a search definition # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html # class Highlight include BaseComponent def initialize(*args, &block) @value = args.pop || {} super end # Specify the fields to highlight # # @example # # search do # highlight do # fields [:title, :body] # field :comments.body if options[:comments] # end # end # def fields(value_or_name) value = case value_or_name when Hash value_or_name when Array value_or_name.reduce({}) { |sum, item| sum.update item.to_sym => {}; sum } else end (@value[:fields] ||= {}).update value self end # Specify a single field to highlight # # @example # # search do # highlight do # field :title, fragment_size: 0 # field :body if options[:comments] # end # end # def field(name, options={}) (@value[:fields] ||= {}).update name.to_sym => options end # Specify the opening tags for the highlighted snippets # def pre_tags(*value) @value[:pre_tags] = value.flatten end; alias_method :pre_tags=, :pre_tags # Specify the closing tags for the highlighted snippets # def post_tags(*value) @value[:post_tags] = value.flatten end; alias_method :post_tags=, :post_tags # Specify the `encoder` option for highlighting # def encoder(value) @value[:encoder] = value end; alias_method :encoder=, :encoder # Specify the `tags_schema` option for highlighting # def tags_schema(value) @value[:tags_schema] = value end; alias_method :tags_schema=, :tags_schema # Convert the definition to a Hash # # @return [Hash] # def to_hash call @hash = @value @hash end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/options.rb000066400000000000000000000023261361161326000303420ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Wraps the "extra" options of a search definition # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-body.html # class Options DSL_METHODS = [ :_source, :fields, :script_fields, :fielddata_fields, :rescore, :explain, :version, :indices_boost, :track_scores, :min_score ] def initialize(*args, &block) @hash = {} end # Defines a method for each valid search definition option # DSL_METHODS.each do |name| define_method name do |*args, &block| @hash[name] = args.pop end define_method name.to_s.gsub(/^_(.*)/, '\1') do |*args, &block| @hash[name] = args.pop end end # Returns true when there are no search options defined # def empty? @hash.empty? end # Convert the definition to a Hash # # @return [Hash] # def to_hash(options={}) @hash end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/000077500000000000000000000000001361161326000277745ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/bool.rb000066400000000000000000000046321361161326000312610ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A compound query which matches documents based on combinations of queries # # @example Defining a bool query with multiple conditions # # search do # query do # bool do # must do # term category: 'men' # end # # must do # term size: 'xxl' # end # # should do # term color: 'red' # end # # must_not do # term manufacturer: 'evil' # end # end # end # end # # See the integration test for a working example. # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html # class Bool include BaseComponent option_method :minimum_should_match option_method :boost def must(*args, &block) @hash[name][:must] ||= [] value = Query.new(*args, &block).to_hash @hash[name][:must].push(value).flatten! unless @hash[name][:must].include?(value) self end def must_not(*args, &block) @hash[name][:must_not] ||= [] value = Query.new(*args, &block).to_hash @hash[name][:must_not].push(value).flatten! unless @hash[name][:must_not].include?(value) self end def should(*args, &block) @hash[name][:should] ||= [] value = Query.new(*args, &block).to_hash @hash[name][:should].push(value).flatten! unless @hash[name][:should].include?(value) self end def filter(*args, &block) @hash[name][:filter] ||= [] if filter = block ? Filter.new(*args, &block) : args.first @hash[name][:filter] << filter.to_hash end self end def to_hash @hash[name].update(@args.to_hash) if @args.respond_to?(:to_hash) if @block call else @hash[name] = @args unless @args.nil? || @args.empty? end @hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/boosting.rb000066400000000000000000000015161361161326000321500ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which will decrease the score of documents matching the `negative` query # # @example # # search do # query do # boosting do # positive terms: { amenities: ['wifi', 'pets'] } # negative terms: { amenities: ['pool'] } # negative_boost 0.5 # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-boosting-query.html # class Boosting include BaseComponent option_method :positive option_method :negative option_method :negative_boost end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/common.rb000066400000000000000000000020451361161326000316120ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which executes the search for low frequency terms first, and high frequency ("common") # terms second # # @example # # search do # query do # common :body do # query 'shakespeare to be or not to be' # end # end # end # # This query is frequently used when a stopwords-based approach loses too much recall and/or precision. # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-common-terms-query.html # class Common include BaseComponent option_method :query option_method :cutoff_frequency option_method :low_freq_operator option_method :minimum_should_match option_method :boost option_method :analyzer option_method :disable_coord end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/constant_score.rb000066400000000000000000000033601361161326000333470ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which wraps another query or filter and returns a constant score for matching documents # # @example # # search do # query do # constant_score do # query do # match content: 'Twitter' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/ignoring-tfidf.html # class ConstantScore include BaseComponent option_method :boost # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Filter.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/dis_max.rb000066400000000000000000000016061361161326000317500ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which will score the documents based on the highest score of any individual specified query, # not by summing the scores (as eg. a `bool` query would) # # @example # # search do # query do # dis_max do # queries [ # { match: { title: 'albino' } }, # { match: { content: 'elephant' } } # ] # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/_best_fields.html # class DisMax include BaseComponent option_method :queries option_method :boost option_method :tie_breaker end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/exists.rb000066400000000000000000000021671361161326000316460ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # Returns documents that have at least one non-null value in the field. # # @example Find documents with non-empty "name" property # # search do # query do # exists do # field 'name' # end # end # end # # @note The "Exists" query can be used as a "Missing" query in a "Bool" query "Must Not" context. # # @example Find documents with an empty "name" property # # search do # query do # bool do # must_not do # exists do # field 'name' # end # end # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/5.1/query-dsl-exists-query.html # class Exists include BaseComponent option_method :field end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/filtered.rb000066400000000000000000000042711361161326000321230ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which allows to combine a query with a filter # # @note It's possible and common to define just the `filter` part of the search definition, # for a structured search use case. # # @example Find documents about Twitter published last month # # search do # query do # filtered do # query do # multi_match do # query 'twitter' # fields [ :title, :abstract, :content ] # end # end # filter do # range :published_on do # gte 'now-1M/M' # end # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html # class Filtered include BaseComponent option_method :strategy # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Filter.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/function_score.rb000066400000000000000000000056671361161326000333570ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which allows to modify the score of documents matching the query, # either via built-in functions or a custom script # # @example Find documents with specific amenities, boosting documents within a certain # price range and geogprahical location # # search do # query do # function_score do # filter do # terms amenities: ['wifi', 'pets'] # end # functions << { gauss: { price: { origin: 100, scale: 200 } } } # functions << { gauss: { location: { origin: '50.090223,14.399590', scale: '5km' } } } # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/guide/current/function-score-query.html # class FunctionScore include BaseComponent option_method :script_score option_method :boost option_method :max_boost option_method :score_mode option_method :boost_mode def initialize(*args, &block) super @functions = [] end # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # DSL method for building the `filter` part of the query definition # # @return [self] # def filter(*args, &block) @filter = block ? Filter.new(*args, &block) : args.first self end # DSL method for building the `functions` part of the query definition # # @return [Array] # def functions(value=nil) if value @functions = value else @functions end end # Set the `functions` part of the query definition # # @return [Array] # def functions=(value) @functions = value end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end if @filter _filter = @filter.respond_to?(:to_hash) ? @filter.to_hash : @filter hash[self.name].update(filter: _filter) end unless @functions.empty? hash[self.name].update(functions: @functions) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/fuzzy.rb000066400000000000000000000021161361161326000315100ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which uses a Levenshtein distance on string fields and plus-minus margin on numerical # fields to match documents # # @example # # search do # query do # fuzzy :name do # value 'Eyjafjallajökull' # end # end # end # # @example # # search do # query do # fuzzy :published_on do # value '2014-01-01' # fuzziness '7d' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html # class Fuzzy include BaseComponent option_method :value option_method :boost option_method :fuzziness option_method :prefix_length option_method :max_expansions end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/fuzzy_like_this.rb000066400000000000000000000016761361161326000335550ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents which are similar to the specified text # # @example # # search do # query do # fuzzy_like_this do # like_text 'Eyjafjallajökull' # fields [:title, :abstract, :content] # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-flt-query.html # class FuzzyLikeThis include BaseComponent option_method :fields option_method :like_text option_method :fuzziness option_method :analyzer option_method :max_query_terms option_method :prefix_length option_method :boost option_method :ignore_tf end end end end end fuzzy_like_this_field.rb000066400000000000000000000016451361161326000346350ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queriesmodule Elasticsearch module DSL module Search module Queries # A query which returns documents which are similar to the specified text, # executed on a single field # # @example # # search do # query do # fuzzy_like_this_field :content do # like_text 'Eyjafjallajökull' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-flt-field-query.html # class FuzzyLikeThisField include BaseComponent option_method :like_text option_method :fuzziness option_method :analyzer option_method :max_query_terms option_method :prefix_length option_method :boost option_method :ignore_tf end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/geo_shape.rb000066400000000000000000000014411361161326000322530ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents which fall into a specified geographical shape # # @example # # search do # query do # geo_shape :location do # shape type: 'envelope', # coordinates: [[14.2162566185,49.9415476869], [14.7149200439,50.1815123678]] # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-geo-shape-query.html # class GeoShape include BaseComponent option_method :shape option_method :indexed_shape end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/has_child.rb000066400000000000000000000027421361161326000322440ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns parent documents for children documents matching a query # # @example Return articles where John has commented # # search do # query do # has_child do # type 'comment' # query do # match author: 'John' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-has-child-query.html # class HasChild include BaseComponent option_method :type option_method :score_mode option_method :min_children option_method :max_children # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/has_parent.rb000066400000000000000000000026731361161326000324550ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns children documents for parent documents matching a query # # @example Return comments for articles about Ruby # # search do # query do # has_parent do # type 'article' # query do # match title: 'Ruby' # end # end # end # end # # @example # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-has-parent-query.html # class HasParent include BaseComponent option_method :parent_type option_method :score_mode # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/ids.rb000066400000000000000000000011151361161326000310760ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching the specified IDs # # @example # # search do # query do # ids values: [1, 2, 3] # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-ids-query.html # class Ids include BaseComponent option_method :type option_method :values end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/indices.rb000066400000000000000000000016321361161326000317410ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which executes a custom query only for documents in specified indices, # and optionally another query for documents in other indices # # @example # # search do # query do # indices do # indices ['audio', 'video'] # query match: { artist: 'Fugazi' } # no_match_query match: { label: 'Dischord' } # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-indices-query.html # class Indices include BaseComponent option_method :indices option_method :query option_method :no_match_query end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/match.rb000066400000000000000000000024321361161326000314160ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A simple to use, yet sophisticated query which returns documents matching the specified terms, # taking into account field types, analyzers, etc. and allowing to search in phrase, prefix, fuzzy modes # # @example # # search do # query do # match :content do # query 'how to fix my printer' # operator 'and' # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-match-query.html # class Match include BaseComponent option_method :query option_method :operator option_method :minimum_should_match option_method :type option_method :boost option_method :fuzziness option_method :prefix_length option_method :max_expansions option_method :fuzzy_rewrite option_method :analyzer option_method :lenient option_method :zero_terms_query option_method :cutoff_frequency option_method :max_expansions end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/match_all.rb000066400000000000000000000010321361161326000322410ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which matches all documents # # @example # # search do # query do # match_all # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-match-all-query.html # class MatchAll include BaseComponent option_method :boost end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/match_phrase.rb000066400000000000000000000014411361161326000327570ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query that analyzes the text and creates a phrase query out of the analyzed text # # @example # # search do # query do # match_phrase :content do # query 'example content' # analyzer 'standard' # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html # class MatchPhrase include BaseComponent option_method :query option_method :analyzer option_method :boost option_method :slop end end end end end match_phrase_prefix.rb000066400000000000000000000014501361161326000342550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queriesmodule Elasticsearch module DSL module Search module Queries # The same as match_phrase, except that it allows for prefix matches on the last term in the text # # @example # # search do # query do # match_phrase_prefix :content do # query 'example content' # max_expansions 10 # end # end # end # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase-prefix.html # class MatchPhrasePrefix include BaseComponent option_method :query option_method :boost option_method :max_expansions end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/more_like_this.rb000066400000000000000000000035061361161326000333220ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents which are similar to the specified text or documents # # @example Find documents similar to the provided text # # search do # query do # more_like_this do # like ['Eyjafjallajökull'] # fields [:title, :abstract, :content] # end # end # end # # # @example Find documents similar to the specified documents # # search do # query do # more_like_this do # like [{_id: 1}, {_id: 2}, {_id: 3}] # fields [:title, :abstract] # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-mlt-query.html # class MoreLikeThis include BaseComponent # like/unlike is since 2.0.0 option_method :like option_method :unlike # before 2.0.0 the following 3 options were available option_method :like_text option_method :docs option_method :ids option_method :fields option_method :min_term_freq option_method :max_query_terms option_method :include option_method :exclude option_method :percent_terms_to_match option_method :stop_words option_method :min_doc_freq option_method :max_doc_freq option_method :min_word_length option_method :max_word_length option_method :boost_terms option_method :boost option_method :analyzer end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/multi_match.rb000066400000000000000000000023361361161326000326330ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which allows to use the `match` query on multiple fields # # @example # # search do # query do # multi_match do # query 'how to fix my printer' # fields [:title, :abstract, :content] # operator 'and' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html # class MultiMatch include BaseComponent option_method :analyzer option_method :boost option_method :cutoff_frequency option_method :fields option_method :fuzziness option_method :max_expansions option_method :minimum_should_match option_method :operator option_method :prefix_length option_method :query option_method :rewrite option_method :slop option_method :type option_method :use_dis_max option_method :zero_terms_query end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/nested.rb000066400000000000000000000026751361161326000316150ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns the root documents for nested documents matching the specified query # # @example Return articles where John has commented # # search do # query do # nested do # path 'comments' # query do # match user: 'John' # end # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html # class Nested include BaseComponent option_method :path option_method :score_mode option_method :inner_hits # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/prefix.rb000066400000000000000000000011511361161326000316140ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching a specified prefix # # @example # # search do # query do # prefix :title do # value 'dis' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html # class Prefix include BaseComponent option_method :value option_method :boost end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/query_string.rb000066400000000000000000000032351361161326000330570ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching a specified expression in the Lucene Query String syntax # # @example # # search do # query do # query_string do # query '(mortgage OR (bank AND loan)) AND published_on:[2013-01-01 TO 2013-12-31]' # fields [:title, :content] # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html # @see http://lucene.apache.org/core/2_9_4/queryparsersyntax.html # class QueryString include BaseComponent option_method :query option_method :fields option_method :type option_method :default_field option_method :default_operator option_method :analyzer option_method :allow_leading_wildcard option_method :lowercase_expanded_terms option_method :enable_position_increments option_method :fuzzy_max_expansions option_method :fuzziness option_method :fuzzy_prefix_length option_method :phrase_slop option_method :boost option_method :analyze_wildcard option_method :auto_generate_phrase_queries option_method :minimum_should_match option_method :lenient option_method :locale option_method :use_dis_max option_method :tie_breaker option_method :time_zone end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/range.rb000066400000000000000000000022521361161326000314160ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching the specified range # # @example Find documents within a numeric range # # search do # query do # range :age do # gte 10 # lte 20 # end # end # end # # @example Find documents published within a date range # # search do # query do # range :published_on do # gte '2013-01-01' # lte 'now' # time_zone '+1:00' # end # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-range-query.html # class Range include BaseComponent option_method :gte option_method :gt option_method :lte option_method :lt option_method :boost option_method :time_zone option_method :format end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/regexp.rb000066400000000000000000000012571361161326000316200ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which matches documents matching a regular expression # # @example # # search do # query do # regexp :path do # value '^/usr/?.*/var' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html # class Regexp include BaseComponent option_method :value option_method :boost option_method :flags end end end end end simple_query_string.rb000066400000000000000000000021351361161326000343470ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queriesmodule Elasticsearch module DSL module Search module Queries # A query which returns documents matching a simplified query string syntax # # @example # # search do # query do # simple_query_string do # query 'disaster -health' # fields ['title^5', 'abstract', 'content'] # default_operator 'and' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html # class SimpleQueryString include BaseComponent option_method :query option_method :fields option_method :default_operator option_method :analyzer option_method :flags option_method :analyze_wildcard option_method :lenient option_method :minimum_should_match option_method :quote_field_suffix option_method :all_fields end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_first.rb000066400000000000000000000013421361161326000324710ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents having spans in the beginning of the field # # @example # # search do # query do # span_first match: { span_term: { title: 'disaster' } }, end: 10 # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-first-query.html # @see https://lucene.apache.org/core/5_0_0/core/org/apache/lucene/search/spans/package-summary.html # class SpanFirst include BaseComponent option_method :match end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_multi.rb000066400000000000000000000013251361161326000324750ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching a multi-term query as a span query # # @example # # search do # query do # span_multi match: { prefix: { name: 'jo' } } # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-multi-term-query.html # @see https://lucene.apache.org/core/5_0_0/core/org/apache/lucene/search/spans/package-summary.html # class SpanMulti include BaseComponent option_method :match end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_near.rb000066400000000000000000000016101361161326000322650ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching spans near each other # # @example # # search do # query do # span_near clauses: [ { span_term: { title: 'disaster' } }, { span_term: { title: 'health' } } ], # slop: 10 # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-near-query.html # @see https://lucene.apache.org/core/5_0_0/core/org/apache/lucene/search/spans/package-summary.html # class SpanNear include BaseComponent option_method :span_near option_method :slop option_method :in_order option_method :collect_payloads end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_not.rb000066400000000000000000000016311361161326000321430ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which discards matching documents which overlap with another query # # @example # # search do # query do # span_not include: { span_term: { title: 'disaster' } }, # exclude: { span_term: { title: 'health' } } # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-not-query.html # @see https://lucene.apache.org/core/5_0_0/core/org/apache/lucene/search/spans/package-summary.html # class SpanNot include BaseComponent option_method :include option_method :exclude option_method :pre option_method :post option_method :dist end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_or.rb000066400000000000000000000013701361161326000317630ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching the union of provided queries # # @example # # search do # query do # span_or clauses: [ { span_term: { title: 'disaster' } }, { span_term: { title: 'health' } } ] # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-or-query.html # @see https://lucene.apache.org/core/5_0_0/core/org/apache/lucene/search/spans/package-summary.html # class SpanOr include BaseComponent option_method :clauses end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_term.rb000066400000000000000000000012211361161326000323050ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents having a span containing a term # # @example # # search do # query do # span_term title: 'disaster' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-term-query.html # @see https://lucene.apache.org/core/5_0_0/core/org/apache/lucene/search/spans/package-summary.html # class SpanTerm include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/template.rb000066400000000000000000000013411361161326000321330ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which allows to use Mustache templates for query definitions # # @example # # search do # query do # template do # query match: { content: '{query_string}' } # params query_string: 'twitter' # end # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-template-query.html # class Template include BaseComponent option_method :query option_method :params end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/term.rb000066400000000000000000000011621361161326000312700ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching the specified term # # @note The specified term is *not analyzed* (lowercased, stemmed, etc) # # @example # # search do # query do # term category: 'Opinion' # end # end # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-term-query.html # class Term include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/terms.rb000066400000000000000000000012101361161326000314450ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching the specified terms # # @note The specified terms are *not analyzed* (lowercased, stemmed, etc) # # @example # # search do # query do # terms categories: ['World', 'Opinion'] # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-common-terms-query.html # class Terms include BaseComponent end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/top_children.rb000066400000000000000000000030441361161326000327740ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A filter which returns parent documents for children documents matching a query # # @example Return articles with comments mentioning 'twitter', summing the score # # search do # query do # top_children do # type 'comment' # query match: { body: 'twitter' } # score 'sum' # end # end # end # # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-top-children-query.html # class TopChildren include BaseComponent option_method :type option_method :score option_method :factor option_method :incremental_factor option_method :_scope # DSL method for building the `query` part of the query definition # # @return [self] # def query(*args, &block) @query = block ? @query = Query.new(*args, &block) : args.first self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash hash = super if @query _query = @query.respond_to?(:to_hash) ? @query.to_hash : @query hash[self.name].update(query: _query) end hash end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/wildcard.rb000066400000000000000000000012601361161326000321110ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Queries # A query which returns documents matching a wildcard expression # # @note The expression is *not analyzed* (lowercased, stemmed, etc) # # @example # # search do # query do # wildcard title: 'tw*' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html # class Wildcard include BaseComponent option_method :value option_method :boost end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/query.rb000066400000000000000000000025731361161326000300200ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Contains the classes for Elasticsearch queries # module Queries;end # Wraps the `query` part of a search definition # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html # class Query def initialize(*args, &block) @block = block end # Looks up the corresponding class for a method being invoked, and initializes it # # @raise [NoMethodError] When the corresponding class cannot be found # def method_missing(name, *args, &block) klass = Utils.__camelize(name) if Queries.const_defined? klass @value = Queries.const_get(klass).new *args, &block else raise NoMethodError, "undefined method '#{name}' for #{self}" end end # Evaluates any block passed to the query # # @return [self] # def call @block.arity < 1 ? self.instance_eval(&@block) : @block.call(self) if @block self end # Converts the query definition to a Hash # # @return [Hash] # def to_hash(options={}) call if @value @value.to_hash else {} end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/sort.rb000066400000000000000000000024331361161326000276350ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Wraps the `sort` part of a search definition # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-sort.html # class Sort include BaseComponent def initialize(*args, &block) @value ||= [] super end # DSL method to specify sorting item # # @example # # search do # sort do # by :category # by :clicks, order: 'desc' # end # end # def by(name, direction=nil) @value << ( direction ? { name => direction } : name ) self end # Convert the definition to a Hash # # @return [Hash] # def to_hash if @block call unless @block_called @block_called = true else @value << @args if @args && !@args.empty? && ! @value.include?(@args) end @hash = @value.flatten @hash end # Return whether the definition is empty # # @return [Boolean] # def empty? to_hash.empty? end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/search/suggest.rb000066400000000000000000000011331361161326000303230ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Wraps the `suggest` part of a search definition # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html # class Suggest include BaseComponent def initialize(key, options={}, &block) @key = key @options = options @block = block end # Convert the definition to a Hash # # @return [Hash] # def to_hash { @key => @options } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/utils.rb000066400000000000000000000007121361161326000265370ustar00rootroot00000000000000module Elasticsearch module DSL # Generic utility methods # module Utils # Camelize an underscored string # # A lightweight version of ActiveSupport's `camelize` # # @example # __camelize('query_string') # # => 'QueryString' # # @api private # def __camelize(string) string.to_s.split('_').map(&:capitalize).join end extend self end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/lib/elasticsearch/dsl/version.rb000066400000000000000000000001021361161326000270550ustar00rootroot00000000000000module Elasticsearch module DSL VERSION = "0.1.5" end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/000077500000000000000000000000001361161326000216425ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/000077500000000000000000000000001361161326000244545ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/000077500000000000000000000000001361161326000252365ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/000077500000000000000000000000001361161326000265035ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/000077500000000000000000000000001361161326000311555ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/avg_spec.rb000066400000000000000000000007011361161326000332670ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Avg do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(avg: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(avg: { foo: 'bar' }) end end end cardinality_spec.rb000066400000000000000000000033661361161326000347500ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Cardinality do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(cardinality: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:cardinality][:foo][:field]).to eq('bar') end end describe '#precision_threshold' do before do search.precision_threshold('bar') end it 'applies the option' do expect(search.to_hash[:cardinality][:foo][:precision_threshold]).to eq('bar') end end describe '#rehash' do before do search.rehash('skip') end it 'applies the option' do expect(search.to_hash[:cardinality][:foo][:rehash]).to eq('skip') end end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:cardinality][:foo][:script]).to eq('bar') end end describe '#params' do before do search.params('bar') end it 'applies the option' do expect(search.to_hash[:cardinality][:foo][:params]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ cardinality: { foo: { field: 'bar' } } }) end end end end children_spec.rb000066400000000000000000000015741361161326000342340ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Children do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(children: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#type' do before do search.type('bar') end it 'applies the option' do expect(search.to_hash[:children][:foo][:type]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do type 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ children: { foo: { type: 'bar' } } }) end end end end date_histogram_spec.rb000066400000000000000000000066471361161326000354440ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::DateHistogram do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(date_histogram: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:field]).to eq('bar') end end describe '#interval' do before do search.interval('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:interval]).to eq('bar') end end describe '#pre_zone' do before do search.pre_zone('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:pre_zone]).to eq('bar') end end describe '#post_zone' do before do search.post_zone('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:post_zone]).to eq('bar') end end describe '#time_zone' do before do search.time_zone('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:time_zone]).to eq('bar') end end describe '#pre_zone_adjust_large_interval' do before do search.pre_zone_adjust_large_interval('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:pre_zone_adjust_large_interval]).to eq('bar') end end describe '#pre_offest' do before do search.pre_offset('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:pre_offset]).to eq('bar') end end describe '#post_offset' do before do search.post_offset('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:post_offset]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:format]).to eq('bar') end end describe '#min_doc_count' do before do search.min_doc_count('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:min_doc_count]).to eq('bar') end end describe '#extended_bounds' do before do search.extended_bounds('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:extended_bounds]).to eq('bar') end end describe '#order' do before do search.order('bar') end it 'applies the option' do expect(search.to_hash[:date_histogram][:foo][:order]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' interval 'day' format 'yyyy-MM-dd' end end it 'executes the block' do expect(search.to_hash).to eq(date_histogram: { field: 'bar', interval: 'day', format: 'yyyy-MM-dd' }) end end end end date_range_spec.rb000066400000000000000000000025531361161326000345330ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::DateRange do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(date_range: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:date_range][:foo][:field]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:date_range][:foo][:format]).to eq('bar') end end describe '#ranges' do before do search.ranges('bar') end it 'applies the option' do expect(search.to_hash[:date_range][:foo][:ranges]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' ranges [ {to: 'foo'}, {from: 'bar'} ] end end it 'executes the block' do expect(search.to_hash).to eq(date_range: { field: 'bar', ranges: [ {to: 'foo'}, {from: 'bar'} ] }) end end end end extended_stats_spec.rb000066400000000000000000000007411361161326000354550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::ExtendedStats do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(extended_stats: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(extended_stats: { foo: 'bar' }) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/filter_spec.rb000066400000000000000000000012731361161326000340040ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Filter do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(filter: {}) end end context 'when another aggregation is nested' do let(:search) do described_class.new(terms: { foo: 'bar' }) do aggregation :sum_clicks do sum moo: 'bam' end end end it 'nests the aggregation in the hash' do expect(search.to_hash).to eq(filter: { terms: { foo: 'bar' } }, aggregations: { sum_clicks: { sum: { moo: 'bam' } } }) end end end filters_spec.rb000066400000000000000000000027541361161326000341150ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Filters do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(filters: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#filters' do before do search.filters(foo: 'bar') end it 'applies the option' do expect(search.to_hash[:filters][:filters][:foo]).to eq('bar') end end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(filters: { foo: 'bar' }) end context 'when filters are passed' do let(:search) do described_class.new(filters: { foo: 'bar' }) end it 'defines filters' do expect(search.to_hash).to eq(filters: { filters: { foo: 'bar' } }) end end end context 'when another aggregation is nested' do let(:search) do described_class.new do filters foo: { terms: { foo: 'bar' } } aggregation :sum_clicks do sum moo: 'bam' end end end it 'nests the aggregation in the hash' do expect(search.to_hash).to eq(filters: { filters: { foo: { terms: { foo: 'bar' } } } }, aggregations: { sum_clicks: { sum: { moo: 'bam' } } }) end end end geo_bounds_spec.rb000066400000000000000000000021341361161326000345610ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::GeoBounds do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_bounds: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounds][:foo][:field]).to eq('bar') end end describe '#wrap_longitude' do before do search.wrap_longitude('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounds][:foo][:wrap_longitude]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(geo_bounds: { field: 'bar' }) end end end end geo_distance_spec.rb000066400000000000000000000037071361161326000350700ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::GeoDistance do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_distance: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:field]).to eq('bar') end end describe '#origin' do before do search.origin('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:origin]).to eq('bar') end end describe '#ranges' do before do search.ranges('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:ranges]).to eq('bar') end end describe '#unit' do before do search.unit('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:unit]).to eq('bar') end end describe '#distance_type' do before do search.distance_type('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:distance_type]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' origin lat: 50, lon: 5 ranges [ { to: 50 }, { from: 50, to: 100 }, { from: 100 } ] end end it 'executes the block' do expect(search.to_hash).to eq(geo_distance: { field: 'bar', origin: { lat: 50, lon: 5 }, ranges: [ { to: 50 }, { from: 50, to: 100 }, { from: 100 } ] }) end end end end geo_grid_spec.rb000066400000000000000000000030431361161326000342140ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::GeohashGrid do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(geohash_grid: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:geohash_grid][:foo][:field]).to eq('bar') end end describe '#precision' do before do search.precision('bar') end it 'applies the option' do expect(search.to_hash[:geohash_grid][:foo][:precision]).to eq('bar') end end describe '#size' do before do search.size('bar') end it 'applies the option' do expect(search.to_hash[:geohash_grid][:foo][:size]).to eq('bar') end end describe '#shard_size' do before do search.shard_size('bar') end it 'applies the option' do expect(search.to_hash[:geohash_grid][:foo][:shard_size]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' precision 5 end end it 'executes the block' do expect(search.to_hash).to eq(geohash_grid: { field: 'bar', precision: 5 }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/global_spec.rb000066400000000000000000000015731361161326000337620ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Global do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(global: {}) end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do end end it 'executes the block' do expect(search.to_hash).to eq(global: {}) end end context 'when another aggregation is nested' do let(:search) do described_class.new do aggregation :foo do terms field: "bar" end end end it 'nests the aggregation in the hash' do expect(search.to_hash).to eq(aggregations: { foo: { terms: { field: "bar" } } }, global: {}) end end end end historgram_spec.rb000066400000000000000000000037121361161326000346170ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Histogram do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(histogram: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:histogram][:foo][:field]).to eq('bar') end end describe '#interval' do before do search.interval('bar') end it 'applies the option' do expect(search.to_hash[:histogram][:foo][:interval]).to eq('bar') end end describe '#min_doc_count' do before do search.min_doc_count('bar') end it 'applies the option' do expect(search.to_hash[:histogram][:foo][:min_doc_count]).to eq('bar') end end describe '#extended_bounds' do before do search.extended_bounds('bar') end it 'applies the option' do expect(search.to_hash[:histogram][:foo][:extended_bounds]).to eq('bar') end end describe '#order' do before do search.order('bar') end it 'applies the option' do expect(search.to_hash[:histogram][:foo][:order]).to eq('bar') end end describe '#keyed' do before do search.keyed('bar') end it 'applies the option' do expect(search.to_hash[:histogram][:foo][:keyed]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' interval 5 end end it 'executes the block' do expect(search.to_hash).to eq(histogram: { field: 'bar', interval: 5 }) end end end end ip_range_spec.rb000066400000000000000000000030131361161326000342160ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::IpRange do let(:search) do described_class.new end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(ip_range: { foo: 'bar' }) end context 'when args are passed' do let(:search) do described_class.new(field: 'test', ranges: [ {to: 'foo'}, {from: 'bar'} ]) end it 'defines filters' do expect(search.to_hash).to eq(ip_range: { field: 'test', ranges: [ {to: 'foo'}, {from: 'bar'} ] }) end end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:ip_range][:foo][:field]).to eq('bar') end end describe '#ranges' do before do search.ranges('bar') end it 'applies the option' do expect(search.to_hash[:ip_range][:foo][:ranges]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' ranges [ {to: 'foo'}, {from: 'bar'} ] end end it 'executes the block' do expect(search.to_hash).to eq(ip_range: { field: 'bar', ranges: [ {to: 'foo'}, {from: 'bar'} ] }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/max_spec.rb000066400000000000000000000007011361161326000332770ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Max do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(max: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(max: { foo: 'bar' }) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/min_spec.rb000066400000000000000000000007011361161326000332750ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Min do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(min: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(min: { foo: 'bar' }) end end end missing_spec.rb000066400000000000000000000022221361161326000341040ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Missing do let(:search) do described_class.new end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(missing: { foo: 'bar' }) end context 'when args are passed' do let(:search) do described_class.new(field: 'test') end it 'defines filters' do expect(search.to_hash).to eq(missing: { field: 'test' }) end end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:missing][:foo][:field]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(missing: { field: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/nested_spec.rb000066400000000000000000000025041361161326000337770ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Nested do let(:search) do described_class.new end context '#initialize' do let(:search) do described_class.new(path: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(nested: { path: 'bar' }) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#path' do before do search.path('bar') end it 'applies the option' do expect(search.to_hash[:nested][:foo][:path]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do path 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(nested: { path: 'bar' }) end end context 'when another aggregation is nested' do let(:search) do described_class.new do path 'bar' aggregation :min_price do min field: 'bam' end end end it 'nests the aggregation in the hash' do expect(search.to_hash).to eq(nested: { path: 'bar' }, aggregations: { min_price: { min: { field: 'bam' } } }) end end end end percentile_ranks_spec.rb000066400000000000000000000041131361161326000357640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::PercentileRanks do let(:search) do described_class.new end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(percentile_ranks: { foo: 'bar' }) end context 'when args are passed' do let(:search) do described_class.new(field: 'test') end it 'defines filters' do expect(search.to_hash).to eq(percentile_ranks: { field: 'test' }) end end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:percentile_ranks][:foo][:field]).to eq('bar') end end describe '#values' do before do search.values('bar') end it 'applies the option' do expect(search.to_hash[:percentile_ranks][:foo][:values]).to eq('bar') end end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:percentile_ranks][:foo][:script]).to eq('bar') end end describe '#params' do before do search.params('bar') end it 'applies the option' do expect(search.to_hash[:percentile_ranks][:foo][:params]).to eq('bar') end end describe '#compression' do before do search.compression('bar') end it 'applies the option' do expect(search.to_hash[:percentile_ranks][:foo][:compression]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' values [5, 10] end end it 'executes the block' do expect(search.to_hash).to eq(percentile_ranks: { field: 'bar', values: [5, 10] }) end end end end percentiles_spec.rb000066400000000000000000000037731361161326000347640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Percentiles do let(:search) do described_class.new end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(percentiles: { foo: 'bar' }) end context 'when args are passed' do let(:search) do described_class.new(field: 'test') end it 'defines filters' do expect(search.to_hash).to eq(percentiles: { field: 'test' }) end end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:percentiles][:foo][:field]).to eq('bar') end end describe '#percents' do before do search.percents('bar') end it 'applies the option' do expect(search.to_hash[:percentiles][:foo][:percents]).to eq('bar') end end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:percentiles][:foo][:script]).to eq('bar') end end describe '#params' do before do search.params('bar') end it 'applies the option' do expect(search.to_hash[:percentiles][:foo][:params]).to eq('bar') end end describe '#compression' do before do search.compression('bar') end it 'applies the option' do expect(search.to_hash[:percentiles][:foo][:compression]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(percentiles: { field: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipeline/000077500000000000000000000000001361161326000327625ustar00rootroot00000000000000avg_bucket_spec.rb000066400000000000000000000025131361161326000363550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::AvgBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(avg_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:avg_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('skip') end it 'applies the option' do expect(search.to_hash[:avg_bucket][:foo][:gap_policy]).to eq('skip') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:avg_bucket][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ avg_bucket: { foo: { format: 'bar' } } }) end end end end bucket_script_spec.rb000066400000000000000000000030571361161326000371100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::BucketScript do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(bucket_script: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:bucket_script][:foo][:buckets_path]).to eq('bar') end end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:bucket_script][:foo][:script]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('skip') end it 'applies the option' do expect(search.to_hash[:bucket_script][:foo][:gap_policy]).to eq('skip') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:bucket_script][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ bucket_script: { foo: { format: 'bar' } } }) end end end end bucket_selector_spec.rb000066400000000000000000000025631361161326000374250ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::BucketSelector do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(bucket_selector: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:bucket_selector][:foo][:buckets_path]).to eq('bar') end end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:bucket_selector][:foo][:script]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('skip') end it 'applies the option' do expect(search.to_hash[:bucket_selector][:foo][:gap_policy]).to eq('skip') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do gap_policy 'skip' end end it 'executes the block' do expect(search.to_hash).to eq({ bucket_selector: { foo: { gap_policy: 'skip' } } }) end end end end cumulative_sum_spec.rb000066400000000000000000000022021361161326000373000ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::CumulativeSum do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(cumulative_sum: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:cumulative_sum][:foo][:buckets_path]).to eq('bar') end end describe '#script' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:cumulative_sum][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ cumulative_sum: { foo: { format: 'bar' } } }) end end end end derivative_spec.rb000066400000000000000000000025121361161326000364040ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Derivative do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(derivative: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:derivative][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:derivative][:foo][:gap_policy]).to eq('bar') end end describe '#script' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:derivative][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ derivative: { foo: { format: 'bar' } } }) end end end end extended_stats_bucket_spec.rb000066400000000000000000000026121361161326000406160ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::ExtendedStatsBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(extended_stats_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:extended_stats_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:extended_stats_bucket][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:extended_stats_bucket][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ extended_stats_bucket: { foo: { format: 'bar' } } }) end end end end max_bucket_spec.rb000066400000000000000000000025111361161326000363630ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::MaxBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(max_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:max_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:max_bucket][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:max_bucket][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ max_bucket: { foo: { format: 'bar' } } }) end end end end min_bucket_spec.rb000066400000000000000000000025111361161326000363610ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::MinBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(min_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:min_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:min_bucket][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:min_bucket][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ min_bucket: { foo: { format: 'bar' } } }) end end end end moving_avg_test_spec.rb000066400000000000000000000042241361161326000374370ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::MovingAvg do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(moving_avg: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:gap_policy]).to eq('bar') end end describe '#minimize' do before do search.minimize(false) end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:minimize]).to eq(false) end end describe '#model' do before do search.model('simple') end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:model]).to eq('simple') end end describe '#settings' do before do search.settings(period: 7) end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:settings]).to eq(period: 7) end end describe '#window' do before do search.window(5) end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:window]).to eq(5) end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:moving_avg][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ moving_avg: { foo: { format: 'bar' } } }) end end end end percentiles_bucket_spec.rb000066400000000000000000000032041361161326000401130ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::PercentilesBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(percentiles_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:percentiles_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:percentiles_bucket][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:percentiles_bucket][:foo][:format]).to eq('bar') end end describe '#percents' do before do search.percents([ 1, 5, 25, 50, 75, 95, 99 ]) end it 'applies the option' do expect(search.to_hash[:percentiles_bucket][:foo][:percents]).to eq([ 1, 5, 25, 50, 75, 95, 99 ]) end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ percentiles_bucket: { foo: { format: 'bar' } } }) end end end end serial_diff_spec.rb000066400000000000000000000030161361161326000365110ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::SerialDiff do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(serial_diff: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:serial_diff][:foo][:buckets_path]).to eq('bar') end end describe '#lag' do before do search.lag(1) end it 'applies the option' do expect(search.to_hash[:serial_diff][:foo][:lag]).to eq(1) end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:serial_diff][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:serial_diff][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ serial_diff: { foo: { format: 'bar' } } }) end end end end stats_bucket_spec.rb000066400000000000000000000025251361161326000367410ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::StatsBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(stats_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:stats_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:stats_bucket][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:stats_bucket][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ stats_bucket: { foo: { format: 'bar' } } }) end end end end sum_bucket_spec.rb000066400000000000000000000025111361161326000364020ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/pipelinerequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::SumBucket do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(sum_bucket: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#buckets_path' do before do search.buckets_path('bar') end it 'applies the option' do expect(search.to_hash[:sum_bucket][:foo][:buckets_path]).to eq('bar') end end describe '#gap_policy' do before do search.gap_policy('bar') end it 'applies the option' do expect(search.to_hash[:sum_bucket][:foo][:gap_policy]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:sum_bucket][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do format 'bar' end end it 'executes the block' do expect(search.to_hash).to eq({ sum_bucket: { foo: { format: 'bar' } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/range_spec.rb000066400000000000000000000046021361161326000336120ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Range do let(:search) do described_class.new end context '#initialize' do let(:search) do described_class.new(field: 'test', ranges: [ { to: 50 } ]) end it 'takes a hash' do expect(search.to_hash).to eq(range: { field: "test", ranges: [ {to: 50} ] }) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('foo') end it 'applies the option' do expect(search.to_hash[:range][:foo][:field]).to eq('foo') end end describe '#script' do before do search.script('bar*2') end it 'applies the option' do expect(search.to_hash[:range][:foo][:script]).to eq('bar*2') end end end describe '#initialize' do context 'when a block is provided' do context 'when keyed ranges are provided' do let(:search) do described_class.new(field: 'test') do key 'foo', to: 10 key 'bar', from: 10, to: 20 end end it 'sets the values' do expect(search.to_hash).to eq(range: { field: "test", keyed: true, ranges: [ {to: 10, key: 'foo'}, { from: 10, to: 20, key: 'bar'}]}) end end context 'when keyed is set to false explicitly' do let(:search) do described_class.new do keyed false field 'test' key 'foo', to: 10 key 'bar', from: 10, to: 20 end end it 'sets the value' do expect(search.to_hash).to eq(range: { field: "test", keyed: false, ranges: [ {to: 10, key: 'foo'}, { from: 10, to: 20, key: 'bar'}]}) end end context 'when field is defined' do let(:search) do described_class.new do field 'test' key 'foo', to: 10 key 'bar', from: 10, to: 20 end end it 'sets the value' do expect(search.to_hash).to eq(range: { field: "test", keyed: true, ranges: [ {to: 10, key: 'foo'}, { from: 10, to: 20, key: 'bar'}]}) end end end end end reverse_nested_spec.rb000066400000000000000000000004271361161326000354550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::ReverseNested do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(reverse_nested: {}) end end end scripted_metric_spec.rb000066400000000000000000000037761361161326000356320ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::ScriptedMetric do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(scripted_metric: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#init_script' do before do search.init_script('bar') end it 'applies the option' do expect(search.to_hash[:scripted_metric][:foo][:init_script]).to eq('bar') end end describe '#map_script' do before do search.map_script('bar') end it 'applies the option' do expect(search.to_hash[:scripted_metric][:foo][:map_script]).to eq('bar') end end describe '#combine_script' do before do search.combine_script('bar') end it 'applies the option' do expect(search.to_hash[:scripted_metric][:foo][:combine_script]).to eq('bar') end end describe '#reduce_script' do before do search.reduce_script('bar') end it 'applies the option' do expect(search.to_hash[:scripted_metric][:foo][:reduce_script]).to eq('bar') end end describe '#params' do before do search.params('bar') end it 'applies the option' do expect(search.to_hash[:scripted_metric][:foo][:params]).to eq('bar') end end describe '#lang' do before do search.lang('bar') end it 'applies the option' do expect(search.to_hash[:scripted_metric][:foo][:lang]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do init_script 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(scripted_metric: { init_script: 'bar' }) end end end end significant_terms_spec.rb000066400000000000000000000061751361161326000361560ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::SignificantTerms do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(significant_terms: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:field]).to eq('bar') end end describe '#size' do before do search.size('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:size]).to eq('bar') end end describe '#shard_size' do before do search.shard_size('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:shard_size]).to eq('bar') end end describe '#min_doc_count' do before do search.min_doc_count('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:min_doc_count]).to eq('bar') end end describe '#shard_min_doc_count' do before do search.shard_min_doc_count('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:shard_min_doc_count]).to eq('bar') end end describe '#include' do before do search.include('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:include]).to eq('bar') end end describe '#exclude' do before do search.exclude('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:exclude]).to eq('bar') end end describe '#background_filter' do before do search.background_filter('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:background_filter]).to eq('bar') end end describe '#mutual_information' do before do search.mutual_information('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:mutual_information]).to eq('bar') end end describe '#chi_square' do before do search.chi_square('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:chi_square]).to eq('bar') end end describe '#gnd' do before do search.gnd('bar') end it 'applies the option' do expect(search.to_hash[:significant_terms][:foo][:gnd]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(significant_terms: { field: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/stats_spec.rb000066400000000000000000000013061361161326000336520ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Stats do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(stats: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(stats: { foo: 'bar' }) end context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(stats: { field: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/sum_spec.rb000066400000000000000000000007011361161326000333160ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Sum do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(sum: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'takes a hash' do expect(search.to_hash).to eq(sum: { foo: 'bar' }) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregations/terms_spec.rb000066400000000000000000000053461361161326000336560ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::Terms do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(terms: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:field]).to eq('bar') end end describe '#size' do before do search.size('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:size]).to eq('bar') end end describe '#shard_size' do before do search.shard_size('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:shard_size]).to eq('bar') end end describe '#order' do before do search.shard_size('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:shard_size]).to eq('bar') end end describe '#min_doc_count' do before do search.min_doc_count('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:min_doc_count]).to eq('bar') end end describe '#shard_min_doc_count' do before do search.shard_min_doc_count('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:shard_min_doc_count]).to eq('bar') end end describe '#include' do before do search.include('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:include]).to eq('bar') end end describe '#exclude' do before do search.exclude('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:exclude]).to eq('bar') end end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:terms][:foo][:script]).to eq('bar') end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(field: 'test') end it 'sets the value' do expect(search.to_hash).to eq(terms: { field: 'test' }) end end context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(terms: { field: 'bar' }) end end end end top_hits_spec.rb000066400000000000000000000023661361161326000342750ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::TopHits do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(top_hits: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#from' do before do search.from('bar') end it 'applies the option' do expect(search.to_hash[:top_hits][:foo][:from]).to eq('bar') end end describe '#size' do before do search.size('bar') end it 'applies the option' do expect(search.to_hash[:top_hits][:foo][:size]).to eq('bar') end end describe '#sort' do before do search.sort('bar') end it 'applies the option' do expect(search.to_hash[:top_hits][:foo][:sort]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do from 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(top_hits: { from: 'bar' }) end end end end value_count_spec.rb000066400000000000000000000007321361161326000347630ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/aggregationsrequire 'spec_helper' describe Elasticsearch::DSL::Search::Aggregations::ValueCount do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(value_count: {}) end end context '#initialize' do let(:search) do described_class.new(foo: 'bar') end it 'sets the value' do expect(search.to_hash).to eq(value_count: { foo: 'bar' }) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/000077500000000000000000000000001361161326000301535ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/and_spec.rb000066400000000000000000000023461361161326000322610ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::And do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(and: {}) end end context 'when enumerable methods are called' do before do search << { term: { foo: 'bar' } } search << { term: { moo: 'mam' } } end it 'behaves like an enumerable' do expect(search.size).to eq(2) expect(search[0][:term][:foo]).to eq('bar') expect(search.any? { |d| d[:term] == { foo: 'bar' } }).to be(true) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(filters: [ { term: { foo: 'bar' } } ]) end it 'applies the hash' do expect(search.to_hash).to eq(and: { filters: [ { term: { foo: 'bar' } } ] }) end end context 'when a block is provided' do let(:search) do described_class.new do term foo: 'bar' term moo: 'mam' end end it 'executes the block' do expect(search.to_hash).to eq(and: [ { term: { foo: 'bar' } }, { term: { moo: 'mam' } } ]) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/bool_spec.rb000066400000000000000000000070231361161326000324470ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Bool do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(bool: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(must: [ { term: { foo: 'bar' } } ]) end it 'applies the hash' do expect(search.to_hash).to eq(bool: { must: [ { term: { foo: 'bar' } } ] }) end end context 'when a block is provided' do let(:search) do described_class.new do must { term foo: 'bar' } end end it 'executes the block' do expect(search.to_hash).to eq(bool: { must: [ { term: { foo: 'bar' } } ] }) end context 'when the block calls multiple methods' do let(:search) do described_class.new do must { term foo: 'bar' } must_not { term moo: 'bam' } should { term xoo: 'bax' } end end it 'executes the block' do expect(search.to_hash).to eq(bool: { must: [ { term: { foo: 'bar' } } ], must_not: [ { term: { moo: 'bam' } } ], should: [ { term: { xoo: 'bax' } } ] }) end end context 'when the block calls multiple conditions' do let(:search) do described_class.new do must { term foo: 'bar' } must { term moo: 'bam' } should { term xoo: 'bax' } should { term zoo: 'baz' } end end it 'executes the block' do expect(search.to_hash).to eq(bool: { must: [ { term: { foo: 'bar' } }, { term: { moo: 'bam' } } ], should: [ { term: { xoo: 'bax' } }, { term: { zoo: 'baz' } } ] }) end end end end describe '#must' do before do search.must { term foo: 'bar' } end it 'applies the condition' do expect(search.to_hash).to eq(bool: { must: [ { term: { foo: 'bar' } } ] }) end context 'when the method is called more than once' do before do search.must { term foo: 'bar' } search.must { term moo: 'bam' } end it 'applies the conditions' do expect(search.to_hash).to eq(bool: { must: [ { term: { foo: 'bar' } }, { term: { moo: 'bam' } } ] }) end end end describe '#should' do before do search.should { term xoo: 'bax' } end it 'applies the condition' do expect(search.to_hash).to eq(bool: { should: [ { term: { xoo: 'bax' } } ] }) end end context 'when methods are chained' do before do search.must { term foo: 'bar' } search.must { term foo: 'baz' }.must { term moo: 'bam' } search.must_not { term foo: 'biz' } search.should { term foo: 'bor' } end it 'applies all the conditions' do expect(search.to_hash).to eq(bool: { must: [{ term: { foo: 'bar' } }, { term: { foo: 'baz' } }, { term: { moo: 'bam' } }], must_not: [{ term: { foo: 'biz' } }], should: [{ term: { foo: 'bor' } }] }) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/exists_spec.rb000066400000000000000000000015411361161326000330320ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Exists do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(exists: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:exists][:foo][:field]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(exists: { field: 'bar' }) end end end end geo_bounding_box_spec.rb000066400000000000000000000046071361161326000347510ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filtersrequire 'spec_helper' describe Elasticsearch::DSL::Search::Filters::GeoBoundingBox do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_bounding_box: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#top_left' do before do search.top_left('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:top_left]).to eq('bar') end end describe '#bottom_right' do before do search.bottom_right('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:bottom_right]).to eq('bar') end end describe '#top_right' do before do search.top_right('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:top_right]).to eq('bar') end end describe '#bottom_left' do before do search.bottom_left('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:bottom_left]).to eq('bar') end end describe '#top' do before do search.top('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:top]).to eq('bar') end end describe '#left' do before do search.left('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:left]).to eq('bar') end end describe '#bottom' do before do search.bottom('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:bottom]).to eq('bar') end end describe '#right' do before do search.right('bar') end it 'applies the option' do expect(search.to_hash[:geo_bounding_box][:right]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do top_left [0,1] bottom_right [3,2] end end it 'executes the block' do expect(search.to_hash).to eq(geo_bounding_box: { top_left: [0,1], bottom_right: [3,2] }) end end end end geo_distance_range_spec.rb000066400000000000000000000034611361161326000352370ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filtersrequire 'spec_helper' describe Elasticsearch::DSL::Search::Filters::GeoDistanceRange do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_distance_range: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#lat' do before do search.lat('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance_range][:foo][:lat]).to eq('bar') end end describe '#lon' do before do search.lon('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance_range][:foo][:lon]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do lat 40 lon -70 end end it 'executes the block' do expect(search.to_hash).to eq(geo_distance_range: { lat: 40, lon: -70 }) end context 'when options are also provided' do let(:search) do described_class.new :foo, from: '10km', to: '20km' do lat 40 lon -70 end end it 'executes the block' do expect(search.to_hash).to eq(geo_distance_range: { foo: { lat: 40, lon: -70 }, from: '10km', to: '20km' }) end end end context 'when options are provided' do let(:search) do described_class.new(from: '10km', to: '20km', foo: { lat: 40, lon: -70 }) end it 'executes the block' do expect(search.to_hash).to eq(geo_distance_range: { foo: { lat: 40, lon: -70 }, from: '10km', to: '20km' }) end end end end geo_distance_spec.rb000066400000000000000000000043221361161326000340600ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filtersrequire 'spec_helper' describe Elasticsearch::DSL::Search::Filters::GeoDistance do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_distance: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#distance' do before do search.distance('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:distance]).to eq('bar') end end describe '#distance_type' do before do search.distance_type('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:distance_type]).to eq('bar') end end describe '#lat' do before do search.lat('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:lat]).to eq('bar') end end describe '#lon' do before do search.lon('bar') end it 'applies the option' do expect(search.to_hash[:geo_distance][:foo][:lon]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new :foo do distance '1km' lat 40 lon -70 end end it 'executes the block' do expect(search.to_hash).to eq(geo_distance: { distance: '1km', foo: { lat: 40, lon: -70 } }) end context 'when options are also provided' do let(:search) do described_class.new(:foo, distance: '10km') do lat 40 lon -70 end end it 'executes the block' do expect(search.to_hash).to eq(geo_distance: { foo: { lat: 40, lon: -70 }, distance: '10km' }) end end end context 'when options are provided' do let(:search) do described_class.new(distance: '10km', foo: { lat: 40, lon: -70 }) end it 'executes the block' do expect(search.to_hash).to eq(geo_distance: { foo: { lat: 40, lon: -70 }, distance: '10km' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/geo_polygon_spec.rb000066400000000000000000000016151361161326000340360ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::GeoPolygon do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_polygon: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#points' do before do search.points('bar') end it 'applies the option' do expect(search.to_hash[:geo_polygon][:foo][:points]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new :foo do points 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(geo_polygon: { foo: { points: 'bar' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/geo_shape_spec.rb000066400000000000000000000021431361161326000334440ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::GeoShape do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_shape: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#shape' do before do search.shape('bar') end it 'applies the option' do expect(search.to_hash[:geo_shape][:foo][:shape]).to eq('bar') end end describe '#indexed_shape' do before do search.indexed_shape('bar') end it 'applies the option' do expect(search.to_hash[:geo_shape][:foo][:indexed_shape]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new :foo do shape 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(geo_shape: { foo: { shape: 'bar' } }) end end end end geohash_cell_spec.rb000066400000000000000000000027621361161326000340570ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filtersrequire 'spec_helper' describe Elasticsearch::DSL::Search::Filters::GeohashCell do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geohash_cell: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#precision' do before do search.precision('bar') end it 'applies the option' do expect(search.to_hash[:geohash_cell][:precision]).to eq('bar') end end describe '#neighbors' do before do search.neighbors('bar') end it 'applies the option' do expect(search.to_hash[:geohash_cell][:neighbors]).to eq('bar') end end describe '#lat' do before do search.lat('bar') end it 'applies the option' do expect(search.to_hash[:geohash_cell][:foo][:lat]).to eq('bar') end end describe '#lon' do before do search.lon('bar') end it 'applies the option' do expect(search.to_hash[:geohash_cell][:foo][:lon]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new :foo do lat 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(geohash_cell: { foo: { lat: 'bar' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/has_child_spec.rb000066400000000000000000000041571361161326000334370ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::HasChild do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(has_child: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#type' do before do search.type('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:foo][:type]).to eq('bar') end end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:query]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:filter]).to eq('bar') end end describe '#min_children' do before do search.min_children('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:foo][:min_children]).to eq('bar') end end describe '#max_children' do before do search.max_children('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:foo][:max_children]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do type 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(has_child: { foo: { type: 'bar' } }) end end context 'when a block is provided to an option method' do let(:search) do described_class.new do type 'bar' query do match :foo do query 'bar' end end end end it 'executes the block' do expect(search.to_hash).to eq(has_child: { type: 'bar', query: { match: { foo: { query: 'bar'} } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/has_parent_spec.rb000066400000000000000000000037021361161326000336400ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::HasParent do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(has_parent: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#parent_type' do before do search.parent_type('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:foo][:parent_type]).to eq('bar') end end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:query]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:filter]).to eq('bar') end end describe '#score_mode' do before do search.score_mode('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:foo][:score_mode]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do parent_type 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(has_parent: { foo: { parent_type: 'bar' } }) end end context 'when a block is provided to an option method' do let(:search) do described_class.new do parent_type 'bar' query do match :foo do query 'bar' end end end end it 'executes the block' do expect(search.to_hash).to eq(has_parent: { parent_type: 'bar', query: { match: { foo: { query: 'bar'} } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/ids_spec.rb000066400000000000000000000021301361161326000322650ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Ids do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(ids: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#type' do before do search.type('bar') end it 'applies the option' do expect(search.to_hash[:ids][:foo][:type]).to eq('bar') end end describe '#values' do before do search.values('bar') end it 'applies the option' do expect(search.to_hash[:ids][:foo][:values]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do type 'bar' values ['1', '2', '3'] end end it 'executes the block' do expect(search.to_hash).to eq(ids: { type: 'bar', values: ['1', '2', '3'] }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/indices_spec.rb000066400000000000000000000034541361161326000331360ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Indices do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(indices: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#indices' do before do search.indices('bar') end it 'applies the option' do expect(search.to_hash[:indices][:indices]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:indices][:filter]).to eq('bar') end end describe '#no_match_filter' do before do search.no_match_filter('bar') end it 'applies the option' do expect(search.to_hash[:indices][:no_match_filter]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do indices 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(indices: { indices: 'bar' }) end end context 'when a block is provided to an option method' do let(:search) do described_class.new do indices 'bar' filter do term foo: 'bar' end no_match_filter do term foo: 'bam' end end end it 'executes the block' do expect(search.to_hash).to eq(indices: { indices: 'bar', filter: { term: { foo: 'bar' } }, no_match_filter: { term: { foo: 'bam' } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/limit_spec.rb000066400000000000000000000015351361161326000326340ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Limit do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(limit: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#value' do before do search.value('bar') end it 'applies the option' do expect(search.to_hash[:limit][:foo][:value]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do value 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(limit: { value: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/match_all_spec.rb000066400000000000000000000004101361161326000334310ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::MatchAll do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(match_all: {}) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/missing_spec.rb000066400000000000000000000015451361161326000331700ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Missing do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(missing: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:missing][:foo][:field]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(missing: { field: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/nested_spec.rb000066400000000000000000000021651361161326000330000ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Nested do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(nested: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#path' do before do search.path('bar') end it 'applies the option' do expect(search.to_hash[:nested][:path]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:nested][:filter]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do path 'bar' filter do term foo: 'bar' end end end it 'executes the block' do expect(search.to_hash).to eq(nested: { path: 'bar', filter: { term: { foo: 'bar' } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/not_spec.rb000066400000000000000000000014761361161326000323220ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Not do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(not: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(filters: [ { term: { foo: 'bar' } } ]) end it 'applies the hash' do expect(search.to_hash).to eq(not: { filters: [ { term: { foo: 'bar' } } ] }) end end context 'when a block is provided' do let(:search) do described_class.new do term foo: 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(not: { term: { foo: 'bar' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/or_spec.rb000066400000000000000000000022471361161326000321370ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Or do let(:search) do described_class.new end it 'responds to enumerable methods' do expect(search.empty?).to be(true) end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(or: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(filters: [ { term: { foo: 'bar' } } ]) end it 'applies the hash' do expect(search.to_hash).to eq(or: { filters: [ { term: { foo: 'bar' } } ] }) end end context 'when a block is provided' do let(:search) do described_class.new do term foo: 'bar' term moo: 'mam' end end it 'executes the block' do expect(search.to_hash).to eq(or: [ {term: { foo: 'bar'}}, {term: { moo: 'mam'}} ]) end end end context 'when the filter is appended to' do before do search << { term: { foo: 'bar' } } end it 'appends the predicate' do expect(search.to_hash).to eq(or: [ { term: { foo: 'bar' } } ]) end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/prefix_spec.rb000066400000000000000000000010101361161326000327770ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Prefix do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(prefix: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(foo: 'bar') end it 'applies the hash' do expect(search.to_hash).to eq(prefix: { foo: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/query_spec.rb000066400000000000000000000014721361161326000326630ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Query do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(query: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(query_string: { query: 'foo' }) end it 'applies the hash' do expect(search.to_hash).to eq(query: { query_string: { query: 'foo' } }) end end context 'when a block is provided' do let(:search) do described_class.new do match foo: 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(query: { match: { foo: 'bar' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/range_spec.rb000066400000000000000000000033231361161326000326070ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Range do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(range: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#gte' do before do search.gte('bar') end it 'applies the option' do expect(search.to_hash[:range][:foo][:gte]).to eq('bar') end end describe '#lte' do before do search.lte('bar') end it 'applies the option' do expect(search.to_hash[:range][:foo][:lte]).to eq('bar') end end describe '#time_zone' do before do search.time_zone('bar') end it 'applies the option' do expect(search.to_hash[:range][:foo][:time_zone]).to eq('bar') end end describe '#format' do before do search.format('bar') end it 'applies the option' do expect(search.to_hash[:range][:foo][:format]).to eq('bar') end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(age: { gte: 10, lte: 20 }) end it 'applies the hash' do expect(search.to_hash).to eq(range: { age: { gte: 10, lte: 20 } }) end end context 'when a block is provided' do let(:search) do described_class.new(:age) do gte 10 lte 20 end end it 'executes the block' do expect(search.to_hash).to eq(range: { age: { gte: 10, lte: 20 } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/regexp_spec.rb000066400000000000000000000024341361161326000330070ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Regexp do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(regexp: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#value' do before do search.value('bar') end it 'applies the option' do expect(search.to_hash[:regexp][:foo][:value]).to eq('bar') end end describe '#flags' do before do search.flags('bar') end it 'applies the option' do expect(search.to_hash[:regexp][:foo][:flags]).to eq('bar') end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(foo: 'b.*r') end it 'applies the hash' do expect(search.to_hash).to eq(regexp: { foo: 'b.*r' }) end end context 'when a block is provided' do let(:search) do described_class.new(:foo) do value 'b*r' end end it 'executes the block' do expect(search.to_hash).to eq(regexp: { foo: { value: 'b*r' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/script_spec.rb000066400000000000000000000021121361161326000330120ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Script do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(script: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#script' do before do search.script('bar') end it 'applies the option' do expect(search.to_hash[:script][:foo][:script]).to eq('bar') end end describe '#params' do before do search.params(foo: 'bar') end it 'applies the option' do expect(search.to_hash[:script][:foo][:params]).to eq(foo: 'bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do script 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(script: { foo: { script: 'bar' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/term_spec.rb000066400000000000000000000014141361161326000324610ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Term do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(term: {}) end end describe '#initialize' do context 'when a scalar is specified' do let(:search) do described_class.new(message: 'test') end it 'sets the value' do expect(search.to_hash).to eq(term: { message: 'test' }) end end context 'when a hash is specified' do let(:search) do described_class.new(message: { query: 'test' }) end it 'sets the value' do expect(search.to_hash).to eq(term: { message: { query: 'test' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/terms_spec.rb000066400000000000000000000010261361161326000326430ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Terms do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(terms: {}) end end describe '#initialize' do context 'when a hash is specified' do let(:search) do described_class.new(foo: ['abc', 'xyz']) end it 'sets the value' do expect(search.to_hash).to eq(terms: { foo: ['abc', 'xyz'] }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/filters/type_spec.rb000066400000000000000000000015501361161326000324740ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Filters::Type do let(:search) do described_class.new end describe '#to_hash' do it 'can be converted to a hash' do expect(search.to_hash).to eq(type: {}) end end context 'when options methods are called' do let(:search) do described_class.new(:foo) end describe '#value' do before do search.value('bar') end it 'applies the option' do expect(search.to_hash[:type][:foo][:value]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do value 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(type: { foo: { value: 'bar' } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/000077500000000000000000000000001361161326000301605ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/bool_spec.rb000066400000000000000000000114311361161326000324520ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Bool do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(bool: {}) end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do must { match foo: 'bar' } end end it 'executes the block' do expect(search.to_hash).to eq(bool: {must: [ {match: { foo: 'bar' }} ] }) end context 'when multiple option methods are called' do let(:search) do described_class.new do should { term tag: 'wow' } should { term tag: 'elasticsearch' } minimum_should_match 1 boost 1.0 end end it 'defines all the options' do expect(search.to_hash).to eq(bool: { minimum_should_match: 1, boost: 1.0, should: [ {term: { tag: 'wow' }}, {term: { tag: 'elasticsearch' }} ]}) end end context 'when multiple conditions are provided' do let(:search) do described_class.new do must do match foo: 'bar' end must do match moo: 'bam' end should do match xoo: 'bax' end should do match zoo: 'baz' end end end it 'applies each condition' do expect(search.to_hash).to eq(bool: { must: [ {match: { foo: 'bar' }}, {match: { moo: 'bam' }} ], should: [ {match: { xoo: 'bax' }}, {match: { zoo: 'baz' }} ] }) end context 'when #to_hash is called more than once' do it 'does not alter the hash' do expect(search.to_hash).to eq(search.to_hash) end end end end end context 'when options methods are called' do let(:search) do described_class.new end before do search.must { match foo: 'bar' } search.must { match moo: 'bam' } search.should { match xoo: 'bax' } end it 'applies the option' do expect(search.to_hash).to eq(bool: { must: [ {match: { foo: 'bar' }}, {match: { moo: 'bam' }} ], should: [ {match: { xoo: 'bax' }} ] }) end end context 'when the filter method is called multiple times' do let(:search) do described_class.new end before do search.filter { term foo: 'bar' } search.filter { term zoo: 'baz' } end it 'combines the filter clauses' do expect(search.to_hash).to eq(bool: { filter: [ { term: { foo: "bar"}}, { term: { zoo: "baz"}} ] }) end end context 'when methods are chained' do let(:search) do described_class.new end before do search.must { match foo: 'bar' }.must { match moo: 'bam' }.should { match xoo: 'bax' } end it 'applies the option' do expect(search.to_hash).to eq(bool: { must: [ {match: { foo: 'bar' }}, {match: { moo: 'bam' }} ], should: [ {match: { xoo: 'bax' }} ] }) end end describe '#filter' do context 'when a block is used to define the filter' do let(:search) do described_class.new do filter do term foo: 'Foo!' end end end it 'applies the filter' do expect(search.to_hash).to eq(bool: { filter: [{ term: { foo: 'Foo!' } }] }) end end context 'when a filter is passed as an argument' do context 'when the filter is a hash' do let(:search) do described_class.new do filter(term: { foo: 'Foo!' }) end end it 'applies the filter' do expect(search.to_hash).to eq(bool: { filter: [{ term: { foo: 'Foo!' } }] }) end end context 'when the filter is a `Elasticsearch::DSL::Search::Filter` object' do let(:search) do filter_object = Elasticsearch::DSL::Search::Filter.new do term bar: 'Bar!' end described_class.new do filter(filter_object) end end it 'applies the filter' do expect(search.to_hash).to eq(bool: { filter: [{ term: { bar: 'Bar!' } }] }) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/boosting_spec.rb000066400000000000000000000026151361161326000333470ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Boosting do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(boosting: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#positive' do before do search.positive('bar') end it 'applies the option' do expect(search.to_hash[:boosting][:positive]).to eq('bar') end end describe '#negative' do before do search.negative('bar') end it 'applies the option' do expect(search.to_hash[:boosting][:negative]).to eq('bar') end end describe '#negative_boost' do before do search.negative_boost('bar') end it 'applies the option' do expect(search.to_hash[:boosting][:negative_boost]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do positive foo: 'bar' negative moo: 'xoo' end end it 'executes the block' do expect(search.to_hash[:boosting][:positive][:foo]).to eq('bar') expect(search.to_hash[:boosting][:negative][:moo]).to eq('xoo') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/common_spec.rb000066400000000000000000000041701361161326000330110ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Common do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(common: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:common][:query]).to eq('bar') end end describe '#cutoff_frequency' do before do search.cutoff_frequency('bar') end it 'applies the option' do expect(search.to_hash[:common][:cutoff_frequency]).to eq('bar') end end describe '#low_freq_operator' do before do search.low_freq_operator('bar') end it 'applies the option' do expect(search.to_hash[:common][:low_freq_operator]).to eq('bar') end end describe '#minimum_should_match' do before do search.minimum_should_match('bar') end it 'applies the option' do expect(search.to_hash[:common][:minimum_should_match]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:common][:boost]).to eq('bar') end end describe '#analyzer' do before do search.analyzer('bar') end it 'applies the option' do expect(search.to_hash[:common][:analyzer]).to eq('bar') end end describe '#disable_coord' do before do search.disable_coord('bar') end it 'applies the option' do expect(search.to_hash[:common][:disable_coord]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do query 'bar' end end it 'executes the block' do expect(search.to_hash[:common][:query]).to eq('bar') end end end end constant_score_spec.rb000066400000000000000000000025031361161326000344640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::ConstantScore do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(constant_score: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:constant_score][:query]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:constant_score][:filter]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:constant_score][:boost]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do query do term foo: 'bar' end end end it 'executes the block' do expect(search.to_hash[:constant_score][:query][:term][:foo]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/dis_max_spec.rb000066400000000000000000000024061361161326000331450ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::DisMax do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(dis_max: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#tie_breaker' do before do search.tie_breaker('bar') end it 'applies the option' do expect(search.to_hash[:dis_max][:tie_breaker]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:dis_max][:boost]).to eq('bar') end end describe '#queries' do before do search.queries('bar') end it 'applies the option' do expect(search.to_hash[:dis_max][:queries]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do tie_breaker 'bar' end end it 'executes the block' do expect(search.to_hash[:dis_max][:tie_breaker]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/exists_spec.rb000066400000000000000000000015311361161326000330360ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Exists do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(exists: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#field' do before do search.field('bar') end it 'applies the option' do expect(search.to_hash[:exists][:field]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do field 'bar' end end it 'executes the block' do expect(search.to_hash[:exists][:field]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/filtered_spec.rb000066400000000000000000000026271361161326000333240ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Filtered do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(filtered: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:filtered][:query]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:filtered][:filter]).to eq('bar') end end describe '#strategy' do before do search.strategy('bar') end it 'applies the option' do expect(search.to_hash[:filtered][:strategy]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do query do match foo: 'BLAM' end filter do term bar: 'slam' end end end it 'executes the block' do expect(search.to_hash).to eq(filtered: { query: { match: { foo: 'BLAM' } }, filter: { term: { bar: 'slam' } } }) end end end end function_score_spec.rb000066400000000000000000000057341361161326000344710ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::FunctionScore do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(function_score: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:query]).to eq('bar') end end describe '#filter' do before do search.filter('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:filter]).to eq('bar') end end describe '#functions' do before do search.functions('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:functions]).to eq('bar') end context 'when the option is called as a setter' do before do search.functions = [ {foo: { abc: '123' }} ] end it 'applies the option' do expect(search.to_hash).to eq(function_score: { functions: [ {foo: { abc: '123' }} ] }) end end end describe '#script_score' do before do search.script_score('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:script_score]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:boost]).to eq('bar') end end describe '#max_boost' do before do search.max_boost('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:max_boost]).to eq('bar') end end describe '#score_mode' do before do search.score_mode('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:score_mode]).to eq('bar') end end describe '#boost_mode' do before do search.boost_mode('bar') end it 'applies the option' do expect(search.to_hash[:function_score][:boost_mode]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do query do match foo: 'BLAM' end filter do term bar: 'slam' end functions << { foo: { abc: '123' } } functions << { foo: { xyz: '456' } } end end it 'executes the block' do expect(search.to_hash).to eq(function_score: { query: { match: { foo: 'BLAM' } }, filter: { term: { bar: 'slam' } }, functions: [ { foo: { abc: '123' } }, { foo: { xyz: '456' } } ] }) end end end end fuzzy_like_this_field_spec.rb000066400000000000000000000043431361161326000360310ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::FuzzyLikeThisField do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(fuzzy_like_this_field: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#like_text' do before do search.like_text('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:like_text]).to eq('bar') end end describe '#fuzziness' do before do search.fuzziness('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:fuzziness]).to eq('bar') end end describe '#analyzer' do before do search.analyzer('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:analyzer]).to eq('bar') end end describe '#max_query_terms' do before do search.max_query_terms('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:max_query_terms]).to eq('bar') end end describe '#prefix_length' do before do search.prefix_length('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:prefix_length]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:boost]).to eq('bar') end end describe '#ignore_tf' do before do search.ignore_tf('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this_field][:ignore_tf]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do like_text 'bar' end end it 'executes the block' do expect(search.to_hash[:fuzzy_like_this_field][:like_text]).to eq('bar') end end end end fuzzy_like_this_spec.rb000066400000000000000000000044011361161326000346610ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::FuzzyLikeThis do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(fuzzy_like_this: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#fields' do before do search.fields('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:fields]).to eq('bar') end end describe '#like_text' do before do search.like_text('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:like_text]).to eq('bar') end end describe '#fuzziness' do before do search.fuzziness('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:fuzziness]).to eq('bar') end end describe '#analyzer' do before do search.analyzer('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:analyzer]).to eq('bar') end end describe '#max_query_terms' do before do search.max_query_terms('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:max_query_terms]).to eq('bar') end end describe '#prefix_length' do before do search.prefix_length('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:prefix_length]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy_like_this][:boost]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do fields ['foo'] like_text 'bar' end end it 'executes the block' do expect(search.to_hash[:fuzzy_like_this][:like_text]).to eq('bar') expect(search.to_hash[:fuzzy_like_this][:fields]).to eq(['foo']) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/fuzzy_spec.rb000066400000000000000000000032301361161326000327040ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Fuzzy do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(fuzzy: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#value' do before do search.value('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy][:value]).to eq('bar') end end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy][:boost]).to eq('bar') end end describe '#fuzziness' do before do search.fuzziness('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy][:fuzziness]).to eq('bar') end end describe '#prefix_length' do before do search.prefix_length('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy][:prefix_length]).to eq('bar') end end describe '#max_expansions' do before do search.max_expansions('bar') end it 'applies the option' do expect(search.to_hash[:fuzzy][:max_expansions]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do value 'bar' end end it 'executes the block' do expect(search.to_hash[:fuzzy][:value]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/geo_shape_spec.rb000066400000000000000000000021151361161326000334500ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::GeoShape do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(geo_shape: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#shape' do before do search.shape('bar') end it 'applies the option' do expect(search.to_hash[:geo_shape][:shape]).to eq('bar') end end describe '#indexed_shape' do before do search.indexed_shape('bar') end it 'applies the option' do expect(search.to_hash[:geo_shape][:indexed_shape]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do shape 'bar' end end it 'executes the block' do expect(search.to_hash[:geo_shape][:foo][:shape]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/has_child_spec.rb000066400000000000000000000034771361161326000334500ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::HasChild do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(has_child: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#type' do before do search.type('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:type]).to eq('bar') end end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:query]).to eq('bar') end end describe '#score_mode' do before do search.score_mode('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:score_mode]).to eq('bar') end end describe '#min_children' do before do search.min_children('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:min_children]).to eq('bar') end end describe '#max_children' do before do search.max_children('bar') end it 'applies the option' do expect(search.to_hash[:has_child][:max_children]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do type 'bar' query do match :foo do query 'bar' end end end end it 'executes the block' do expect(search.to_hash).to eq(has_child: { type: 'bar', query: { match: { foo: { query: 'bar'} } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/has_parent_spec.rb000066400000000000000000000025531361161326000336500ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::HasParent do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(has_parent: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#parent_type' do before do search.parent_type('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:parent_type]).to eq('bar') end end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:query]).to eq('bar') end end describe '#score_mode' do before do search.score_mode('bar') end it 'applies the option' do expect(search.to_hash[:has_parent][:score_mode]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do parent_type 'bar' query match: { foo: 'bar' } end end it 'executes the block' do expect(search.to_hash).to eq(has_parent: { parent_type: 'bar', query: { match: { foo: 'bar' } } }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/ids_spec.rb000066400000000000000000000020721361161326000322770ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Ids do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(ids: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#type' do before do search.type('bar') end it 'applies the option' do expect(search.to_hash[:ids][:type]).to eq('bar') end end describe '#values' do before do search.values('bar') end it 'applies the option' do expect(search.to_hash[:ids][:values]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do type 'bar' values [1, 2, 3] end end it 'executes the block' do expect(search.to_hash).to eq(ids: { type: 'bar', values: [1, 2, 3] }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/indices_spec.rb000066400000000000000000000025211361161326000331350ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Indices do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(indices: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#indices' do before do search.indices('bar') end it 'applies the option' do expect(search.to_hash[:indices][:indices]).to eq('bar') end end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:indices][:query]).to eq('bar') end end describe '#no_match_query' do before do search.no_match_query('bar') end it 'applies the option' do expect(search.to_hash[:indices][:no_match_query]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do indices 'bar' query term: { foo: 'bar' } end end it 'executes the block' do expect(search.to_hash).to eq(indices: { indices: 'bar', query: { term: { foo: 'bar' } } } ) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/mach_spec.rb000066400000000000000000000035221361161326000324310ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Match do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(match: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:match][:query]).to eq('bar') end end describe '#operator' do before do search.operator('standard') end it 'applies the option' do expect(search.to_hash[:match][:operator]).to eq('standard') end end describe '#type' do before do search.type(10) end it 'applies the option' do expect(search.to_hash[:match][:type]).to eq(10) end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(message: { query: 'test' }) end it 'sets the value' do expect(search.to_hash).to eq(match: { message: { query: 'test' } }) end end context 'when a block is provided' do let(:search) do described_class.new do query 'test' operator 'and' type 'phrase_prefix' boost 2 fuzziness 'AUTO' end end it 'executes the block' do expect(search.to_hash[:match][:query]).to eq('test') expect(search.to_hash[:match][:operator]).to eq('and') expect(search.to_hash[:match][:type]).to eq('phrase_prefix') expect(search.to_hash[:match][:boost]).to eq(2) expect(search.to_hash[:match][:fuzziness]).to eq('AUTO') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/match_all_spec.rb000066400000000000000000000015461361161326000334510ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::MatchAll do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(match_all: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#boost' do before do search.boost('bar') end it 'applies the option' do expect(search.to_hash[:match_all][:boost]).to eq('bar') end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do boost 'bar' end end it 'executes the block' do expect(search.to_hash).to eq(match_all: { boost: 'bar' }) end end end end match_phrase_prefix_spec.rb000066400000000000000000000034031361161326000354530ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::MatchPhrasePrefix do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(match_phrase_prefix: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:match_phrase_prefix][:query]).to eq('bar') end end describe '#boost' do before do search.boost(10) end it 'applies the option' do expect(search.to_hash[:match_phrase_prefix][:boost]).to eq(10) end end describe '#max_expansions' do before do search.max_expansions(2) end it 'applies the option' do expect(search.to_hash[:match_phrase_prefix][:max_expansions]).to eq(2) end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(message: 'test') end it 'sets the value' do expect(search.to_hash).to eq(match_phrase_prefix: { message: 'test' }) end end context 'when a block is provided' do let(:search) do described_class.new do query 'test' boost 2 max_expansions 1 end end it 'executes the block' do expect(search.to_hash[:match_phrase_prefix][:query]).to eq('test') expect(search.to_hash[:match_phrase_prefix][:boost]).to eq(2) expect(search.to_hash[:match_phrase_prefix][:max_expansions]).to eq(1) end end end end match_phrase_spec.rb000066400000000000000000000035661361161326000341100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::MatchPhrase do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(match_phrase: {}) end end context 'when options methods are called' do let(:search) do described_class.new end describe '#query' do before do search.query('bar') end it 'applies the option' do expect(search.to_hash[:match_phrase][:query]).to eq('bar') end end describe '#analyzer' do before do search.analyzer('standard') end it 'applies the option' do expect(search.to_hash[:match_phrase][:analyzer]).to eq('standard') end end describe '#boost' do before do search.boost(10) end it 'applies the option' do expect(search.to_hash[:match_phrase][:boost]).to eq(10) end end describe '#slop' do before do search.slop(1) end it 'applies the option' do expect(search.to_hash[:match_phrase][:slop]).to eq(1) end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(message: { query: 'test' }) end it 'sets the value' do expect(search.to_hash).to eq(match_phrase: { message: { query: 'test' } }) end end context 'when a block is provided' do let(:search) do described_class.new do query 'test' slop 1 boost 2 end end it 'executes the block' do expect(search.to_hash[:match_phrase][:query]).to eq('test') expect(search.to_hash[:match_phrase][:boost]).to eq(2) expect(search.to_hash[:match_phrase][:slop]).to eq(1) end end end end more_like_this_spec.rb000066400000000000000000000026031361161326000344360ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::MoreLikeThis do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(more_like_this: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'fields', 'like_text', 'min_term_freq', 'max_query_terms', 'docs', 'ids', 'include', 'exclude', 'percent_terms_to_match', 'stop_words', 'min_doc_freq', 'max_doc_freq', 'min_word_length', 'max_word_length', 'boost_terms', 'boost', 'analyzer' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:more_like_this][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do fields ['foo', 'bar'] like_text 'abc' end end it 'executes the block' do expect(search.to_hash[:more_like_this][:fields]).to eq(['foo', 'bar']) expect(search.to_hash[:more_like_this][:like_text]).to eq('abc') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/multi_match_spec.rb000066400000000000000000000021171361161326000340260ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::MultiMatch do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(multi_match: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'query', 'fields', 'type', 'use_dis_max' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:multi_match][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do query 'bar' fields ['a', 'b'] end end it 'executes the block' do expect(search.to_hash[:multi_match][:fields]).to eq(['a', 'b']) expect(search.to_hash[:multi_match][:query]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/nested_spec.rb000066400000000000000000000030731361161326000330040ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Nested do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(nested: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'path', 'score_mode', 'score_mode', 'query' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:nested][option.to_sym]).to eq('bar') end end describe '#inner_hits' do before do search.inner_hits(size: 1) end it 'applies the option' do expect(search.to_hash[:nested][:inner_hits]).to eq(size: 1) end end describe '#query' do before do search.query(match: { foo: 'bar' }) end it 'applies the option' do expect(search.to_hash[:nested][:query]).to eq(match: { foo: 'bar' }) end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do path 'bar' query do match foo: 'bar' end end end it 'executes the block' do expect(search.to_hash[:nested][:path]).to eq('bar') expect(search.to_hash[:nested][:query]).to eq(match: { foo: 'bar' }) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/prefix_spec.rb000066400000000000000000000016631361161326000330220ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Prefix do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(prefix: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'value', 'boost'].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:prefix][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do value 'bar' end end it 'executes the block' do expect(search.to_hash[:prefix][:value]).to eq('bar') end end end end query_string_spec.rb000066400000000000000000000026561361161326000342040ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::QueryString do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(query_string: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'query', 'fields', 'type', 'default_field', 'default_operator', 'allow_leading_wildcard', 'lowercase_expanded_terms', 'enable_position_increments', 'fuzzy_max_expansions', 'fuzziness', 'fuzzy_prefix_length', 'phrase_slop', 'boost', 'analyze_wildcard', 'auto_generate_phrase_queries', 'minimum_should_match', 'lenient', 'locale', 'use_dis_max', 'tie_breaker', 'time_zone'].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:query_string][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do query 'foo AND bar' end end it 'executes the block' do expect(search.to_hash[:query_string][:query]).to eq('foo AND bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/range_spec.rb000066400000000000000000000022701361161326000326140ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Range do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(range: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'gte', 'lte', 'boost', 'format'].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:range][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do gte 10 lte 20 boost 2 format 'mm/dd/yyyy' end end it 'executes the block' do expect(search.to_hash[:range][:gte]).to eq(10) expect(search.to_hash[:range][:lte]).to eq(20) expect(search.to_hash[:range][:boost]).to eq(2) expect(search.to_hash[:range][:format]).to eq('mm/dd/yyyy') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/regexp_spec.rb000066400000000000000000000022561361161326000330160ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Regexp do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(regexp: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'value', 'boost', 'flags'].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:regexp][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(foo: 'b.*r') end it 'sets the value' do expect(search.to_hash[:regexp][:foo]).to eq('b.*r') end end context 'when a block is provided' do let(:search) do described_class.new(:foo) do value 'bar' end end it 'executes the block' do expect(search.to_hash[:regexp][:foo][:value]).to eq('bar') end end end end simple_query_string_spec.rb000066400000000000000000000020761361161326000355510ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SimpleQueryString do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(simple_query_string: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'query', 'fields', 'default_operator', 'analyzer', 'flags', 'lenient'].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:simple_query_string][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new(:foo) do query 'bar' end end it 'executes the block' do expect(search.to_hash[:simple_query_string][:foo][:query]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/span_first_spec.rb000066400000000000000000000016641361161326000336760ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SpanFirst do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(span_first: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'match' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:span_first][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do match 'bar' end end it 'executes the block' do expect(search.to_hash[:span_first][:match]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/span_multi_spec.rb000066400000000000000000000016641361161326000337010ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SpanMulti do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(span_multi: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'match' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:span_multi][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do match 'bar' end end it 'executes the block' do expect(search.to_hash[:span_multi][:match]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/span_near_spec.rb000066400000000000000000000017661361161326000334770ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SpanNear do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(span_near: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'span_near', 'slop', 'in_order', 'collect_payloads' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:span_near][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do span_near 'bar' end end it 'executes the block' do expect(search.to_hash[:span_near][:span_near]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/span_not_spec.rb000066400000000000000000000017541361161326000333470ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SpanNot do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(span_not: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'include', 'exclude', 'pre', 'post', 'dist' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:span_not][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do include 'bar' end end it 'executes the block' do expect(search.to_hash[:span_not][:include]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/span_or_spec.rb000066400000000000000000000016561361161326000331700ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SpanOr do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(span_or: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'clauses' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:span_or][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do clauses 'bar' end end it 'executes the block' do expect(search.to_hash[:span_or][:clauses]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/span_term_spec.rb000066400000000000000000000010221361161326000335020ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::SpanTerm do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(span_term: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(foo: 'bar') end it 'sets the value' do expect(search.to_hash[:span_term][:foo]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/template_spec.rb000066400000000000000000000025411361161326000333340ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Template do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(template: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'query', 'params' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:template][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(query: 'bar', params: { foo: 'abc' }) end it 'sets the value' do expect(search.to_hash[:template][:query]).to eq('bar') expect(search.to_hash[:template][:params][:foo]).to eq('abc') end end context 'when a block is provided' do let(:search) do described_class.new do query 'bar' params foo: 'abc' end end it 'executes the block' do expect(search.to_hash[:template][:query]).to eq('bar') expect(search.to_hash[:template][:params][:foo]).to eq('abc') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/term_spec.rb000066400000000000000000000014401361161326000324650ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Term do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(term: {}) end end describe '#initialize' do context 'when a String is provided' do let(:search) do described_class.new(message: 'test') end it 'executes the block' do expect(search.to_hash[:term][:message]).to eq('test') end end context 'when a hash is provided' do let(:search) do described_class.new(message: { query: 'test', boost: 2 }) end it 'sets the value' do expect(search.to_hash[:term][:message]).to eq(query: 'test', boost: 2) end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/terms_spec.rb000066400000000000000000000010301361161326000326430ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Terms do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(terms: {}) end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(foo: ['abc', 'xyz']) end it 'sets the value' do expect(search.to_hash[:terms]).to eq(foo: ['abc', 'xyz']) end end end end top_children_spec.rb000066400000000000000000000030061361161326000341110ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queriesrequire 'spec_helper' describe Elasticsearch::DSL::Search::Queries::TopChildren do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(top_children: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'type', 'query', 'score', 'factor', 'incremental_factor', '_scope' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:top_children][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a block is provided' do let(:search) do described_class.new do type 'bar' query 'foo' end end it 'executes the block' do expect(search.to_hash[:top_children][:type]).to eq('bar') expect(search.to_hash[:top_children][:query]).to eq('foo') end end context 'when nested blocks are provided' do let(:search) do described_class.new do type 'bar' query do match foo: 'BLAM' end end end it 'executes the block' do expect(search.to_hash[:top_children][:type]).to eq('bar') expect(search.to_hash[:top_children][:query][:match][:foo]).to eq('BLAM') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/elasticsearch/dsl/search/queries/wildcard_spec.rb000066400000000000000000000022341361161326000333110ustar00rootroot00000000000000require 'spec_helper' describe Elasticsearch::DSL::Search::Queries::Wildcard do describe '#to_hash' do let(:search) do described_class.new end it 'can be converted to a hash' do expect(search.to_hash).to eq(wildcard: {}) end end context 'when options methods are called' do let(:search) do described_class.new end [ 'value', 'boost' ].each do |option| describe "##{option}" do before do search.send(option, 'bar') end it 'applies the option' do expect(search.to_hash[:wildcard][option.to_sym]).to eq('bar') end end end end describe '#initialize' do context 'when a hash is provided' do let(:search) do described_class.new(foo: 'bar') end it 'sets the value' do expect(search.to_hash[:wildcard][:foo]).to eq('bar') end end context 'when a block is provided' do let(:search) do described_class.new do value 'bar' end end it 'executes the block' do expect(search.to_hash[:wildcard][:value]).to eq('bar') end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/spec/spec_helper.rb000066400000000000000000000002201361161326000244520ustar00rootroot00000000000000require 'elasticsearch' require 'elasticsearch-dsl' RSpec.configure do |config| config.formatter = 'documentation' config.color = true end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/000077500000000000000000000000001361161326000216675ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/000077500000000000000000000000001361161326000242125ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_aggregation_children_test.rb000066400000000000000000000063221361161326000332650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ChildrenAggregationIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "A children aggregation" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'articles-and-comments', body: { mappings: { _doc: { properties: { title: { type: 'text' }, category: { type: 'keyword' }, join_field: { type: 'join', relations: { article: 'comment' } }, author: { type: 'keyword'} } } } } @client.index index: 'articles-and-comments', id: 1, type: '_doc', body: { title: 'A', category: 'one', join_field: 'article' } @client.index index: 'articles-and-comments', id: 2, type: '_doc', body: { title: 'B', category: 'one', join_field: 'article' } @client.index index: 'articles-and-comments', id: 3, type: '_doc', body: { title: 'C', category: 'two', join_field: 'article' } @client.index index: 'articles-and-comments', routing: '1', type: '_doc', body: { author: 'John', join_field: { name: 'comment', parent: 1 } } @client.index index: 'articles-and-comments', routing: '1', type: '_doc', body: { author: 'Mary', join_field: { name: 'comment', parent: 1 } } @client.index index: 'articles-and-comments', routing: '2', type: '_doc', body: { author: 'John', join_field: { name: 'comment', parent: 2 } } @client.index index: 'articles-and-comments', routing: '2', type: '_doc', body: { author: 'Dave', join_field: { name: 'comment', parent: 2 } } @client.index index: 'articles-and-comments', routing: '3', type: '_doc', body: { author: 'Ruth', join_field: { name: 'comment', parent: 3 } } @client.indices.refresh index: 'articles-and-comments' end should "return the top commenters per article category" do response = @client.search index: 'articles-and-comments', size: 0, body: search { aggregation :top_categories do terms field: 'category' do aggregation :comments do children type: 'comment' do aggregation :top_authors do terms field: 'author' end end end end end }.to_hash assert_equal 'one', response['aggregations']['top_categories']['buckets'][0]['key'] assert_equal 3, response['aggregations']['top_categories']['buckets'][0]['comments']['top_authors']['buckets'].size assert_equal 'John', response['aggregations']['top_categories']['buckets'][0]['comments']['top_authors']['buckets'][0]['key'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_aggregation_geo_test.rb000066400000000000000000000067101361161326000322500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class GeoAggregationIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "A geo aggregation" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'venues-test', body: { mappings: { venue: { properties: { location: { type: 'geo_point' } } } } } @client.index index: 'venues-test', type: 'venue', body: { name: 'Space', location: "38.886214,1.403889" } @client.index index: 'venues-test', type: 'venue', body: { name: 'Pacha', location: "38.9184427,1.4433646" } @client.index index: 'venues-test', type: 'venue', body: { name: 'Amnesia', location: "38.948045,1.408341" } @client.index index: 'venues-test', type: 'venue', body: { name: 'Privilege', location: "38.958082,1.408288" } @client.index index: 'venues-test', type: 'venue', body: { name: 'Es Paradis', location: "38.979071,1.307394" } @client.indices.refresh index: 'venues-test' end should "return the geo distances from a location" do response = @client.search index: 'venues-test', size: 0, body: search { aggregation :venue_distances do geo_distance do field :location origin '38.9126352,1.4350621' unit 'km' ranges [ { to: 1 }, { from: 1, to: 5 }, { from: 5, to: 10 }, { from: 10 } ] aggregation :top_venues do top_hits _source: { include: 'name' } end end end }.to_hash result = response['aggregations']['venue_distances'] assert_equal 4, result['buckets'].size assert_equal 1, result['buckets'][0]['doc_count'] assert_equal 'Pacha', result['buckets'][0]['top_venues']['hits']['hits'][0]['_source']['name'] assert_equal 2, result['buckets'][1]['top_venues']['hits']['total'] end should "return the geohash grid distribution" do # # See the geohash plot eg. at http://openlocation.org/geohash/geohash-js/ # See the locations visually eg. at http://geohash.org/sncj8h17r2 # response = @client.search index: 'venues-test', size: 0, body: search { aggregation :venue_distributions do geohash_grid do field :location precision 5 aggregation :top_venues do top_hits _source: { include: 'name' } end end end }.to_hash result = response['aggregations']['venue_distributions'] assert_equal 4, result['buckets'].size assert_equal 'sncj8', result['buckets'][0]['key'] assert_equal 2, result['buckets'][0]['doc_count'] assert_same_elements %w[ Privilege Amnesia ], result['buckets'][0]['top_venues']['hits']['hits'].map { |h| h['_source']['name'] } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_aggregation_nested_test.rb000066400000000000000000000074151361161326000327630ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class NestedAggregationIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "A nested aggregation" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'products-test', body: { mappings: { product: { properties: { title: { type: 'text' }, category: { type: 'keyword' }, offers: { type: 'nested', properties: { name: { type: 'text' }, price: { type: 'double' } } } } } } } @client.index index: 'products-test', type: 'product', body: { title: 'A', category: 'audio', offers: [ { name: 'A1', price: 100 }, { name: 'A2', price: 120 } ] } @client.index index: 'products-test', type: 'product', body: { title: 'B', category: 'audio', offers: [ { name: 'B1', price: 200 }, { name: 'B2', price: 180 } ] } @client.index index: 'products-test', type: 'product', body: { title: 'C', category: 'video', offers: [ { name: 'C1', price: 300 }, { name: 'C2', price: 350 } ] } @client.indices.refresh index: 'products-test' end should "return the minimal price from offers" do response = @client.search index: 'products-test', body: search { query { match title: 'A' } aggregation :offers do nested do path 'offers' aggregation :min_price do min field: 'offers.price' end end end }.to_hash assert_equal 100, response['aggregations']['offers']['min_price']['value'].to_i end should "return the top categories for offer price range" do response = @client.search index: 'products-test', body: search { query do bool do must do nested do path 'offers' query do bool do filter do range 'offers.price' do gte 100 lte 300 end end end end end end end end aggregation :offers do nested do path 'offers' aggregation :top_categories do reverse_nested do aggregation :top_category_per_offer do terms field: 'category' end end end end end }.to_hash assert_equal 2, response['aggregations']['offers']['top_categories']['top_category_per_offer']['buckets'].size assert_equal 'audio', response['aggregations']['offers']['top_categories']['top_category_per_offer']['buckets'][0]['key'] assert_equal 'video', response['aggregations']['offers']['top_categories']['top_category_per_offer']['buckets'][1]['key'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_aggregations_test.rb000066400000000000000000000233151361161326000316010ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class AggregationsIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Aggregations integration" do setup do @client.indices.create index: 'test', body: { mappings: { d: { properties: { tags: { type: 'keyword' } } } } } @client.index index: 'test', type: 'd', id: '1', body: { title: 'A', tags: %w[one], clicks: 5 } @client.index index: 'test', type: 'd', id: '2', body: { title: 'B', tags: %w[one two], clicks: 15 } @client.index index: 'test', type: 'd', id: '3', body: { title: 'C', tags: %w[one three], clicks: 20 } @client.indices.refresh index: 'test' end context "with a terms aggregation" do should "return tag counts" do response = @client.search index: 'test', body: search { aggregation :tags do terms field: 'tags' end }.to_hash assert_equal 3, response['aggregations']['tags']['buckets'].size assert_equal 'one', response['aggregations']['tags']['buckets'][0]['key'] end should "return approximate tag counts" do response = @client.search index: 'test', body: search { aggregation :tags do cardinality field: 'tags' end }.to_hash assert_equal 3, response['aggregations']['tags']['value'] end should "return tag counts per clicks range as an inner (nested) aggregation" do response = @client.search index: 'test', body: search { aggregation :clicks do range field: 'clicks' do key :low, to: 10 key :mid, from: 10, to: 20 aggregation :tags do terms field: 'tags' end end end }.to_hash assert_equal 2, response['aggregations']['clicks']['buckets'].size assert_equal 1, response['aggregations']['clicks']['buckets']['low']['doc_count'] assert_equal 'one', response['aggregations']['clicks']['buckets']['low']['tags']['buckets'][0]['key'] end should "define multiple aggregations" do response = @client.search index: 'test', body: search { aggregation :clicks do range field: 'clicks' do key :low, to: 10 key :mid, from: 10, to: 20 aggregation :tags do terms { field 'tags' } end end end aggregation :min_clicks do min field: 'clicks' end aggregation :max_clicks do max field: 'clicks' end aggregation :sum_clicks do sum field: 'clicks' end aggregation :avg_clicks do avg field: 'clicks' end }.to_hash assert_equal 2, response['aggregations']['clicks']['buckets'].size assert_equal 1, response['aggregations']['clicks']['buckets']['low']['doc_count'] assert_equal 'one', response['aggregations']['clicks']['buckets']['low']['tags']['buckets'][0]['key'] assert_equal 5, response['aggregations']['min_clicks']['value'] assert_equal 20, response['aggregations']['max_clicks']['value'] assert_equal 40, response['aggregations']['sum_clicks']['value'] assert_equal 13, response['aggregations']['avg_clicks']['value'].to_i end should "define a global aggregation" do response = @client.search index: 'test', body: search { query do bool filter: { terms: { tags: ['two'] } } end aggregation :avg_clicks do avg field: 'clicks' end aggregation :all_documents do global do aggregation :avg_clicks do avg field: 'clicks' end end end }.to_hash assert_equal 15, response['aggregations']['avg_clicks']['value'].to_i assert_equal 13, response['aggregations']['all_documents']['avg_clicks']['value'].to_i end should "return statistics on clicks" do response = @client.search index: 'test', body: search { aggregation :stats_clicks do stats field: 'clicks' end aggregation :value_count do value_count field: 'clicks' end }.to_hash assert_equal 3, response['aggregations']['stats_clicks']['count'] assert_equal 5, response['aggregations']['stats_clicks']['min'] assert_equal 20, response['aggregations']['stats_clicks']['max'] assert_equal 40, response['aggregations']['stats_clicks']['sum'] assert_equal 13, response['aggregations']['stats_clicks']['avg'].to_i assert_equal 3, response['aggregations']['value_count']['value'] end should "return percentiles on clicks" do response = @client.search index: 'test', body: search { aggregation :percentiles do percentiles field: 'clicks' end }.to_hash assert_equal 20, response['aggregations']['percentiles']['values']['99.0'].round end should "return percentile ranks on clicks" do response = @client.search index: 'test', body: search { aggregation :percentiles do percentile_ranks field: 'clicks', values: [5] end }.to_hash assert_equal 17, response['aggregations']['percentiles']['values']['5.0'].round end should "return top hits per tag" do response = @client.search index: 'test', body: search { aggregation :tags do terms do field 'tags' size 5 aggregation :top_hits do top_hits sort: [ clicks: { order: 'desc' } ], _source: { include: 'title' } end end end }.to_hash assert_equal 3, response['aggregations']['tags']['buckets'][0]['top_hits']['hits']['hits'].size assert_equal 'C', response['aggregations']['tags']['buckets'][0]['top_hits']['hits']['hits'][0]['_source']['title'] end should "calculate clicks for a tag" do response = @client.search index: 'test', body: search { aggregation :clicks_for_one do scripted_metric do init_script "params._agg.transactions = []" map_script "if (doc['tags'].value.contains('one')) { params._agg.transactions.add(doc['clicks'].value) }" combine_script "double sum = 0; for (t in params._agg.transactions) { sum += t } return sum" reduce_script "double sum = 0; for (a in params._aggs) { sum += a } return sum" end end }.to_hash assert_equal 40, response['aggregations']['clicks_for_one']['value'] end should "limit the scope with a filter" do response = @client.search index: 'test', body: search { aggregation :clicks_for_one do filter terms: { tags: ['one'] } do aggregation :sum_clicks do sum field: 'clicks' end end end }.to_hash assert_equal 40, response['aggregations']['clicks_for_one']['sum_clicks']['value'] end end should "return aggregations for multiple filters" do response = @client.search index: 'test', body: search { aggregation :avg_clicks_per_tag do filters do filters one: { terms: { tags: ['one'] } }, two: { terms: { tags: ['two'] } } aggregation :avg do avg field: 'clicks' end end end }.to_hash assert_equal 13, response['aggregations']['avg_clicks_per_tag']['buckets']['one']['avg']['value'].to_i assert_equal 15, response['aggregations']['avg_clicks_per_tag']['buckets']['two']['avg']['value'].to_i end should "return a histogram on clicks" do response = @client.search index: 'test', body: search { aggregation :clicks_histogram do histogram do field 'clicks' interval 10 end end }.to_hash assert_equal 3, response['aggregations']['clicks_histogram']['buckets'].size assert_equal 10, response['aggregations']['clicks_histogram']['buckets'][1]['key'] assert_equal 1, response['aggregations']['clicks_histogram']['buckets'][1]['doc_count'] end should "return a histogram with empty buckets on clicks" do response = @client.search index: 'test', body: search { aggregation :clicks_histogram do histogram do field 'clicks' interval 2 min_doc_count 0 end end }.to_hash assert_equal 9, response['aggregations']['clicks_histogram']['buckets'].size end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_filters_test.rb000066400000000000000000000220511361161326000305730ustar00rootroot00000000000000# encoding: UTF-8 require 'test_helper' module Elasticsearch module Test class FiltersIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Filters integration" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'test' @client.index index: 'test', type: 'd', id: 1, body: { name: 'Original', color: 'red', size: 'xxl', category: 'unisex', manufacturer: 'a' } @client.index index: 'test', type: 'd', id: 2, body: { name: 'Original', color: 'red', size: 'xl', category: 'unisex', manufacturer: 'a' } @client.index index: 'test', type: 'd', id: 3, body: { name: 'Original', color: 'red', size: 'l', category: 'unisex', manufacturer: 'a' } @client.index index: 'test', type: 'd', id: 4, body: { name: 'Western', color: 'red', size: 'm', category: 'men', manufacturer: 'c' } @client.index index: 'test', type: 'd', id: 5, body: { name: 'Modern', color: 'grey', size: 'l', category: 'men', manufacturer: 'b' } @client.index index: 'test', type: 'd', id: 6, body: { name: 'Modern', color: 'grey', size: 's', category: 'men', manufacturer: 'b' } @client.index index: 'test', type: 'd', id: 7, body: { name: 'Modern', color: 'grey', size: 's', category: 'women', manufacturer: 'b' } @client.indices.refresh index: 'test' end context "term filter" do should "return matching documents" do response = @client.search index: 'test', body: search { query do bool do filter do term color: 'red' end end end }.to_hash assert_equal 4, response['hits']['total'] assert response['hits']['hits'].all? { |h| h['_source']['color'] == 'red' }, response.inspect end end context "terms filter" do should "return matching documents" do response = @client.search index: 'test', body: search { query do bool do filter do terms color: ['red', 'grey', 'gold'] end end end }.to_hash assert_equal 7, response['hits']['total'] end end context "bool filter" do should "return correct documents" do response = @client.search index: 'test', body: search { query do bool do filter do bool do must do term size: 'l' end should do term color: 'red' end should do term category: 'men' end must_not do term manufacturer: 'b' end end end end end }.to_hash assert_equal 1, response['hits']['hits'].size assert_equal '3', response['hits']['hits'][0]['_id'].to_s end end context "geographical filters" do setup do @client.indices.create index: 'places', body: { mappings: { d: { properties: { location: { type: 'geo_point' } } } } } @client.index index: 'places', type: 'd', id: 1, body: { name: 'Vyšehrad', location: '50.064399, 14.420018'} @client.index index: 'places', type: 'd', id: 2, body: { name: 'Karlštejn', location: '49.939518, 14.188046'} @client.indices.refresh index: 'places' end should "find documents within the bounding box" do response = @client.search index: 'places', body: search { query do bool do filter do geo_bounding_box :location do top_right "50.1815123678,14.7149200439" bottom_left "49.9415476869,14.2162566185" end end end end }.to_hash assert_equal 1, response['hits']['hits'].size assert_equal 'Vyšehrad', response['hits']['hits'][0]['_source']['name'] end should "find documents within the distance specified with a hash" do response = @client.search index: 'places', body: search { query do bool do filter do geo_distance location: '50.090223,14.399590', distance: '5km' end end end }.to_hash assert_equal 1, response['hits']['hits'].size assert_equal 'Vyšehrad', response['hits']['hits'][0]['_source']['name'] end should "find documents within the distance specified with a block" do response = @client.search index: 'places', body: search { query do bool do filter do geo_distance :location do lat '50.090223' lon '14.399590' distance '5km' end end end end }.to_hash assert_equal 1, response['hits']['hits'].size assert_equal 'Vyšehrad', response['hits']['hits'][0]['_source']['name'] end should "find documents within the geographical distance range" do response = @client.search index: 'places', body: search { query do bool do filter do geo_distance location: { lat: '50.090223', lon: '14.399590' }, distance: '50km' end end end aggregation :distance_ranges do geo_distance do field :location origin '50.090223,14.399590' unit 'km' ranges [ { from: 10, to: 50 } ] aggregation :results do top_hits _source: { include: 'name' } end end end }.to_hash assert_equal 2, response['hits']['hits'].size bucket = response['aggregations']['distance_ranges']['buckets'][0] assert_equal 1, bucket['doc_count'] assert_equal 1, bucket['results']['hits']['hits'].size assert_equal 'Karlštejn', bucket['results']['hits']['hits'][0]['_source']['name'] end should "find documents within the polygon" do response = @client.search index: 'places', body: search { query do bool do filter do geo_polygon :location do points [ [14.2244355,49.9419006], [14.2244355,50.1774301], [14.7067869,50.1774301], [14.7067869,49.9419006], [14.2244355,49.9419006] ] end end end end }.to_hash assert_equal 1, response['hits']['hits'].size assert_equal 'Vyšehrad', response['hits']['hits'][0]['_source']['name'] end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_options_test.rb000066400000000000000000000015411361161326000306170ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchOptionsIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Search options" do setup do @client.indices.create index: 'test' @client.index index: 'test', type: 'd', id: '1', body: { title: 'Test' } @client.index index: 'test', type: 'd', id: '2', body: { title: 'Rest' } @client.indices.refresh index: 'test' end should "explain the match" do response = @client.search index: 'test', body: search { query { match title: 'test' } explain true }.to_hash assert_equal 1, response['hits']['total'] assert_not_nil response['hits']['hits'][0]['_explanation'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_query_test.rb000066400000000000000000000052501361161326000302720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class QueryIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Queries integration" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'test' @client.index index: 'test', type: 'd', id: '1', body: { title: 'Test', tags: ['one'] } @client.index index: 'test', type: 'd', id: '2', body: { title: 'Rest', tags: ['one', 'two'] } @client.indices.refresh index: 'test' end context "for match query" do should "find the document" do response = @client.search index: 'test', body: search { query { match title: 'test' } }.to_hash assert_equal 1, response['hits']['total'] end end context "for match_phrase_prefix query" do should "find the document" do response = @client.search index: 'test', body: search { query { match_phrase_prefix title: 'te' } }.to_hash assert_equal 1, response['hits']['total'] end end context "for query_string query" do should "find the document" do response = @client.search index: 'test', body: search { query { query_string { query 'te*' } } }.to_hash assert_equal 1, response['hits']['total'] end end context "for the bool query" do should "find the document" do response = @client.search index: 'test', body: search { query do bool do must { terms tags: ['one'] } should { match title: 'Test' } end end }.to_hash assert_equal 2, response['hits']['total'] assert_equal 'Test', response['hits']['hits'][0]['_source']['title'] end should "find the document with a filter" do skip "Not supported on this Elasticsearch version" unless @version > '2' response = @client.search index: 'test', body: search { query do bool do filter { terms tags: ['one'] } filter { terms tags: ['two'] } end end }.to_hash assert_equal 1, response['hits']['total'] assert_equal 'Rest', response['hits']['hits'][0]['_source']['title'] end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_size_from_test.rb000066400000000000000000000030151361161326000311170ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SizeIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Search results pagination" do setup do @client.indices.create index: 'test', body: { mappings: { d: { properties: { title: { type: 'text', fields: { keyword: { type: 'keyword' } } } } } } } 25.times { |i| @client.index index: 'test', type: 'd', id: i, body: { title: "Test #{sprintf('%03d', i)}" } } @client.indices.refresh index: 'test' end should "find the correct number of documents" do response = @client.search index: 'test', body: search { query { match title: 'test' } size 15 }.to_hash assert_equal 25, response['hits']['total'] assert_equal 15, response['hits']['hits'].size end should "move the offset" do response = @client.search index: 'test', body: search { query { match(:title) { query 'test' } } size 5 from 5 sort { by 'title.keyword' } }.to_hash assert_equal 25, response['hits']['total'] assert_equal 5, response['hits']['hits'].size assert_equal 'Test 005', response['hits']['hits'][0]['_source']['title'] assert_equal 'Test 009', response['hits']['hits'][4]['_source']['title'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_sort_test.rb000066400000000000000000000023511361161326000301130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SortingIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Sorting integration" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'test' @client.index index: 'test', type: 'd', id: '1', body: { tags: ['one'], clicks: 15 } @client.index index: 'test', type: 'd', id: '2', body: { tags: ['one', 'two'], clicks: 5 } @client.index index: 'test', type: 'd', id: '3', body: { tags: ['one', 'three'], clicks: 20 } @client.indices.refresh index: 'test' end context "sorting by clicks" do should "return documents in order" do response = @client.search index: 'test', body: search { sort do by :clicks, order: 'desc' end }.to_hash assert_same_elements ['3', '1', '2'], response['hits']['hits'].map { |d| d['_id'] } end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_suggest_test.rb000066400000000000000000000051301361161326000306030ustar00rootroot00000000000000# encoding: UTF-8 require 'test_helper' module Elasticsearch module Test class SuggestIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Suggest integration" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'test', body: { mappings: { d: { properties: { title: { type: 'text' }, suggest: { type: 'object', properties: { title: { type: 'completion' }, payload: { type: 'object', enabled: false } } } } } } } @client.index index: 'test', type: 'd', id: '1', body: { title: 'One', suggest: { title: { input: ['one', 'uno', 'jedna'] }, payload: { id: '1' } } } @client.index index: 'test', type: 'd', id: '2', body: { title: 'Two', suggest: { title: { input: ['two', 'due', 'dvě'] }, payload: { id: '2' } } } @client.index index: 'test', type: 'd', id: '3', body: { title: 'Three', suggest: { title: { input: ['three', 'tres', 'tři'] }, payload: { id: '3' } } } @client.indices.refresh index: 'test' end should "return suggestions" do s = search do suggest :title, text: 't', completion: { field: 'suggest.title' } end response = @client.search index: 'test', body: s.to_hash assert_equal 2, response['suggest']['title'][0]['options'].size assert_same_elements %w[2 3], response['suggest']['title'][0]['options'].map { |d| d['_source']['suggest']['payload']['id'] } end should "return a single suggestion" do s = search do suggest :title, text: 'th', completion: { field: 'suggest.title' } end response = @client.search index: 'test', body: s.to_hash assert_equal 1, response['suggest']['title'][0]['options'].size assert_same_elements %w[3], response['suggest']['title'][0]['options'].map { |d| d['_source']['suggest']['payload']['id'] } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/integration/search_test.rb000066400000000000000000000034221361161326000270440ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search class MySearch include Elasticsearch::DSL::Search def initialize(q) @q = q end def tags %w[ one two ] end def search_definition search do |q| q.query do |q| q.bool do |q| q.must do |q| q.match title: @q end q.must do |q| q.terms tags: tags end end end end end end context "The Search class" do startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end setup do @client.indices.create index: 'test' @client.index index: 'test', type: 'd', id: '1', body: { title: 'Test', tags: ['one'] } @client.index index: 'test', type: 'd', id: '2', body: { title: 'Test', tags: ['one', 'two'] } @client.index index: 'test', type: 'd', id: '3', body: { title: 'Test', tags: ['three'] } @client.indices.refresh index: 'test' end should "have access to the calling context" do s = MySearch.new('test') response = @client.search index: 'test', body: s.search_definition.to_hash assert_equal 2, response['hits']['total'] assert_equal 'Test', response['hits']['hits'][0]['_source']['title'] assert_same_elements ['1', '2'], response['hits']['hits'].map { |d| d['_id'] } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/test_helper.rb000066400000000000000000000051021361161326000245300ustar00rootroot00000000000000JRUBY = defined?(JRUBY_VERSION) if ENV['COVERAGE'] || ENV['CI'] require 'simplecov' SimpleCov.start { add_filter "/test|test_" } end ELASTICSEARCH_HOSTS = if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end end.freeze at_exit { Elasticsearch::Test::IntegrationTestCase.__run_at_exit_hooks } require 'minitest/autorun' require 'shoulda-context' require 'mocha/setup' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new # Minitest::Reporters.use! [ Minitest::Reporters::SpecReporter.new, # Minitest::Reporters::JUnitReporter.new, # Minitest::Reporters::HtmlReporter.new ] require 'elasticsearch' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/dsl' module Elasticsearch module Test module Assertions def assert_nothing_raised(*) yield end end class UnitTestCase < ::Minitest::Test include Assertions alias_method :assert_not_nil, :refute_nil alias_method :assert_raise, :assert_raises end class IntegrationTestCase < ::Minitest::Test include Assertions alias_method :assert_not_nil, :refute_nil alias_method :assert_raise, :assert_raises include Elasticsearch::Extensions::Test extend StartupShutdown startup do Cluster.start(number_of_nodes: 1) if ENV['SERVER'] \ && ! Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 1) end shutdown do Cluster.stop if ENV['SERVER'] \ && started? \ && Elasticsearch::Extensions::Test::Cluster.running? end def setup @logger = Logger.new(STDERR) @logger.formatter = proc do |severity, datetime, progname, msg| color = case severity when /INFO/ then :green when /ERROR|WARN|FATAL/ then :red when /DEBUG/ then :cyan else :white end ANSI.ansi(severity[0] + ' ', color, :faint) + ANSI.ansi(msg, :white, :faint) + "\n" end @client = Elasticsearch::Client.new hosts: ELASTICSEARCH_HOSTS, logger: (ENV['QUIET'] ? nil : @logger) @version = @client.info['version']['number'] end def teardown @client.indices.delete index: '_all' end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/000077500000000000000000000000001361161326000226465ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/dsl_test.rb000066400000000000000000000007411361161326000250160ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class DSLTest < ::Elasticsearch::Test::UnitTestCase context "The DSL" do class DummyDSLReceiver include Elasticsearch::DSL end should "include the module in receiver" do assert_contains DummyDSLReceiver.included_modules, Elasticsearch::DSL assert_contains DummyDSLReceiver.included_modules, Elasticsearch::DSL::Search end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_aggregation_test.rb000066400000000000000000000043661361161326000300570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchAggregationTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Aggregation.new } context "Search Aggregation" do should "be serializable to a Hash" do assert_equal( {}, subject.to_hash ) subject = Elasticsearch::DSL::Search::Aggregation.new subject.instance_variable_set(:@value, { foo: 'bar' }) assert_equal( { foo: 'bar' }, subject.to_hash ) end should "evaluate the block and return itself" do block = Proc.new { 1+1 } subject = Elasticsearch::DSL::Search::Aggregation.new &block subject.expects(:instance_eval) assert_instance_of Elasticsearch::DSL::Search::Aggregation, subject.call end should "call the block and return itself" do block = Proc.new { |s| 1+1 } subject = Elasticsearch::DSL::Search::Aggregation.new &block block.expects(:call) assert_instance_of Elasticsearch::DSL::Search::Aggregation, subject.call end should "define the value with DSL methods" do assert_nothing_raised do subject.terms field: 'foo' assert_instance_of Hash, subject.to_hash assert_equal( { terms: { field: 'foo' } }, subject.to_hash ) end end should "raise an exception for unknown DSL method" do assert_raise(NoMethodError) { subject.foofoo } end should "return the aggregations" do subject.expects(:call) subject.instance_variable_set(:@value, mock(aggregations: { foo: 'bar' })) subject.aggregations end should "define a nested aggregation" do subject.instance_variable_set(:@value, mock(aggregation: true)) subject.aggregation(:foo) { 1+1 } end should "return a non-hashy value directly" do subject.instance_variable_set(:@value, 'FOO') assert_equal 'FOO', subject.to_hash end should "return an empty Hash when it has no value set" do subject.instance_variable_set(:@value, nil) assert_equal({}, subject.to_hash) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_base_aggregation_component_test.rb000066400000000000000000000025221361161326000331230ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class BaseAggregationComponentTest < ::Elasticsearch::Test::UnitTestCase context "BaseAggregationComponent" do class DummyAggregationComponent include ::Elasticsearch::DSL::Search::BaseAggregationComponent end class ::Elasticsearch::DSL::Search::Aggregations::Dummy include ::Elasticsearch::DSL::Search::BaseAggregationComponent end subject { DummyAggregationComponent.new } should "return an instance of the aggregation by name" do assert_instance_of ::Elasticsearch::DSL::Search::Aggregations::Dummy, subject.dummy end should "raise an exception when unknown aggregation is called" do assert_raise(NoMethodError) { subject.foobar } end should "add a nested aggregation" do subject.aggregation :inner do dummy field: 'foo' end assert ! subject.aggregations.empty?, "#{subject.aggregations.inspect} is empty" assert_instance_of Elasticsearch::DSL::Search::Aggregation, subject.aggregations[:inner] assert_equal( {:dummy=>{:field=>"foo"}}, subject.aggregations[:inner].to_hash ) assert_equal 'foo', subject.to_hash[:aggregations][:inner][:dummy][:field] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_base_component_test.rb000066400000000000000000000136021361161326000305550ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class BaseComponentTest < ::Elasticsearch::Test::UnitTestCase context "BaseComponent" do class DummyComponent include Elasticsearch::DSL::Search::BaseComponent end class DummyComponentWithAName include Elasticsearch::DSL::Search::BaseComponent name :foo end class DummyComponentWithNewName include Elasticsearch::DSL::Search::BaseComponent end class DummyCompoundFilter include Elasticsearch::DSL::Search::BaseCompoundFilterComponent end subject { DummyComponent.new :foo } should "have a name" do assert_equal :dummy_component, DummyComponent.new.name end should "have a custom name" do assert_equal :foo, DummyComponentWithAName.new.name end should "allow to set a name" do DummyComponentWithNewName.name :foo assert_equal :foo, DummyComponentWithNewName.new.name assert_equal :foo, DummyComponentWithNewName.name DummyComponentWithNewName.name = :bar assert_equal :bar, DummyComponentWithNewName.name assert_equal :bar, DummyComponentWithNewName.new.name end should "initialize the hash" do assert_instance_of Hash, subject.to_hash end should "have an empty Hash as args by default" do subject = DummyComponentWithNewName.new assert_equal({}, subject.instance_variable_get(:@args)) end should "have an option method with args" do class DummyComponentWithOptionMethod include Elasticsearch::DSL::Search::BaseComponent option_method :bar end subject = DummyComponentWithOptionMethod.new :foo assert_respond_to subject, :bar subject.bar 'BAM' assert_equal({ dummy_component_with_option_method: { foo: { bar: 'BAM' } } }, subject.to_hash) end should "keep track of option methods" do class DummyComponentWithCustomOptionMethod include Elasticsearch::DSL::Search::BaseComponent option_method :foo end subject = DummyComponentWithCustomOptionMethod assert_includes subject.option_methods, :foo end should "have an option method without args" do class DummyComponentWithOptionMethod include Elasticsearch::DSL::Search::BaseComponent option_method :bar end subject = DummyComponentWithOptionMethod.new assert_respond_to subject, :bar subject.bar 'BAM' assert_equal({ dummy_component_with_option_method: { bar: 'BAM' } }, subject.to_hash) end should "define a custom option method" do class DummyComponentWithCustomOptionMethod include Elasticsearch::DSL::Search::BaseComponent option_method :bar, lambda { |*args| @hash = { :foo => 'bar' } } end subject = DummyComponentWithCustomOptionMethod.new subject.bar assert_equal 'bar', subject.instance_variable_get(:@hash)[:foo] end should "execute the passed block" do subject = DummyComponent.new(:foo) { @foo = 'BAR' } assert_respond_to subject, :call assert_instance_of DummyComponent, subject.call assert_equal 'BAR', subject.instance_variable_get(:@foo) end should "respond to empty?" do assert DummyComponent.new.empty? assert DummyComponent.new(:foo).empty? subject = DummyComponent.new(:foo) { @hash = { foo: 'bar' } } assert ! subject.empty? end context "to_hash conversion" do should "build the hash with the block with args" do subject = DummyComponent.new :foo do @hash[:dummy_component][:foo].update moo: 'xoo' end assert_equal({dummy_component: { foo: { moo: 'xoo' } } }, subject.to_hash ) end should "build the hash with the block without args" do subject = DummyComponent.new do @hash[:dummy_component].update moo: 'xoo' end assert_equal({dummy_component: { moo: 'xoo' } }, subject.to_hash ) end should "build the hash with the option method" do class DummyComponentWithOptionMethod include Elasticsearch::DSL::Search::BaseComponent option_method :foo end subject = DummyComponentWithOptionMethod.new do foo 'bar' end assert_equal({ dummy_component_with_option_method: { foo: 'bar' } }, subject.to_hash) end should "build the hash with the passed args" do subject = DummyComponent.new foo: 'bar' assert_equal({ dummy_component: { foo: 'bar' } }, subject.to_hash) end should "merge the top-level options to the hash" do class DummyComponentWithOptionMethod include Elasticsearch::DSL::Search::BaseComponent option_method :bar end subject = DummyComponentWithOptionMethod.new :foo, xoo: 'X' do bar 'B' end assert_equal({ dummy_component_with_option_method: { xoo: 'X', foo: { bar: 'B' } } }, subject.to_hash) end should "return the already built hash" do subject = DummyComponent.new subject.instance_variable_set(:@hash, { foo: 'bar' }) assert_equal({ foo: 'bar' }, subject.to_hash) end end context "compound filter" do subject { DummyCompoundFilter.new } should "raise an exception for unknown DSL method" do assert_raise(NoMethodError) { subject.foofoo } end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_filter_test.rb000066400000000000000000000035351361161326000270520ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchFilterTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Filter.new } context "Search Filter" do should "be serializable to a Hash" do assert_equal( {}, subject.to_hash ) subject = Elasticsearch::DSL::Search::Filter.new subject.instance_variable_set(:@value, { foo: 'bar' }) assert_equal( { foo: 'bar' }, subject.to_hash ) end should "evaluate the block and return itself" do block = Proc.new { 1+1 } subject = Elasticsearch::DSL::Search::Filter.new &block subject.expects(:instance_eval) assert_instance_of Elasticsearch::DSL::Search::Filter, subject.call end should "call the block and return itself" do block = Proc.new { |s| 1+1 } subject = Elasticsearch::DSL::Search::Filter.new &block block.expects(:call) assert_instance_of Elasticsearch::DSL::Search::Filter, subject.call end should "define the value with filter methods" do assert_nothing_raised do subject.term foo: 'bar' assert_instance_of Hash, subject.to_hash assert_equal( { term: { foo: 'bar' } }, subject.to_hash ) end end should "redefine the value with filter methods" do assert_nothing_raised do subject.term foo: 'bar' subject.term foo: 'bam' subject.to_hash subject.to_hash assert_instance_of Hash, subject.to_hash assert_equal({ term: { foo: 'bam' } }, subject.to_hash) end end should "raise an exception for unknown filter" do assert_raise(NoMethodError) { subject.foofoo } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_highlight_test.rb000066400000000000000000000047771361161326000275450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class HighlightTest < ::Elasticsearch::Test::UnitTestCase context "Search highlight" do subject { Elasticsearch::DSL::Search::Highlight.new } should "take a Hash" do subject = Elasticsearch::DSL::Search::Highlight.new fields: { 'foo' => {} }, pre_tags: ['*'], post_tags: ['*'] assert_equal({ fields: { 'foo' => {} }, pre_tags: ['*'], post_tags: ['*'] }, subject.to_hash) end should "encode fields as an array" do subject.fields ['foo', 'bar'] assert_equal({ fields: { foo: {}, bar: {} } }, subject.to_hash) end should "encode fields as a Hash" do subject.fields foo: { bar: 1 }, xoo: { bar: 2 } assert_equal({ fields: { foo: { bar: 1 }, xoo: { bar: 2 } } }, subject.to_hash) end should "encode a field" do subject.field 'foo' assert_equal({ fields: { foo: {} } }, subject.to_hash) end should "be additive on multiple calls" do subject.fields ['foo', 'bar'] subject.field 'bam' subject.field 'baz', { xoo: 10 } assert_equal({ fields: { foo: {}, bar: {}, bam: {}, baz: { xoo: 10 } } }, subject.to_hash) end should "encode pre_tags" do subject.pre_tags '*' assert_equal({ pre_tags: ['*'] }, subject.to_hash) end should "encode post_tags" do subject.post_tags '*' assert_equal({ post_tags: ['*'] }, subject.to_hash) end should "encode pre_tags as an array" do subject.pre_tags ['*', '**'] assert_equal({ pre_tags: ['*', '**'] }, subject.to_hash) end should "encode post_tags as an array" do subject.post_tags ['*', '**'] assert_equal({ post_tags: ['*', '**'] }, subject.to_hash) end should "encode the encoder option" do subject.encoder 'foo' assert_equal({ encoder: 'foo' }, subject.to_hash) end should "encode the tags_schema option" do subject.tags_schema 'foo' assert_equal({ tags_schema: 'foo' }, subject.to_hash) end should "combine the options" do subject.fields ['foo', 'bar'] subject.field 'bam' subject.pre_tags '*' subject.post_tags '*' assert_equal({ fields: { foo: {}, bar: {}, bam: {} }, pre_tags: ['*'], post_tags: ['*'] }, subject.to_hash) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_options_test.rb000066400000000000000000000046121361161326000272550ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchOptionsTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Options.new } context "Search options" do should "combine different options" do subject.version true subject.min_score 0.5 assert_equal({version: true, min_score: 0.5}, subject.to_hash) end should "encode _source" do subject._source false assert_equal( { _source: false }, subject.to_hash ) subject._source 'foo.*' assert_equal( { _source: 'foo.*' }, subject.to_hash ) subject._source ['foo', 'bar'] assert_equal( { _source: ['foo', 'bar'] }, subject.to_hash ) subject._source include: ['foo.*'], exclude: ['bar.*'] assert_equal( { _source: { include: ['foo.*'], exclude: ['bar.*'] } }, subject.to_hash ) subject.source false assert_equal( { _source: false }, subject.to_hash ) end should "encode fields" do subject.fields ['foo'] assert_equal( { fields: ['foo'] }, subject.to_hash ) end should "encode script_fields" do subject.script_fields ['foo'] assert_equal( { script_fields: ['foo'] }, subject.to_hash ) end should "encode fielddata_fields" do subject.fielddata_fields ['foo'] assert_equal( { fielddata_fields: ['foo'] }, subject.to_hash ) end should "encode rescore" do subject.rescore foo: 'bar' assert_equal( { rescore: { foo: 'bar' } }, subject.to_hash ) end should "encode explain" do subject.explain true assert_equal( { explain: true }, subject.to_hash ) end should "encode version" do subject.version true assert_equal( { version: true }, subject.to_hash ) end should "encode indices_boost" do subject.indices_boost foo: 'bar' assert_equal( { indices_boost: { foo: 'bar' } }, subject.to_hash ) end should "encode track_scores" do subject.track_scores true assert_equal( { track_scores: true }, subject.to_hash ) end should "encode min_score" do subject.min_score 0.5 assert_equal( { min_score: 0.5 }, subject.to_hash ) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_query_test.rb000066400000000000000000000036641361161326000267350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchQueryTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Query.new } context "Search Query" do should "be serializable to a Hash" do assert_equal( {}, subject.to_hash ) subject = Elasticsearch::DSL::Search::Query.new subject.instance_variable_set(:@value, {}) assert_equal( {}, subject.to_hash ) end should "evaluate the block and return itself" do block = Proc.new { 1+1 } subject = Elasticsearch::DSL::Search::Query.new &block subject.expects(:instance_eval) assert_instance_of Elasticsearch::DSL::Search::Query, subject.call end should "call the block and return itself" do block = Proc.new { |s| 1+1 } subject = Elasticsearch::DSL::Search::Query.new &block block.expects(:call) assert_instance_of Elasticsearch::DSL::Search::Query, subject.call end should "define the value with query methods" do assert_nothing_raised do subject.match foo: 'bar' assert_instance_of Hash, subject.to_hash assert_equal( { match: { foo: 'bar' } }, subject.to_hash ) end end should "redefine the value with query methods" do assert_nothing_raised do subject.match foo: 'bar' subject.match foo: 'bam' subject.to_hash subject.to_hash assert_instance_of Hash, subject.to_hash assert_equal({ match: { foo: 'bam' } }, subject.to_hash) end end should "have the query methods" do assert_nothing_raised { subject.match foo: 'bar' } end should "raise an exception for unknown query" do assert_raise(NoMethodError) { subject.foofoo } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_size_from_test.rb000066400000000000000000000023101361161326000275500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchSizeTest < ::Elasticsearch::Test::UnitTestCase context "Search pagination" do should "encode the size parameter" do subject = Elasticsearch::DSL::Search::Search.new do size 5 end assert_equal( { size: 5 }, subject.to_hash ) end should "encode the from parameter" do subject = Elasticsearch::DSL::Search::Search.new do from 5 end assert_equal( { from: 5 }, subject.to_hash ) end should "have getter methods" do subject = Elasticsearch::DSL::Search::Search.new assert_nil subject.size assert_nil subject.from subject.size = 5 subject.from = 5 assert_equal 5, subject.size assert_equal 5, subject.from end should "have setter methods" do subject = Elasticsearch::DSL::Search::Search.new subject.size = 5 subject.from = 5 assert_equal 5, subject.size assert_equal 5, subject.from assert_equal( { size: 5, from: 5 }, subject.to_hash ) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_sort_test.rb000066400000000000000000000036571361161326000265610ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchSortTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Sort.new } context "Search sort" do should "add a single field" do subject = Elasticsearch::DSL::Search::Sort.new :foo assert_equal( [:foo], subject.to_hash ) end should "add multiple fields" do subject = Elasticsearch::DSL::Search::Sort.new [:foo, :bar] assert_equal( [:foo, :bar], subject.to_hash ) end should "add a field with options" do subject = Elasticsearch::DSL::Search::Sort.new foo: { order: 'desc', mode: 'avg' } assert_equal( [ { foo: { order: 'desc', mode: 'avg' } } ], subject.to_hash ) end should "add fields with the DSL method" do subject = Elasticsearch::DSL::Search::Sort.new do by :foo by :bar, order: 'desc' end assert_equal( [ :foo, { bar: { order: 'desc' } }, ], subject.to_hash ) end should "be empty" do subject = Elasticsearch::DSL::Search::Sort.new assert_equal subject.empty?, true end should "not be empty" do subject = Elasticsearch::DSL::Search::Sort.new foo: { order: 'desc' } assert_equal subject.empty?, false end context "#to_hash" do should "not duplicate values when defined by arguments" do subject = Elasticsearch::DSL::Search::Sort.new foo: { order: 'desc' } assert_equal(subject.to_hash, subject.to_hash) end should "not duplicate values when defined by a block" do subject = Elasticsearch::DSL::Search::Sort.new do by :foo end assert_equal(subject.to_hash, subject.to_hash) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_suggest_test.rb000066400000000000000000000010521361161326000272360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchSuggestTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Suggest.new :foo } context "Search suggest" do should "be an empty hash by default" do assert_equal({ foo: {} }, subject.to_hash) end should "contain options" do subject = Elasticsearch::DSL::Search::Suggest.new :foo, boo: 'bam' assert_equal({ foo: { boo: 'bam' } }, subject.to_hash) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/search_test.rb000066400000000000000000000174161361161326000255100ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchTest < ::Elasticsearch::Test::UnitTestCase subject { Elasticsearch::DSL::Search::Search.new } context "The Search module" do should "have the search method on instance" do class DummySearchReceiver include Elasticsearch::DSL::Search end assert_instance_of Elasticsearch::DSL::Search::Search, DummySearchReceiver.new.search end should "have the search method on module" do class DummySearchReceiver include Elasticsearch::DSL::Search end assert_instance_of Elasticsearch::DSL::Search::Search, Elasticsearch::DSL::Search.search end should "have access to the calling context" do class DummySearchReceiver include Elasticsearch::DSL::Search def initialize @other_value = 'foo' end def value 42 end def search_definition search do |q| q.from value q.size @other_value q.stored_fields ['term'] q.filter do |q| q._and do |q| q.term thang: @other_value q.term attributes: value end end end end end assert_equal({from: 42, size: 'foo', stored_fields: ['term'], filter: { and: [ { term: { thang: 'foo' } }, { term: { attributes: 42 } }]}}, DummySearchReceiver.new.search_definition.to_hash) end end context "The Search class" do context "with query" do should "take the query as a literal value" do subject.query foo: 'bar' assert_equal({query: { foo: 'bar' }}, subject.to_hash) end should "take the query as a block" do Elasticsearch::DSL::Search::Query.expects(:new).returns({foo: 'bar'}) subject.query do; end assert_equal({query: { foo: 'bar' }}, subject.to_hash) end should "allow chaining" do assert_instance_of Elasticsearch::DSL::Search::Search, subject.query(:foo) assert_instance_of Elasticsearch::DSL::Search::Search, subject.query(:foo).query(:bar) end should "be converted to hash" do assert_equal({}, subject.to_hash) subject.query foo: 'bar' assert_equal({query: { foo: 'bar' }}, subject.to_hash) end should "have a getter/setter method" do assert_nil subject.query subject.query = Object.new assert_not_nil subject.query end end context "with filter" do should "take the filter as a literal value" do subject.filter foo: 'bar' assert_equal({filter: { foo: 'bar' }}, subject.to_hash) end should "take the filter as a block" do Elasticsearch::DSL::Search::Filter.expects(:new).returns({foo: 'bar'}) subject.filter do; end assert_equal({filter: { foo: 'bar' }}, subject.to_hash) end should "allow chaining" do assert_instance_of Elasticsearch::DSL::Search::Search, subject.filter(:foo) assert_instance_of Elasticsearch::DSL::Search::Search, subject.filter(:foo).filter(:bar) end should "be converted to hash" do assert_equal({}, subject.to_hash) subject.filter foo: 'bar' assert_equal({filter: { foo: 'bar' }}, subject.to_hash) end should "have a getter/setter method" do assert_nil subject.filter subject.filter = Object.new assert_not_nil subject.filter end end context "with post_filter" do should "take the filter as a literal value" do subject.post_filter foo: 'bar' assert_equal({post_filter: { foo: 'bar' }}, subject.to_hash) end should "take the filter as a block" do Elasticsearch::DSL::Search::Filter.expects(:new).returns({foo: 'bar'}) subject.post_filter do; end assert_equal({post_filter: { foo: 'bar' }}, subject.to_hash) end should "allow chaining" do assert_instance_of Elasticsearch::DSL::Search::Search, subject.post_filter(:foo) assert_instance_of Elasticsearch::DSL::Search::Search, subject.post_filter(:foo).post_filter(:bar) end should "be converted to hash" do assert_equal({}, subject.to_hash) subject.post_filter foo: 'bar' assert_equal({post_filter: { foo: 'bar' }}, subject.to_hash) end should "have a getter/setter method" do assert_nil subject.post_filter subject.post_filter = Object.new assert_not_nil subject.post_filter end end context "with aggregations" do should "take the aggregation as a literal value" do subject.aggregation :foo, terms: 'bar' assert_equal({aggregations: { foo: { terms: "bar" } } }, subject.to_hash) end should "take the aggregation as a block" do Elasticsearch::DSL::Search::Aggregation.expects(:new).returns({tam: 'tam'}) subject.aggregation :foo do; end assert_equal({aggregations: { foo: { tam: 'tam' } } }, subject.to_hash) end should "allow chaining" do assert_instance_of Elasticsearch::DSL::Search::Search, subject.aggregation(:foo) assert_instance_of Elasticsearch::DSL::Search::Search, subject.aggregation(:foo).aggregation(:bar) end should "be converted to hash" do assert_equal({}, subject.to_hash) subject.post_filter foo: 'bar' assert_equal({post_filter: { foo: 'bar' }}, subject.to_hash) end should "have a getter/setter method" do assert_nil subject.aggregations subject.aggregations = { foo: Object.new } assert_not_nil subject.aggregations end end context "with sorting" do should "be converted to hash" do subject.sort :foo assert_equal( { sort: [ :foo ] }, subject.to_hash ) end should "have a getter method" do assert_nil subject.sort subject.sort :foo assert_instance_of Elasticsearch::DSL::Search::Sort, subject.sort end end context "with suggest" do should "be converted to hash" do subject.suggest :foo, { bar: 'bam' } assert_equal( { suggest: { foo: { bar: 'bam' } } }, subject.to_hash ) end should "have a getter/setter method" do assert_nil subject.suggest subject.suggest = Object.new assert_not_nil subject.suggest end end context "with highlighting" do should "be converted to a hash" do subject.highlight foo: 'bar' assert_not_nil subject.highlight assert_equal( { highlight: { foo: 'bar' } }, subject.to_hash ) end end context "with options" do should "encode options" do subject.explain true subject.fields [:foo, :bar] assert_equal( { explain: true, fields: [:foo, :bar] }, subject.to_hash ) end should "raise an exception for unknown method" do assert_raise(NoMethodError) { subject.foobar true } end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-dsl/test/unit/utils_test.rb000066400000000000000000000011201361161326000253640ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class UtilsTest < ::Elasticsearch::Test::UnitTestCase context "Utils" do should "convert a string to camelcase" do assert_equal 'Foo', Elasticsearch::DSL::Utils.__camelize('foo') end should "convert an underscored string to camelcase" do assert_equal 'FooBar', Elasticsearch::DSL::Utils.__camelize('foo_bar') end should "convert a symbol" do assert_equal 'FooBar', Elasticsearch::DSL::Utils.__camelize(:foo_bar) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/000077500000000000000000000000001361161326000223255ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/.gitignore000066400000000000000000000002321361161326000243120ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp elasticsearch-ruby-6.8.1/elasticsearch-extensions/Gemfile000066400000000000000000000013261361161326000236220ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-extensions.gemspec gemspec if File.exist? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-transport/elasticsearch-transport.gemspec", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch/", __FILE__) end elasticsearch-ruby-6.8.1/elasticsearch-extensions/LICENSE.txt000066400000000000000000000010561361161326000241520ustar00rootroot00000000000000Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-extensions/README.md000066400000000000000000000232501361161326000236060ustar00rootroot00000000000000# Elasticsearch::Extensions This library provides a set of extensions to the [`elasticsearch`](https://github.com/elasticsearch/elasticsearch-ruby) Rubygem. ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch-extensions To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch-extensions', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git' or install it from a source code checkout: git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch-extensions bundle install rake install ## Extensions ### Backup Backup Elasticsearch indices as flat JSON files on the disk via integration with the [_Backup_](http://backup.github.io/backup/v4/) gem. Use the Backup gem's DSL to configure the backup: require 'elasticsearch/extensions/backup' Model.new(:elasticsearch_backup, 'Elasticsearch') do database Elasticsearch do |db| db.url = 'http://localhost:9200' db.indices = 'test' end store_with Local do |local| local.path = '/tmp/backups' end compress_with Gzip end Perform the backup with the Backup gem's command line utility: $ backup perform -t elasticsearch_backup See more information in the [`Backup::Database::Elasticsearch`](lib/extensions/backup.rb) class documentation. ### Reindex Copy documents from one index and cluster into another one, for example for purposes of changing the settings and mappings of the index. **NOTE:** Elasticsearch natively supports re-indexing since version 2.3. This extension is useful when you need the feature on older versions. When the extension is loaded together with the [Ruby client for Elasticsearch](../elasticsearch/README.md), a `reindex` method is added to the client: require 'elasticsearch' require 'elasticsearch/extensions/reindex' client = Elasticsearch::Client.new target_client = Elasticsearch::Client.new url: 'http://localhost:9250', log: true client.index index: 'test', type: 'd', body: { title: 'foo' } client.reindex source: { index: 'test' }, target: { index: 'test', client: target_client }, transform: lambda { |doc| doc['_source']['title'].upcase! }, refresh: true # => { errors: 0 } target_client.search index: 'test' # => ... hits ... "title"=>"FOO" The method takes similar arguments as the core API [`reindex`](http://www.rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions#reindex-instance_method) method. You can also use the `Reindex` class directly: require 'elasticsearch' require 'elasticsearch/extensions/reindex' client = Elasticsearch::Client.new reindex = Elasticsearch::Extensions::Reindex.new \ source: { index: 'test', client: client }, target: { index: 'test-copy' } reindex.perform See more information in the [`Elasticsearch::Extensions::Reindex::Reindex`](lib/extensions/reindex.rb) class documentation. ### ANSI Colorize and format selected Elasticsearch response parts in terminal: Display formatted search results: require 'elasticsearch/extensions/ansi' puts Elasticsearch::Client.new.search.to_ansi Display a table with the output of the `_analyze` API: require 'elasticsearch/extensions/ansi' puts Elasticsearch::Client.new.indices.analyze(text: 'Quick Brown Fox Jumped').to_ansi [Full documentation](http://rubydoc.info/gems/elasticsearch-extensions/Elasticsearch/Extensions/ANSI) ### Test::Cluster Allows to programatically start and stop an Elasticsearch cluster suitable for isolating tests. The HTTP service is running on ports `9250-*` by default. Start and stop the default cluster: require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start Elasticsearch::Extensions::Test::Cluster.stop Start the cluster on specific port, with a specific Elasticsearch version, number of nodes and cluster name: require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start \ cluster_name: "my-testing-cluster", command: "/usr/local/Cellar/elasticsearch/0.90.10/bin/elasticsearch", port: 9350, number_of_nodes: 3 # Starting 3 Elasticsearch nodes..................... # -------------------------------------------------------------------------------- # Cluster: my-testing-cluster # Status: green # Nodes: 3 # - node-1 | version: 1.0.0.Beta2, pid: 54469 # + node-2 | version: 1.0.0.Beta2, pid: 54470 # - node-3 | version: 1.0.0.Beta2, pid: 54468 # => true Stop this cluster: require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.stop port: 9350 # Stopping Elasticsearch nodes... stopped PID 54469. stopped PID 54470. stopped PID 54468. # # => [54469, 54470, 54468] You can control the cluster configuration with environment variables as well: TEST_CLUSTER_NAME=my-testing-cluster \ TEST_CLUSTER_COMMAND=/usr/local/Cellar/elasticsearch/0.90.10/bin/elasticsearch \ TEST_CLUSTER_PORT=9350 \ TEST_CLUSTER_NODES=3 \ TEST_CLUSTER_NAME=my_testing_cluster \ ruby -r elasticsearch -e "require 'elasticsearch/extensions/test/cluster'; Elasticsearch::Extensions::Test::Cluster.start" To prevent deleting data and configurations when the cluster is started, for example in a development environment, use the `clear_cluster: false` option or the `TEST_CLUSTER_CLEAR=false` environment variable. [Full documentation](http://rubydoc.info/gems/elasticsearch-extensions/Elasticsearch/Extensions/Test/Cluster) ### Test::StartupShutdown Allows to register `startup` and `shutdown` hooks for Test::Unit, similarly to RSpec's `before(:all)`, compatible with the [Test::Unit 2](https://github.com/test-unit/test-unit/blob/master/lib/test/unit/testcase.rb) syntax. The extension is useful for e.g. starting the testing Elasticsearch cluster before the test suite is executed, and stopping it afterwards. ** IMPORTANT NOTE ** You have to register the handler for `shutdown` hook before requiring 'test/unit': # File: test_helper.rb at_exit { MyTest.__run_at_exit_hooks } require 'test/unit' Example of handler registration: class MyTest < Test::Unit::TestCase extend Elasticsearch::Extensions::Test::StartupShutdown startup { puts "Suite starting up..." } shutdown { puts "Suite shutting down..." } end [Full documentation](http://rubydoc.info/gems/elasticsearch-extensions/Elasticsearch/Extensions/Test/StartupShutdown) Examples in the Elasticsearch gem test suite: [1](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/test/integration/client_test.rb#L4-L6), [2](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/test/test_helper.rb#L44) ### Test::Profiling Allows to define and execute profiling tests within [Shoulda](https://github.com/thoughtbot/shoulda) contexts. Measures operations and reports statistics, including code profile. Let's define a simple profiling test in a `profiling_test.rb` file: require 'test/unit' require 'shoulda/context' require 'elasticsearch/extensions/test/profiling' class ProfilingTest < Test::Unit::TestCase extend Elasticsearch::Extensions::Test::Profiling context "Mathematics" do measure "divide numbers", count: 10_000 do assert_nothing_raised { 1/2 } end end end Let's run it: $ QUIET=y ruby profiling_test.rb ... ProfilingTest ------------------------------------------------------------------------------- Context: Mathematics should divide numbers (10000x) mean: 0.03ms | avg: 0.03ms | max: 0.14ms ------------------------------------------------------------------------------- PASS (0:00:00.490) test: Mathematics should divide numbers (10000x). ... When using the `QUIET` option, only the statistics on operation throughput are printed. When omitted, the full code profile by [RubyProf](https://github.com/ruby-prof/ruby-prof) is printed. [Full documentation](http://rubydoc.info/gems/elasticsearch-extensions/Elasticsearch/Extensions/Test/StartupShutdown) [Example in the Elasticsearch gem](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/test/profile/client_benchmark_test.rb) ## Development To work on the code, clone and bootstrap the main repository first -- please see instructions in the main [README](../README.md#development). To run tests, launch a testing cluster -- again, see instructions in the main [README](../README.md#development) -- and use the Rake tasks: ``` time rake test:unit time rake test:integration ``` Unit tests have to use Ruby 1.8 compatible syntax, integration tests can use Ruby 2.x syntax and features. ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-extensions/Rakefile000066400000000000000000000036731361161326000240030ustar00rootroot00000000000000require "bundler/gem_tasks" desc "Run unit tests" task :default => 'test:unit' task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' namespace :test do Rake::TestTask.new(:unit) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/**/unit/**/*_test.rb"] test.verbose = false test.warning = false end Rake::TestTask.new(:integration) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/**/integration/**/*_test.rb"] test.verbose = false test.warning = false end Rake::TestTask.new(:all) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/**/unit/**/*_test.rb", "test/**/integration/**/*_test.rb"] end Rake::TestTask.new(:profile) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/profile/**/*_test.rb"] end namespace :cluster do desc "Start Elasticsearch nodes for tests" task :start do $LOAD_PATH << File.expand_path('../lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start end desc "Stop Elasticsearch nodes for tests" task :stop do $LOAD_PATH << File.expand_path('../lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.stop end end end # ----- Documentation tasks --------------------------------------------------- require 'yard' YARD::Rake::YardocTask.new(:doc) do |t| t.options = %w| --embed-mixins --markup=markdown | end # ----- Code analysis tasks --------------------------------------------------- if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'cane/rake_task' Cane::RakeTask.new(:quality) do |cane| cane.abc_max = 15 cane.no_style = true end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/elasticsearch-extensions.gemspec000066400000000000000000000035671361161326000307140ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/extensions/version' Gem::Specification.new do |s| s.name = "elasticsearch-extensions" s.version = Elasticsearch::Extensions::VERSION s.authors = ["Karel Minarik"] s.email = ["karel.minarik@elasticsearch.org"] s.description = %q{Extensions for the Elasticsearch Rubygem} s.summary = %q{Extensions for the Elasticsearch Rubygem} s.homepage = "https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-extensions" s.license = "Apache-2.0" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] s.add_dependency "ansi" s.add_dependency "elasticsearch" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) end s.add_development_dependency "bundler" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "rake", "~> 11.1" else s.add_development_dependency "rake", "< 11.0" end s.add_development_dependency "awesome_print" s.add_development_dependency 'shoulda-context' s.add_development_dependency 'mocha' s.add_development_dependency 'minitest' s.add_development_dependency 'minitest-reporters' s.add_development_dependency 'simplecov' s.add_development_dependency 'yard' s.add_development_dependency 'cane' s.add_development_dependency 'pry' unless defined?(JRUBY_VERSION) s.add_development_dependency 'oj' s.add_development_dependency 'patron' end if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_development_dependency "json", '~> 1.8' end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/000077500000000000000000000000001361161326000230735ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch-extensions.rb000066400000000000000000000000431361161326000304240ustar00rootroot00000000000000require 'elasticsearch/extensions' elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/000077500000000000000000000000001361161326000257055ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions.rb000066400000000000000000000002121361161326000304240ustar00rootroot00000000000000# encoding: utf-8 require 'elasticsearch' require 'elasticsearch/extensions/version' module Elasticsearch module Extensions end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/000077500000000000000000000000001361161326000301045ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/ansi.rb000066400000000000000000000017211361161326000313640ustar00rootroot00000000000000# encoding: utf-8 require 'elasticsearch/extensions' require 'ansi' require 'ansi/table' require 'ansi/terminal' require 'delegate' require 'elasticsearch/transport/transport/response' require 'elasticsearch/extensions/ansi/helpers' require 'elasticsearch/extensions/ansi/actions' require 'elasticsearch/extensions/ansi/response' module Elasticsearch module Extensions # This extension provides a {ResponseBody#to_ansi} method for the Elasticsearch response body, # which colorizes and formats the output with the `ansi` gem. # # @example Display formatted search results # # require 'elasticsearch/extensions/ansi' # puts Elasticsearch::Client.new.search.to_ansi # # @example Display a table with the output of the `_analyze` API # # require 'elasticsearch/extensions/ansi' # puts Elasticsearch::Client.new.indices.analyze(text: 'Quick Brown Fox Jumped').to_ansi # module ANSI end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/000077500000000000000000000000001361161326000310365ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/actions.rb000066400000000000000000000204401361161326000330230ustar00rootroot00000000000000# encoding: utf-8 module Elasticsearch module Extensions module ANSI module Actions # Display shard allocation # def display_allocation_on_nodes(json, options={}) return unless json['routing_nodes'] output = [] << '' json['routing_nodes']['nodes'].each do |id, shards| output << (json['nodes'][id]['name'] || id).to_s.ansi(:bold) + " [#{id}]".ansi(:faint) if shards.empty? output << "No shards".ansi(:cyan) else output << Helpers.table(shards.map do |shard| [ shard['index'], shard['shard'].to_s.ansi( shard['primary'] ? :bold : :clear ), shard['primary'] ? '◼'.ansi(:green) : '◻'.ansi(:yellow) ] end) end end unless json['routing_nodes']['unassigned'].empty? output << 'Unassigned: '.ansi(:faint, :yellow) + "#{json['routing_nodes']['unassigned'].size} shards" output << Helpers.table( json['routing_nodes']['unassigned'].map do |shard| primary = shard['primary'] [ shard['index'], shard['shard'].to_s.ansi( primary ? :bold : :clear ), primary ? '◼'.ansi(:red) : '◻'.ansi(:yellow) ] end, border: false) end output.join("\n") end # Display search results # def display_hits(json, options={}) return unless json['hits'] && json['hits']['hits'] output = [] << '' hits = json['hits']['hits'] source = json['hits']['hits'].any? { |h| h['fields'] } ? 'fields' : '_source' properties = hits.map { |h| h[source] ? h[source].keys : nil }.compact.flatten.uniq max_property_length = properties.map { |d| d.to_s.size }.compact.max.to_i + 1 hits.each_with_index do |hit, i| title = hit[source] && hit[source].select { |k, v| ['title', 'name'].include?(k) }.to_a.first size_length = hits.size.to_s.size+2 padding = size_length output << "#{i+1}. ".rjust(size_length).ansi(:faint) + " <#{hit['_id']}> " + (title ? title.last.to_s.ansi(:bold) : '') output << Helpers.___ ['_score', '_index', '_type'].each do |property| output << ' '*padding + "#{property}: ".rjust(max_property_length+1).ansi(:faint) + hit[property].to_s if hit[property] end hit[source].each do |property, value| output << ' '*padding + "#{property}: ".rjust(max_property_length+1).ansi(:faint) + value.to_s end if hit[source] # Highlight if hit['highlight'] output << "" output << ' '*(padding+max_property_length+1) + "Highlights".ansi(:faint) + "\n" + ' '*(padding+max_property_length+1) + ('─'*10).ansi(:faint) hit['highlight'].each do |property, matches| line = "" line << ' '*padding + "#{property}: ".rjust(max_property_length+1).ansi(:faint) matches.each_with_index do |match, e| line << ' '*padding + ''.rjust(max_property_length+1) if e > 0 line << '…'.ansi(:faint) unless hit[source][property] && hit[source][property].size <= match.size line << match.strip.ansi(:faint).gsub(/\n/, ' ') .gsub(/([^<]+)<\/em>/, '\1'.ansi(:clear, :bold)) .ansi(:faint) line << '…'.ansi(:faint) unless hit[source][property] && hit[source][property].size <= match.size line << ' '*padding + ''.rjust(max_property_length+1) if e > 0 line << "\n" end output << line end end output << "" end output << Helpers.___ output << "#{hits.size.to_s.ansi(:bold)} of #{json['hits']['total'].to_s.ansi(:bold)} results".ansi(:faint) output.join("\n") end # Display terms facets # def display_terms_facets(json, options={}) return unless json['facets'] output = [] << '' facets = json['facets'].select { |name, values| values['_type'] == 'terms' } facets.each do |name, values| longest = values['terms'].map { |t| t['term'].size }.max max = values['terms'].map { |t| t['count'] }.max padding = longest.to_i + max.to_s.size + 5 ratio = ((Helpers.width)-padding)/max.to_f output << "#{'Facet: '.ansi(:faint)}#{Helpers.humanize(name)}" << Helpers.___ values['terms'].each_with_index do |value, i| output << value['term'].ljust(longest).ansi(:bold) + " [" + value['count'].to_s.rjust(max.to_s.size) + "] " + " " + '█' * (value['count']*ratio).ceil end end output.join("\n") end # Display date histogram facets # def display_date_histogram_facets(json, options={}) return unless json['facets'] output = [] << '' facets = json['facets'].select { |name, values| values['_type'] == 'date_histogram' } facets.each do |name, values| max = values['entries'].map { |t| t['count'] }.max padding = 27 ratio = ((Helpers.width)-padding)/max.to_f interval = options[:interval] || 'day' output << "#{'Facet: '.ansi(:faint)}#{Helpers.humanize(name)} #{interval ? ('(by ' + interval + ')').ansi(:faint) : ''}" output << Helpers.___ values['entries'].each_with_index do |value, i| output << Helpers.date(Time.at(value['time'].to_i/1000).utc, interval).rjust(21).ansi(:bold) + " [" + value['count'].to_s.rjust(max.to_s.size) + "] " + " " + '█' * (value['count']*ratio).ceil end end output.join("\n") end # Display histogram facets # def display_histogram_facets(json, options={}) return unless json['facets'] output = [] << '' facets = json['facets'].select { |name, values| values['_type'] == 'histogram' } facets.each do |name, values| max = values['entries'].map { |t| t['count'] }.max padding = 27 ratio = ((Helpers.width)-padding)/max.to_f histogram = values['entries'] histogram.each_with_index do |segment, i| key = (i == 0) ? "<#{histogram[1]['key']}ms" : "#{segment['key']}ms" output << key.rjust(7) + ' ' + '█' * (segment['count']*ratio).ceil + " [#{segment['count']}]" end end output.join("\n") end # Display statistical facets # def display_statistical_facets(json, options={}) return unless json['facets'] output = [] << '' facets = json['facets'].select { |name, values| values['_type'] == 'statistical' } facets.each do |name, facet| output << "#{'Facet: '.ansi(:faint)}#{Helpers.humanize(name)}" << Helpers.___ output << Helpers.table(facet.reject { |k,v| ['_type'].include? k }.to_a.map do |pair| [ Helpers.humanize(pair[0]), pair[1] ] end) end output.join("\n") end # Display the analyze output # def display_analyze_output(json, options={}) return unless json['tokens'] output = [] << '' max_length = json['tokens'].map { |d| d['token'].to_s.size }.max output << Helpers.table(json['tokens'].map do |t| [ t['position'], t['token'].ljust(max_length+5).ansi(:bold), "#{t['start_offset']}–#{t['end_offset']}", t['type'] ] end).to_s output.join("\n") end extend self end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/helpers.rb000066400000000000000000000032241361161326000330260ustar00rootroot00000000000000# encoding: utf-8 module Elasticsearch module Extensions module ANSI module Helpers # Shortcut for {::ANSI::Table.new} # def table(data, options={}, &format) ::ANSI::Table.new(data, options, &format) end # Terminal width, based on {::ANSI::Terminal.terminal_width} # def width ::ANSI::Terminal.terminal_width-5 end # Humanize a string # def humanize(string) string.to_s.gsub(/\_/, ' ').split.map { |s| s.capitalize}.join(' ') end # Return date formatted by interval # def date(date, interval='day') case interval when 'minute' date.strftime('%a %m/%d %H:%M') + ' – ' + (date+60).strftime('%H:%M') when 'hour' date.strftime('%a %m/%d %H:%M') + ' – ' + (date+60*60).strftime('%H:%M') when 'day' date.strftime('%a %m/%d') when 'week' days_to_monday = date.wday!=0 ? date.wday-1 : 6 days_to_sunday = date.wday!=0 ? 7-date.wday : 0 start = (date - days_to_monday*24*60*60).strftime('%a %m/%d') stop = (date+(days_to_sunday*24*60*60)).strftime('%a %m/%d') "#{start} – #{stop}" when 'month' date.strftime('%B %Y') when 'year' date.strftime('%Y') else date.strftime('%Y-%m-%d %H:%M') end end # Output divider # def ___ ('─'*Helpers.width).ansi(:faint) end extend self end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/response.rb000066400000000000000000000032431361161326000332230ustar00rootroot00000000000000module Elasticsearch module Extensions module ANSI # Wrapper for the Elasticsearch response body, which adds a {#to_ansi} method # class ResponseBody < DelegateClass(Hash) def initialize(body) super(body) end # Return a [colorized and formatted](http://en.wikipedia.org/wiki/ANSI_escape_code) # representation of the Elasticsearch response for: # # * Search results (hits and highlights) # * Facets (terms, statistical, histogram, date_histogram) # * Analyze API output # * Shard allocation # # @example Display formatted search results # # require 'elasticsearch/extensions/ansi' # puts Elasticsearch::Client.new.search.to_ansi # # @todo Add all facets and handlers for remaining response parts / types # def to_ansi(options={}) output = Actions.public_methods.select do |m| m.to_s =~ /^display_/ end.map do |m| Actions.send(m, self, options) end unless output.compact.empty? output.compact.join("\n") else self.respond_to?(:awesome_inspect) ? self.awesome_inspect : self.inspect end end end end end end module Elasticsearch module Transport module Transport class Response # Wrap the response body in the {Extensions::ANSI::ResponseBody} class # def body_to_ansi Extensions::ANSI::ResponseBody.new @body end alias_method :body_original, :body alias_method :body, :body_to_ansi end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/backup.rb000066400000000000000000000114601361161326000317000ustar00rootroot00000000000000# encoding: utf-8 require 'pathname' require 'fileutils' require 'multi_json' begin require 'oj' rescue LoadError warn('The "oj" gem could not be loaded. JSON parsing and serialization performance may not be optimal.') end begin require 'patron' rescue LoadError warn('The "patron" gem could not be loaded. HTTP requests may not be performed optimally.') end require 'elasticsearch' module Backup module Database # Integration with the Backup gem [http://backup.github.io/backup/v4/] # # This extension allows to backup Elasticsearch indices as flat JSON files on the disk. # # @example Use the Backup gem's DSL to configure the backup # # require 'elasticsearch/extensions/backup' # # Model.new(:elasticsearch_backup, 'Elasticsearch') do # # database Elasticsearch do |db| # db.url = 'http://localhost:9200' # db.indices = 'articles,people' # db.size = 500 # db.scroll = '10m' # end # # store_with Local do |local| # local.path = '/tmp/backups' # local.keep = 3 # end # # compress_with Gzip # end # # Perform the backup with the Backup gem's command line utility: # # $ backup perform -t elasticsearch_backup # # The Backup gem can store your backup files on S3, Dropbox and other # cloud providers, send notifications about the operation, and so on; # read more in the gem documentation. # # @example Use the integration as a standalone script (eg. in a Rake task) # # require 'backup' # require 'elasticsearch/extensions/backup' # # Backup::Logger.configure do # logfile.enabled = true # logfile.log_path = '/tmp/backups/log' # end; Backup::Logger.start! # # backup = Backup::Model.new(:elasticsearch, 'Backup Elasticsearch') do # database Backup::Database::Elasticsearch do |db| # db.indices = 'test' # end # # store_with Backup::Storage::Local do |local| # local.path = '/tmp/backups' # end # end # # backup.perform! # # @example A simple recover script for the backup created in the previous examples # # PATH = '/path/to/backup/' # # require 'elasticsearch' # client = Elasticsearch::Client.new log: true # payload = [] # # Dir[ File.join( PATH, '**', '*.json' ) ].each do |file| # document = MultiJson.load(File.read(file)) # item = document.merge(data: document['_source']) # document.delete('_source') # document.delete('_score') # # payload << { index: item } # # if payload.size == 100 # client.bulk body: payload # payload = [] # end # # client.bulk body: payload # end # # @see http://backup.github.io/backup/v4/ # class Elasticsearch < Base class Error < ::Backup::Error; end attr_accessor :url, :indices, :size, :scroll attr_accessor :mode def initialize(model, database_id = nil, &block) super @url ||= 'http://localhost:9200' @indices ||= '_all' @size ||= 100 @scroll ||= '10m' @mode ||= 'single' instance_eval(&block) if block_given? end def perform! super case mode when 'single' __perform_single else raise Error, "Unsupported mode [#{mode}]" end log!(:finished) end def client @client ||= ::Elasticsearch::Client.new url: url, logger: logger end def path Pathname.new File.join(dump_path , dump_filename.downcase) end def logger logger = Backup::Logger.__send__(:logger) logger.instance_eval do def debug(*args);end # alias :debug :info alias :fatal :warn end logger end def __perform_single r = client.search index: indices, search_type: 'scan', scroll: scroll, size: size raise Error, "No scroll_id returned in response:\n#{r.inspect}" unless r['_scroll_id'] while r = client.scroll(scroll_id: r['_scroll_id'], scroll: scroll) and not r['hits']['hits'].empty? do r['hits']['hits'].each do |hit| FileUtils.mkdir_p "#{path.join hit['_index'], hit['_type']}" File.open("#{path.join hit['_index'], hit['_type'], hit['_id']}.json", 'w') do |file| file.write MultiJson.dump(hit) end end end end end end end ::Backup::Config::DSL::Elasticsearch = ::Backup::Database::Elasticsearch elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/reindex.rb000066400000000000000000000143751361161326000321010ustar00rootroot00000000000000# encoding: utf-8 module Elasticsearch module Extensions # This module allows copying documents from one index/cluster to another one # # When required together with the client, it will add the `reindex` method # # @see Reindex::Reindex.initialize # @see Reindex::Reindex#perform # # @see http://www.rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions#reindex-instance_method # module Reindex # Initialize a new instance of the Reindex class (shortcut) # # @see Reindex::Reindex.initialize # def new(arguments={}) Reindex.new(arguments) end; extend self module API # Copy documents from one index into another and refresh the target index # # @example # client.reindex source: { index: 'test1' }, target: { index: 'test2' }, refresh: true # # The method allows all the options as {Reindex::Reindex.new}. # # This method will be mixed into the Elasticsearch client's API, if available. # def reindex(arguments={}) arguments[:source] ||= {} arguments[:source][:client] = self Reindex.new(arguments).perform end end # Include the `reindex` method in the API and client, if available Elasticsearch::API::Actions.__send__ :include, API if defined?(Elasticsearch::API::Actions) Elasticsearch::Transport::Client.__send__ :include, API if defined?(Elasticsearch::Transport::Client) && defined?(Elasticsearch::API) # Copy documents from one index into another # # @example Copy documents to another index # # client = Elasticsearch::Client.new # reindex = Elasticsearch::Extensions::Reindex.new \ # source: { index: 'test1', client: client }, # target: { index: 'test2' } # # reindex.perform # # @example Copy documents to a different cluster # # source_client = Elasticsearch::Client.new url: 'http://localhost:9200' # target_client = Elasticsearch::Client.new url: 'http://localhost:9250' # # reindex = Elasticsearch::Extensions::Reindex.new \ # source: { index: 'test', client: source_client }, # target: { index: 'test', client: target_client } # reindex.perform # # @example Transform the documents during re-indexing # # reindex = Elasticsearch::Extensions::Reindex.new \ # source: { index: 'test1', client: client }, # target: { index: 'test2' }, # transform: lambda { |doc| doc['_source']['category'].upcase! } # # # The reindexing process works by "scrolling" an index and sending # batches via the "Bulk" API to the target index/cluster # # @option arguments [String] :source The source index/cluster definition (*Required*) # @option arguments [String] :target The target index/cluster definition (*Required*) # @option arguments [Proc] :transform A block which will be executed for each document # @option arguments [Integer] :batch_size The size of the batch for scroll operation (Default: 1000) # @option arguments [String] :scroll The timeout for the scroll operation (Default: 5min) # @option arguments [Boolean] :refresh Whether to refresh the target index after # the operation is completed (Default: false) # # Be aware, that if you want to change the target index settings and/or mappings, # you have to do so in advance by using the "Indices Create" API. # # Note, that there is a native "Reindex" API in Elasticsearch 2.3.x and higer versions, # which will be more performant than the Ruby version. # # @see http://www.rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions#reindex-instance_method # class Reindex attr_reader :arguments def initialize(arguments={}) [ [:source, :index], [:source, :client], [:target, :index] ].each do |required_option| value = required_option.reduce(arguments) { |sum, o| sum = sum[o] ? sum[o] : {} } raise ArgumentError, "Required argument '#{Hash[*required_option]}' missing" if \ value.respond_to?(:empty?) ? value.empty? : value.nil? end @arguments = { batch_size: 1000, scroll: '5m', refresh: false }.merge(arguments) arguments[:target][:client] ||= arguments[:source][:client] end # Performs the operation # # @return [Hash] A Hash with the information about the operation outcome # def perform output = { errors: 0 } response = arguments[:source][:client].search( index: arguments[:source][:index], scroll: arguments[:scroll], size: arguments[:batch_size] ) documents = response['hits']['hits'] unless documents.empty? bulk_response = __store_batch(documents) output[:errors] += bulk_response['items'].select { |k, v| k.values.first['error'] }.size end while response = arguments[:source][:client].scroll(scroll_id: response['_scroll_id'], scroll: arguments[:scroll]) do documents = response['hits']['hits'] break if documents.empty? bulk_response = __store_batch(documents) output[:errors] += bulk_response['items'].select { |k, v| k.values.first['error'] }.size end arguments[:target][:client].indices.refresh index: arguments[:target][:index] if arguments[:refresh] output end def __store_batch(documents) body = documents.map do |doc| doc['_index'] = arguments[:target][:index] arguments[:transform].call(doc) if arguments[:transform] doc['data'] = doc['_source'] doc.delete('_score') doc.delete('_source') { index: doc } end arguments[:target][:client].bulk body: body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/test/000077500000000000000000000000001361161326000310635ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/test/cluster.rb000066400000000000000000000646461361161326000331110ustar00rootroot00000000000000require 'timeout' require 'net/http' require 'fileutils' require 'socket' require 'uri' require 'json' require 'ansi' STDOUT.sync = true STDERR.sync = true class String # Redefine the ANSI method: do not print ANSI when not running in the terminal # def ansi(*args) STDOUT.tty? ? ANSI.ansi(self, *args) : self end end module Elasticsearch module Extensions module Test # A convenience Ruby class for starting and stopping an Elasticsearch cluster, # eg. for integration tests # # @example Start a cluster with default configuration, # assuming `elasticsearch` is on $PATH. # # require 'elasticsearch/extensions/test/cluster' # Elasticsearch::Extensions::Test::Cluster.start # # @example Start a cluster with a specific Elasticsearch launch script, # eg. from a downloaded `.tar.gz` distribution # # system 'wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.1.1.tar.gz' # system 'tar -xvf elasticsearch-5.1.1.tar.gz' # # require 'elasticsearch/extensions/test/cluster' # Elasticsearch::Extensions::Test::Cluster.start command: 'elasticsearch-5.1.1/bin/elasticsearch' # # @see Cluster#initialize # module Cluster # Starts a cluster # # @see Cluster#start # def start(arguments={}) Cluster.new(arguments).start end # Stops a cluster # # @see Cluster#stop # def stop(arguments={}) Cluster.new(arguments).stop end # Returns true when a specific test node is running within the cluster # # @see Cluster#running? # def running?(arguments={}) Cluster.new(arguments).running? end # Waits until the cluster is green and prints information # # @see Cluster#wait_for_green # def wait_for_green(arguments={}) Cluster.new(arguments).wait_for_green end module_function :start, :stop, :running?, :wait_for_green class Cluster attr_reader :arguments COMMANDS = { '0.90' => lambda { |arguments, node_number| <<-COMMAND.gsub(/ /, '').gsub(/\n$/, '') #{arguments[:command]} \ -f \ -D es.cluster.name=#{arguments[:cluster_name]} \ -D es.node.name=#{arguments[:node_name]}-#{node_number} \ -D es.http.port=#{arguments[:port].to_i + (node_number-1)} \ -D es.path.data=#{arguments[:path_data]} \ -D es.path.work=#{arguments[:path_work]} \ -D es.path.logs=#{arguments[:path_logs]} \ -D es.cluster.routing.allocation.disk.threshold_enabled=false \ -D es.network.host=#{arguments[:network_host]} \ -D es.discovery.zen.ping.multicast.enabled=#{arguments[:multicast_enabled]} \ -D es.script.inline=true \ -D es.script.indexed=true \ -D es.node.test=true \ -D es.node.testattr=test \ -D es.node.bench=true \ -D es.path.repo=/tmp \ -D es.repositories.url.allowed_urls=http://snapshot.test* \ -D es.logger.level=#{ENV['DEBUG'] ? 'DEBUG' : 'INFO'} \ #{arguments[:es_params]} COMMAND }, '1.0' => lambda { |arguments, node_number| <<-COMMAND.gsub(/ /, '').gsub(/\n$/, '') #{arguments[:command]} \ -D es.foreground=yes \ -D es.cluster.name=#{arguments[:cluster_name]} \ -D es.node.name=#{arguments[:node_name]}-#{node_number} \ -D es.http.port=#{arguments[:port].to_i + (node_number-1)} \ -D es.path.data=#{arguments[:path_data]} \ -D es.path.work=#{arguments[:path_work]} \ -D es.path.logs=#{arguments[:path_logs]} \ -D es.cluster.routing.allocation.disk.threshold_enabled=false \ -D es.network.host=#{arguments[:network_host]} \ -D es.discovery.zen.ping.multicast.enabled=#{arguments[:multicast_enabled]} \ -D es.script.inline=on \ -D es.script.indexed=on \ -D es.node.test=true \ -D es.node.testattr=test \ -D es.node.bench=true \ -D es.path.repo=/tmp \ -D es.repositories.url.allowed_urls=http://snapshot.test* \ -D es.logger.level=#{ENV['DEBUG'] ? 'DEBUG' : 'INFO'} \ #{arguments[:es_params]} COMMAND }, '2.0' => lambda { |arguments, node_number| <<-COMMAND.gsub(/ /, '').gsub(/\n$/, '') #{arguments[:command]} \ -D es.foreground=yes \ -D es.cluster.name=#{arguments[:cluster_name]} \ -D es.node.name=#{arguments[:node_name]}-#{node_number} \ -D es.http.port=#{arguments[:port].to_i + (node_number-1)} \ -D es.path.data=#{arguments[:path_data]} \ -D es.path.work=#{arguments[:path_work]} \ -D es.path.logs=#{arguments[:path_logs]} \ -D es.cluster.routing.allocation.disk.threshold_enabled=false \ -D es.network.host=#{arguments[:network_host]} \ -D es.script.inline=true \ -D es.script.stored=true \ -D es.node.attr.testattr=test \ -D es.path.repo=/tmp \ -D es.repositories.url.allowed_urls=http://snapshot.test* \ -D es.logger.level=#{ENV['DEBUG'] ? 'DEBUG' : 'INFO'} \ #{arguments[:es_params]} COMMAND }, '5.0' => lambda { |arguments, node_number| <<-COMMAND.gsub(/ /, '').gsub(/\n$/, '') #{arguments[:command]} \ -E cluster.name=#{arguments[:cluster_name]} \ -E node.name=#{arguments[:node_name]}-#{node_number} \ -E http.port=#{arguments[:port].to_i + (node_number-1)} \ -E path.data=#{arguments[:path_data]} \ -E path.logs=#{arguments[:path_logs]} \ -E cluster.routing.allocation.disk.threshold_enabled=false \ -E network.host=#{arguments[:network_host]} \ -E script.inline=true \ -E script.stored=true \ -E node.attr.testattr=test \ -E path.repo=/tmp \ -E repositories.url.allowed_urls=http://snapshot.test* \ -E discovery.zen.minimum_master_nodes=#{arguments[:number_of_nodes]-1} \ -E node.max_local_storage_nodes=#{arguments[:number_of_nodes]} \ -E logger.level=#{ENV['DEBUG'] ? 'DEBUG' : 'INFO'} \ #{arguments[:es_params]} COMMAND }, '6.0' => lambda { |arguments, node_number| <<-COMMAND.gsub(/ /, '').gsub(/\n$/, '') #{arguments[:command]} \ -E cluster.name=#{arguments[:cluster_name]} \ -E node.name=#{arguments[:node_name]}-#{node_number} \ -E http.port=#{arguments[:port].to_i + (node_number-1)} \ -E path.data=#{arguments[:path_data]} \ -E path.logs=#{arguments[:path_logs]} \ -E cluster.routing.allocation.disk.threshold_enabled=false \ -E network.host=#{arguments[:network_host]} \ -E node.attr.testattr=test \ -E path.repo=/tmp \ -E repositories.url.allowed_urls=http://snapshot.test* \ -E discovery.zen.minimum_master_nodes=#{arguments[:number_of_nodes]-1} \ -E node.max_local_storage_nodes=#{arguments[:number_of_nodes]} \ -E logger.level=#{ENV['DEBUG'] ? 'DEBUG' : 'INFO'} \ #{arguments[:es_params]} COMMAND } } COMMANDS['7.0'] = COMMANDS['6.0'].clone COMMANDS.freeze # Create a new instance of the Cluster class # # @option arguments [String] :cluster_name Cluster name (default: `elasticsearch_test`) # @option arguments [Integer] :number_of_nodes Number of desired nodes (default: 2) # @option arguments [String] :command Elasticsearch command (default: `elasticsearch`) # @option arguments [String] :port Starting port number; will be auto-incremented (default: 9250) # @option arguments [String] :node_name The node name (will be appended with a number) # @option arguments [String] :path_data Path to the directory to store data in # @option arguments [String] :path_work Path to the directory with auxiliary files # @option arguments [String] :path_logs Path to the directory with log files # @option arguments [Boolean] :multicast_enabled Whether multicast is enabled (default: true) # @option arguments [Integer] :timeout Timeout when starting the cluster (default: 60) # @option arguments [Integer] :timeout_version Timeout when waiting for `elasticsearch --version` (default: 15) # @option arguments [String] :network_host The host that nodes will bind on and publish to # @option arguments [Boolean] :clear_cluster Wipe out cluster content on startup (default: true) # @option arguments [Boolean] :quiet Disable printing to STDERR (default: false) # # You can also use environment variables to set the constructor options (see source). # # @see Cluster#start # def initialize(arguments={}) @arguments = arguments.dup @arguments[:command] ||= ENV.fetch('TEST_CLUSTER_COMMAND', 'elasticsearch') @arguments[:port] ||= ENV.fetch('TEST_CLUSTER_PORT', 9250).to_i @arguments[:cluster_name] ||= ENV.fetch('TEST_CLUSTER_NAME', __default_cluster_name).chomp @arguments[:node_name] ||= ENV.fetch('TEST_CLUSTER_NODE_NAME', 'node') @arguments[:path_data] ||= ENV.fetch('TEST_CLUSTER_DATA', '/tmp/elasticsearch_test') @arguments[:path_work] ||= ENV.fetch('TEST_CLUSTER_TMP', '/tmp') @arguments[:path_logs] ||= ENV.fetch('TEST_CLUSTER_LOGS', '/tmp/log/elasticsearch') @arguments[:es_params] ||= ENV.fetch('TEST_CLUSTER_PARAMS', '') @arguments[:multicast_enabled] ||= ENV.fetch('TEST_CLUSTER_MULTICAST', 'true') @arguments[:timeout] ||= ENV.fetch('TEST_CLUSTER_TIMEOUT', 60).to_i @arguments[:timeout_version] ||= ENV.fetch('TEST_CLUSTER_TIMEOUT_VERSION', 15).to_i @arguments[:number_of_nodes] ||= ENV.fetch('TEST_CLUSTER_NODES', 2).to_i @arguments[:network_host] ||= ENV.fetch('TEST_CLUSTER_NETWORK_HOST', __default_network_host) @arguments[:quiet] ||= ! ENV.fetch('QUIET', '').empty? @clear_cluster = !!@arguments[:clear_cluster] || (ENV.fetch('TEST_CLUSTER_CLEAR', 'true') != 'false') # Make sure `cluster_name` is not dangerous raise ArgumentError, "The `cluster_name` argument cannot be empty string or a slash" \ if @arguments[:cluster_name] =~ /^[\/\\]?$/ end # Starts a cluster # # Launches the specified number of nodes in a test-suitable configuration and prints # information about the cluster -- unless this specific cluster is already running. # # @example Start a cluster with the default configuration (2 nodes, installed version, etc) # Elasticsearch::Extensions::Test::Cluster::Cluster.new.start # # @example Start a cluster with a custom configuration # Elasticsearch::Extensions::Test::Cluster::Cluster.new( # cluster_name: 'my-cluster', # number_of_nodes: 3, # node_name: 'my-node', # port: 9350 # ).start # # @example Start a cluster with a different Elasticsearch version # Elasticsearch::Extensions::Test::Cluster::Cluster.new( # command: "/usr/local/Cellar/elasticsearch/1.0.0.Beta2/bin/elasticsearch" # ).start # # @return Boolean,Array # @see Cluster#stop # def start if self.running? __log "[!] Elasticsearch cluster already running".ansi(:red) return false end __remove_cluster_data if @clear_cluster __log "Starting ".ansi(:faint) + arguments[:number_of_nodes].to_s.ansi(:bold, :faint) + " Elasticsearch #{arguments[:number_of_nodes] < 2 ? 'node' : 'nodes'}..".ansi(:faint), :print pids = [] __log "\nUsing Elasticsearch version [#{version}]" if ENV['DEBUG'] arguments[:number_of_nodes].times do |n| n += 1 command = __command(version, arguments, n) command += '> /dev/null' unless ENV['DEBUG'] __log command.gsub(/ {1,}/, ' ').ansi(:bold) if ENV['DEBUG'] pid = Process.spawn(command) Process.detach pid pids << pid sleep 1 end __check_for_running_processes(pids) wait_for_green __log __cluster_info return true end # Stops the cluster # # Fetches the PID numbers from "Nodes Info" API and terminates matching nodes. # # @example Stop the default cluster # Elasticsearch::Extensions::Test::Cluster::Cluster.new.stop # # @example Stop the cluster reachable on specific port # Elasticsearch::Extensions::Test::Cluster::Cluster.new(port: 9350).stop # # @return Boolean,Array # @see Cluster#start # def stop begin nodes = __get_nodes rescue Exception => e __log "[!] Exception raised when stopping the cluster: #{e.inspect}".ansi(:red) nil end return false if nodes.nil? or nodes.empty? pids = nodes['nodes'].map { |id, info| info['process']['id'] } unless pids.empty? __log "Stopping Elasticsearch nodes... ".ansi(:faint), :print pids.each_with_index do |pid, i| ['INT','KILL'].each do |signal| begin Process.kill signal, pid rescue Exception => e __log "[#{e.class}] PID #{pid} not found. ".ansi(:red), :print end # Give the system some breathing space to finish... Kernel.sleep 1 # Check that pid really is dead begin Process.getpgid pid # `getpgid` will raise error if pid is dead, so if we get here, try next signal next rescue Errno::ESRCH __log "Stopped PID #{pid}".ansi(:green) + (ENV['DEBUG'] ? " with #{signal} signal".ansi(:green) : '') + ". ".ansi(:green), :print break # pid is dead end end end __log "\n" else return false end return pids end # Returns true when a specific test node is running within the cluster # # @return Boolean # def running? if cluster_health = Timeout::timeout(0.25) { __get_cluster_health } rescue nil return cluster_health['cluster_name'] == arguments[:cluster_name] && \ cluster_health['number_of_nodes'] == arguments[:number_of_nodes] end return false end # Waits until the cluster is green and prints information about it # # @return Boolean # def wait_for_green __wait_for_status('green', arguments[:timeout]) end # Returns the major version of Elasticsearch # # @return String # @see __determine_version # def version @version ||= __determine_version end # Returns default `:network_host` setting based on the version # # @api private # # @return String # def __default_network_host case version when /^0|^1/ '0.0.0.0' when /^2/ '_local_' when /^5|^6|^7/ '_local_' else raise RuntimeError, "Cannot determine default network host from version [#{version}]" end end # Returns a reasonably unique cluster name # # @api private # # @return String # def __default_cluster_name "elasticsearch-test-#{Socket.gethostname.downcase}" end # Returns the HTTP URL for the cluster based on `:network_host` setting # # @api private # # @return String # def __cluster_url if '_local_' == arguments[:network_host] "http://localhost:#{arguments[:port]}" else "http://#{arguments[:network_host]}:#{arguments[:port]}" end end # Determine Elasticsearch version to be launched # # Tries to get the version from the arguments passed, # if not available, it parses the version number from the `lib/elasticsearch-X.Y.Z.jar` file, # if that is not available, uses `elasticsearch --version` or `elasticsearch -v` # # @api private # # @return String # def __determine_version path_to_lib = File.dirname(arguments[:command]) + '/../lib/' version = if arguments[:version] arguments[:version] elsif File.exist?(path_to_lib) && !(jar = Dir.entries(path_to_lib).select { |f| f =~ /^elasticsearch\-\d/ }.first).nil? __log "Determining version from [#{jar}]" if ENV['DEBUG'] if m = jar.match(/elasticsearch\-(\S+-)?(?\d+\.\d+\.\d+).*/) m[:version] else raise RuntimeError, "Cannot determine Elasticsearch version from jar [#{jar}]" end else __log "[!] Cannot find Elasticsearch .jar from path to command [#{arguments[:command]}], using `#{arguments[:command]} --version`" if ENV['DEBUG'] unless File.exist? arguments[:command] __log "File [#{arguments[:command]}] does not exists, checking full path by `which`: ", :print if ENV['DEBUG'] begin full_path = `which #{arguments[:command]}`.strip __log "#{full_path.inspect}\n", :print if ENV['DEBUG'] rescue Exception => e raise RuntimeError, "Cannot determine full path to [#{arguments[:command]}] with 'which'" end if full_path.empty? raise Errno::ENOENT, "Cannot find Elasticsearch launch script from [#{arguments[:command]}] -- did you pass a correct path?" end end output = '' begin # First, try the new `--version` syntax... __log "Running [#{arguments[:command]} --version] to determine version" if ENV['DEBUG'] io = IO.popen("#{arguments[:command]} --version") pid = io.pid Timeout::timeout(arguments[:timeout_version]) do Process.wait(pid) output = io.read end rescue Timeout::Error # ...else, the old `-v` syntax __log "Running [#{arguments[:command]} -v] to determine version" if ENV['DEBUG'] output = `#{arguments[:command]} -v` ensure if pid Process.kill('INT', pid) rescue Errno::ESRCH # Most likely the process has terminated already end io.close unless io.closed? end STDERR.puts "> #{output}" if ENV['DEBUG'] if output.empty? raise RuntimeError, "Cannot determine Elasticsearch version from [#{arguments[:command]} --version] or [#{arguments[:command]} -v]" end if m = output.match(/Version: (\d\.\d.\d).*,/) m[1] else raise RuntimeError, "Cannot determine Elasticsearch version from elasticsearch --version output [#{output}]" end end case version when /^0\.90.*/ '0.90' when /^1\..*/ '1.0' when /^2\..*/ '2.0' when /^5\..*/ '5.0' when /^6\..*/ '6.0' when /^7\..*/ '7.0' else raise RuntimeError, "Cannot determine major version from [#{version}]" end end # Returns the launch command for a specific version # # @api private # # @return String # def __command(version, arguments, node_number) if command = COMMANDS[version] command.call(arguments, node_number) else raise ArgumentError, "Cannot find command for version [#{version}]" end end # Blocks the process and waits for the cluster to be in a "green" state # # Prints information about the cluster on STDOUT if the cluster is available. # # @param status [String] The status to wait for (yellow, green) # @param timeout [Integer] The explicit timeout for the operation # # @api private # # @return Boolean # def __wait_for_status(status='green', timeout=30) begin Timeout::timeout(timeout) do loop do response = __get_cluster_health(status) __log response if ENV['DEBUG'] if response && response['status'] == status && ( arguments[:number_of_nodes].nil? || arguments[:number_of_nodes].to_i == response['number_of_nodes'].to_i ) break end __log '.'.ansi(:faint), :print sleep 1 end end rescue Timeout::Error => e message = "\nTimeout while waiting for cluster status [#{status}]" message += " and [#{arguments[:number_of_nodes]}] nodes" if arguments[:number_of_nodes] __log message.ansi(:red, :bold) raise e end return true end # Return information about the cluster # # @api private # # @return String # def __cluster_info health = JSON.parse(Net::HTTP.get(URI("#{__cluster_url}/_cluster/health"))) nodes = if version == '0.90' JSON.parse(Net::HTTP.get(URI("#{__cluster_url}/_nodes/?process&http"))) else JSON.parse(Net::HTTP.get(URI("#{__cluster_url}/_nodes/process,http"))) end master = JSON.parse(Net::HTTP.get(URI("#{__cluster_url}/_cluster/state")))['master_node'] result = ["\n", ('-'*80).ansi(:faint), 'Cluster: '.ljust(20).ansi(:faint) + health['cluster_name'].to_s.ansi(:faint), 'Status: '.ljust(20).ansi(:faint) + health['status'].to_s.ansi(:faint), 'Nodes: '.ljust(20).ansi(:faint) + health['number_of_nodes'].to_s.ansi(:faint)].join("\n") nodes['nodes'].each do |id, info| m = id == master ? '*' : '-' result << "\n" + ''.ljust(20) + "#{m} ".ansi(:faint) + "#{info['name'].ansi(:bold)} ".ansi(:faint) + "| version: #{info['version'] rescue 'N/A'}, ".ansi(:faint) + "pid: #{info['process']['id'] rescue 'N/A'}, ".ansi(:faint) + "address: #{info['http']['bound_address'] rescue 'N/A'}".ansi(:faint) end result end # Tries to load cluster health information # # @api private # # @return Hash,Nil # def __get_cluster_health(status=nil) uri = URI("#{__cluster_url}/_cluster/health") uri.query = "wait_for_status=#{status}" if status begin response = Net::HTTP.get(uri) rescue Exception => e STDERR.puts e.inspect if ENV['DEBUG'] return nil end JSON.parse(response) end # Remove the data directory # # @api private # def __remove_cluster_data FileUtils.rm_rf arguments[:path_data] end # Check whether process for PIDs are running # # @api private # def __check_for_running_processes(pids) if `ps -p #{pids.join(' ')}`.split("\n").size < arguments[:number_of_nodes]+1 __log "\n[!!!] Process failed to start (see output above)".ansi(:red) exit(1) end end # Get the information about nodes # # @api private # def __get_nodes JSON.parse(Net::HTTP.get(URI("#{__cluster_url}/_nodes/process"))) end # Print to STDERR # def __log(message, mode=:puts) STDERR.__send__ mode, message unless @arguments[:quiet] end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/test/cluster/000077500000000000000000000000001361161326000325445ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/test/cluster/tasks.rb000066400000000000000000000005011361161326000342120ustar00rootroot00000000000000require 'elasticsearch/extensions/test/cluster' namespace :elasticsearch do desc "Start Elasticsearch cluster for tests" task :start do Elasticsearch::Extensions::Test::Cluster.start end desc "Stop Elasticsearch cluster for tests" task :stop do Elasticsearch::Extensions::Test::Cluster.stop end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/test/profiling.rb000066400000000000000000000073051361161326000334060ustar00rootroot00000000000000require 'ruby-prof' require 'benchmark' require 'ansi' module Elasticsearch module Extensions module Test # Allows to define and execute profiling tests within [Shoulda](https://github.com/thoughtbot/shoulda) contexts. # # Measures operations and reports statistics, including code profile. # # Uses the "benchmark" standard library and the "ruby-prof" gem. # # File: profiling_test.rb # # require 'test/unit' # require 'shoulda/context' # require 'elasticsearch/extensions/test/profiling' # # class ProfilingTest < Test::Unit::TestCase # extend Elasticsearch::Extensions::Test::Profiling # # context "Mathematics" do # measure "divide numbers", count: 10_000 do # assert_nothing_raised { 1/2 } # end # end # # end # # $ QUIET=y ruby profiling_test.rb # # ... # ProfilingTest # # ------------------------------------------------------------------------------- # Context: Mathematics should divide numbers (10000x) # mean: 0.03ms | avg: 0.03ms | max: 0.14ms # ------------------------------------------------------------------------------- # PASS (0:00:00.490) test: Mathematics should divide numbers (10000x). # ... # module Profiling # Profiles the passed block of code. # # measure "divide numbers", count: 10_000 do # assert_nothing_raised { 1/2 } # end # # @todo Try to make progress bar not to interfere with tests # def measure(name, options={}, &block) ___ = '-'*ANSI::Terminal.terminal_width test_name = name suite_name = self.name.split('::').last context_name = self.context(nil) {}.first.parent.name count = Integer(ENV['COUNT'] || options[:count] || 1_000) ticks = [] progress = ANSI::Progressbar.new(suite_name, count) unless ENV['QUIET'] || options[:quiet] should "#{test_name} (#{count}x)" do RubyProf.start begin count.times do ticks << Benchmark.realtime { self.instance_eval(&block) } if progress RubyProf.pause progress.inc RubyProf.resume end end ensure result = RubyProf.stop progress.finish if progress end total = result.threads.reduce(0) { |t,info| t += info.total_time; t } mean = (ticks.sort[(ticks.size/2).round-1])*1000 avg = (ticks.inject {|sum,el| sum += el; sum}.to_f/ticks.size)*1000 min = ticks.min*1000 max = ticks.max*1000 result.eliminate_methods!([/Integer#times|Benchmark.realtime|ANSI::Code#.*|ANSI::ProgressBar#.*/]) printer = RubyProf::FlatPrinter.new(result) # printer = RubyProf::GraphPrinter.new(result) puts "\n", ___, "#{suite_name}: " + ANSI.bold(context_name) + ' should ' + ANSI.bold(name) + " (#{count}x)", "total: #{sprintf('%.2f', total)}s | " + "mean: #{sprintf('%.2f', mean)}ms | " + "avg: #{sprintf('%.2f', avg)}ms | " + "min: #{sprintf('%.2f', min)}ms | " + "max: #{sprintf('%.2f', max)}ms", ___ printer.print(STDOUT, {}) unless ENV['QUIET'] || options[:quiet] end end end end end end startup_shutdown.rb000066400000000000000000000027531361161326000347750ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/testmodule Elasticsearch module Extensions module Test # Startup/shutdown support for test suites # # Example: # # class MyTest < Test::Unit::TestCase # extend Elasticsearch::Extensions::Test::StartupShutdown # # startup { puts "Suite starting up..." } # shutdown { puts "Suite shutting down..." } # end # # *** IMPORTANT NOTE: ********************************************************** # # You have to register the handler for shutdown before requiring 'test/unit': # # # File: test_helper.rb # at_exit { MyTest.__run_at_exit_hooks } # require 'test/unit' # # The API follows Test::Unit 2.0 # # module StartupShutdown @@started = false @@shutdown_blocks ||= [] def startup &block return if started? @@started = true yield block if block_given? end def shutdown &block @@shutdown_blocks << block if block_given? end def started? !! @@started end def __run_at_exit_hooks return unless started? STDERR.puts ANSI.faint("Running at_exit hooks...") puts ANSI.faint('-'*80) @@shutdown_blocks.each { |b| b.call } puts ANSI.faint('-'*80) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/lib/elasticsearch/extensions/version.rb000066400000000000000000000001121361161326000321100ustar00rootroot00000000000000module Elasticsearch module Extensions VERSION = "0.0.31" end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/000077500000000000000000000000001361161326000233045ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/ansi/000077500000000000000000000000001361161326000242365ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/ansi/unit/000077500000000000000000000000001361161326000252155ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/ansi/unit/ansi_test.rb000066400000000000000000000034541361161326000275410ustar00rootroot00000000000000require 'test_helper' require 'elasticsearch/extensions/ansi' class Elasticsearch::Extensions::AnsiTest < Elasticsearch::Test::UnitTestCase context "The ANSI extension" do setup do @client = Elasticsearch::Client.new @client.stubs(:perform_request).returns \ Elasticsearch::Transport::Transport::Response.new(200, { "ok" => true, "status" => 200, "name" => "Hit-Maker", "version" => { "number" => "0.90.7", "build_hash" => "abc123", "build_timestamp"=>"2013-11-13T12:06:54Z", "build_snapshot"=>false, "lucene_version"=>"4.5.1" }, "tagline"=>"You Know, for Search" }) end should "wrap the response" do response = @client.info assert_instance_of Elasticsearch::Extensions::ANSI::ResponseBody, response assert_instance_of Hash, response.to_hash end should "extend the response object with `to_ansi`" do response = @client.info assert_respond_to response, :to_ansi assert_instance_of String, response.to_ansi end should "call the 'awesome_inspect' method when available and no handler found" do @client.stubs(:perform_request).returns \ Elasticsearch::Transport::Transport::Response.new(200, {"index-1"=>{"aliases"=>{}}}) response = @client.cat.aliases response.instance_eval do def awesome_inspect; "---PRETTY---"; end end assert_equal '---PRETTY---', response.to_ansi end should "call `to_s` method when no pretty printer or handler found" do @client.stubs(:perform_request).returns \ Elasticsearch::Transport::Transport::Response.new(200, {"index-1"=>{"aliases"=>{}}}) response = @client.cat.aliases assert_equal '{"index-1"=>{"aliases"=>{}}}', response.to_ansi end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/backup/000077500000000000000000000000001361161326000245515ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/backup/unit/000077500000000000000000000000001361161326000255305ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/backup/unit/backup_test.rb000066400000000000000000000053771361161326000303750ustar00rootroot00000000000000require 'test_helper' require 'logger' # Mock the Backup modules and classes so we're not depending on the gem in the unit test # module Backup class Error < StandardError; end class Logger < ::Logger def self.logger self.new($stderr) end end module Config module DSL end end module Database class Base def initialize(model, database_id = nil) end def dump_path; 'dump_path'; end def dump_filename; 'dump_filename'; end def log!(*args) puts "LOGGING..." if ENV['DEBUG'] end def perform! puts "PERFORMING..." if ENV['DEBUG'] end end end end require 'elasticsearch/extensions/backup' class Elasticsearch::Extensions::BackupTest < Elasticsearch::Test::UnitTestCase context "The Backup gem extension" do setup do @model = stub trigger: true @subject = ::Backup::Database::Elasticsearch.new(@model) end should "have a client" do assert_instance_of Elasticsearch::Transport::Client, @subject.client end should "have a path" do assert_instance_of Pathname, @subject.path end should "have defaults" do assert_equal 'http://localhost:9200', @subject.url assert_equal '_all', @subject.indices end should "be configurable" do @subject = ::Backup::Database::Elasticsearch.new(@model) do |db| db.url = 'https://example.com' db.indices = 'foo,bar' end assert_equal 'https://example.com', @subject.url assert_equal 'foo,bar', @subject.indices assert_equal 'example.com', @subject.client.transport.connections.first.host[:host] end should "perform the backup" do @subject.expects(:__perform_single) @subject.perform! end should "raise an expection for an unsupported type of backup" do @subject = ::Backup::Database::Elasticsearch.new(@model) { |db| db.mode = 'foobar' } assert_raise ::Backup::Database::Elasticsearch::Error do @subject.perform! end end should "scan and scroll the index" do @subject = ::Backup::Database::Elasticsearch.new(@model) { |db| db.indices = 'test' } @subject.client .expects(:search) .with do |params| assert_equal 'test', params[:index] true # Thanks, Ruby 2.2 end .returns({"_scroll_id" => "abc123"}) @subject.client .expects(:scroll) .twice .returns({"_scroll_id" => "def456", "hits" => { "hits" => [ {"_index"=>"test", "_type"=>"doc", "_id"=>"1", "_source"=>{"title"=>"Test"}} ] } }) .then .returns({"_scroll_id" => "ghi789", "hits" => { "hits" => [] } }) @subject.__perform_single end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/reindex/000077500000000000000000000000001361161326000247425ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/reindex/integration/000077500000000000000000000000001361161326000272655ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/reindex/integration/reindex_test.rb000066400000000000000000000061161361161326000323130ustar00rootroot00000000000000require 'test_helper' require 'elasticsearch/extensions/reindex' class Elasticsearch::Extensions::ReindexIntegrationTest < Elasticsearch::Test::IntegrationTestCase context "The Reindex extension" do setup do @logger = ::Logger.new(STDERR) @logger.formatter = proc do |severity, datetime, progname, msg| color = case severity when /INFO/ then :green when /ERROR|WARN|FATAL/ then :red when /DEBUG/ then :cyan else :white end ANSI.ansi(severity[0] + ' ', color, :faint) + ANSI.ansi(msg, :white, :faint) + "\n" end @client = Elasticsearch::Client.new host: "#{TEST_HOST}:#{TEST_PORT}", logger: @logger @client.indices.delete index: '_all' @client.index index: 'test1', type: 'd', id: 1, body: { title: 'TEST 1', category: 'one' } @client.index index: 'test1', type: 'd', id: 2, body: { title: 'TEST 2', category: 'two' } @client.index index: 'test1', type: 'd', id: 3, body: { title: 'TEST 3', category: 'three' } @client.indices.refresh index: 'test1' @client.indices.create index: 'test2' @client.cluster.health wait_for_status: 'yellow' end teardown do @client.indices.delete index: '_all' end should "copy documents from one index to another" do reindex = Elasticsearch::Extensions::Reindex.new \ source: { index: 'test1', client: @client }, target: { index: 'test2' }, batch_size: 2, refresh: true result = reindex.perform assert_equal 0, result[:errors] assert_equal 3, @client.search(index: 'test2')['hits']['total'] end should "transform documents with a lambda" do reindex = Elasticsearch::Extensions::Reindex.new \ source: { index: 'test1', client: @client }, target: { index: 'test2' }, transform: lambda { |d| d['_source']['category'].upcase! }, refresh: true result = reindex.perform assert_equal 0, result[:errors] assert_equal 3, @client.search(index: 'test2')['hits']['total'] assert_equal 'ONE', @client.get(index: 'test2', type: 'd', id: 1)['_source']['category'] end should "return the number of errors" do @client.indices.create index: 'test3', body: { mappings: { d: { properties: { category: { type: 'integer' } }}}} @client.cluster.health wait_for_status: 'yellow' reindex = Elasticsearch::Extensions::Reindex.new \ source: { index: 'test1', client: @client }, target: { index: 'test3' } result = reindex.perform @client.indices.refresh index: 'test3' assert_equal 3, result[:errors] assert_equal 0, @client.search(index: 'test3')['hits']['total'] end should "reindex via the API integration" do @client.indices.create index: 'test4' @client.reindex source: { index: 'test1' }, target: { index: 'test4' } @client.indices.refresh index: 'test4' assert_equal 3, @client.search(index: 'test4')['hits']['total'] end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/reindex/unit/000077500000000000000000000000001361161326000257215ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/reindex/unit/reindex_test.rb000066400000000000000000000076541361161326000307570ustar00rootroot00000000000000require 'test_helper' require 'elasticsearch/extensions/reindex' class Elasticsearch::Extensions::ReindexTest < Elasticsearch::Test::UnitTestCase context "The Reindex extension module" do DEFAULT_OPTIONS = { source: { index: 'foo', client: Object.new }, target: { index: 'bar' } } should "require options" do assert_raise ArgumentError do Elasticsearch::Extensions::Reindex.new end end should "allow to initialize the class" do assert_instance_of Elasticsearch::Extensions::Reindex::Reindex, Elasticsearch::Extensions::Reindex.new(DEFAULT_OPTIONS) end should "add the reindex to the API and client" do assert_includes Elasticsearch::API::Actions.public_instance_methods.sort, :reindex assert_respond_to Elasticsearch::Client.new, :reindex end should "pass the client when used in API mode" do client = Elasticsearch::Client.new Elasticsearch::Extensions::Reindex::Reindex .expects(:new) .with({source: { client: client }}) .returns(stub perform: {}) client.reindex end context "when performing the operation" do setup do d = { '_id' => 'foo', '_type' => 'type', '_source' => { 'foo' => 'bar' } } @default_response = { 'hits' => { 'hits' => [d] } } @empty_response = { 'hits' => { 'hits' => [] } } @bulk_request = [{ index: { '_index' => 'bar', '_type' => d['_type'], '_id' => d['_id'], 'data' => d['_source'] } }] @bulk_response = {'errors'=>false, 'items' => [{'index' => {}}, {'index' => {}}]} @bulk_response_error = {'errors'=>true, 'items' => [{'index' => {}}, {'index' => {'error' => 'FOOBAR'}}]} end should "scroll through the index and save batches in bulk" do client = mock() subject = Elasticsearch::Extensions::Reindex.new source: { index: 'foo', client: client }, target: { index: 'bar' } client.expects(:search) .returns({ '_scroll_id' => 'scroll_id_1' }.merge(Marshal.load(Marshal.dump(@default_response)))) client.expects(:scroll) .returns(Marshal.load(Marshal.dump(@default_response))) .then .returns(@empty_response).times(2) client.expects(:bulk) .with(body: @bulk_request) .returns(@bulk_response).times(2) result = subject.perform assert_equal 0, result[:errors] end should "return the number of errors" do client = mock() subject = Elasticsearch::Extensions::Reindex.new source: { index: 'foo', client: client }, target: { index: 'bar' } client.expects(:search).returns({ '_scroll_id' => 'scroll_id_1' }.merge(@default_response)) client.expects(:scroll).returns(@empty_response) client.expects(:bulk).with(body: @bulk_request).returns(@bulk_response_error) result = subject.perform assert_equal 1, result[:errors] end should "transform the documents with a lambda" do client = mock() subject = Elasticsearch::Extensions::Reindex.new \ source: { index: 'foo', client: client }, target: { index: 'bar' }, transform: lambda { |d| d['_source']['foo'].upcase!; d } client.expects(:search).returns({ '_scroll_id' => 'scroll_id_1' }.merge(@default_response)) client.expects(:scroll).returns(@empty_response) client.expects(:bulk).with do |arguments| assert_equal 'BAR', arguments[:body][0][:index]['data']['foo'] true end .returns(@bulk_response) result = subject.perform assert_equal 0, result[:errors] end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test/000077500000000000000000000000001361161326000242635ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test/cluster/000077500000000000000000000000001361161326000257445ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test/cluster/integration/000077500000000000000000000000001361161326000302675ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test/cluster/integration/cluster_test.rb000066400000000000000000000032621361161326000333370ustar00rootroot00000000000000require 'test_helper' require 'pathname' require 'elasticsearch/extensions/test/cluster' class Elasticsearch::Extensions::TestClusterIntegrationTest < Elasticsearch::Test::IntegrationTestCase context "The Test::Cluster" do PATH_TO_BUILDS = if ENV['PATH_TO_BUILDS'] Pathname(ENV['PATH_TO_BUILDS']) else Pathname(File.expand_path('../../../../../../tmp/builds', __FILE__)) end unless PATH_TO_BUILDS.exist? puts "Path to builds doesn't exist, skipping TestClusterIntegrationTest" exit(0) end @builds = begin PATH_TO_BUILDS.entries.reject { |f| f.to_s =~ /^\./ }.sort rescue Errno::ENOENT [] end STDOUT.puts %Q|Builds: \n#{@builds.map { |b| " * #{b}"}.join("\n")}| unless ENV['QUIET'] @builds.each do |build| should "start and stop #{build.to_s}" do puts ("----- #{build.to_s} " + "-"*(80-7-build.to_s.size)).to_s.ansi(:bold) begin Elasticsearch::Extensions::Test::Cluster.start \ command: PATH_TO_BUILDS.join(build.join('bin/elasticsearch')).to_s, port: 9260, cluster_name: 'elasticsearch-ext-integration-test', path_data: '/tmp/elasticsearch-ext-integration-test' # Index some data to create the data directory client = Elasticsearch::Client.new host: "localhost:9260" client.index index: 'test1', type: 'd', id: 1, body: { title: 'TEST' } ensure Elasticsearch::Extensions::Test::Cluster.stop \ command: PATH_TO_BUILDS.join(build.join('bin/elasticsearch')).to_s, port: 9260, cluster_name: 'elasticsearch-ext-integration-test' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test/cluster/unit/000077500000000000000000000000001361161326000267235ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test/cluster/unit/cluster_test.rb000066400000000000000000000265221361161326000317770ustar00rootroot00000000000000require 'test_helper' require 'elasticsearch/extensions/test/cluster' class Elasticsearch::Extensions::TestClusterTest < Elasticsearch::Test::UnitTestCase include Elasticsearch::Extensions::Test context "The Test::Cluster" do context "module" do should "delegate the methods to the class" do Cluster::Cluster .expects(:new) .with({foo: 'bar'}) .returns(mock start: true, stop: true, running?: true, wait_for_green: true) .times(4) Elasticsearch::Extensions::Test::Cluster.start foo: 'bar' Elasticsearch::Extensions::Test::Cluster.stop foo: 'bar' Elasticsearch::Extensions::Test::Cluster.running? foo: 'bar' Elasticsearch::Extensions::Test::Cluster.wait_for_green foo: 'bar' end end context "class" do setup do Elasticsearch::Extensions::Test::Cluster::Cluster.any_instance.stubs(:__default_network_host).returns('_local_') @subject = Elasticsearch::Extensions::Test::Cluster::Cluster.new(number_of_nodes: 1) @subject.stubs(:__remove_cluster_data).returns(true) end teardown do ENV.delete('TEST_CLUSTER_PORT') end should "be initialized with parameters" do c = Cluster::Cluster.new port: 9400 assert_equal 9400, c.arguments[:port] end should "not modify the arguments" do args = { port: 9400 }.freeze assert_nothing_raised { Cluster::Cluster.new args } assert_nil args[:command] end should "take parameters from environment variables" do ENV['TEST_CLUSTER_PORT'] = '9400' c = Cluster::Cluster.new assert_equal 9400, c.arguments[:port] end should "raise exception for dangerous cluster name" do assert_raise(ArgumentError) { Cluster::Cluster.new cluster_name: '' } assert_raise(ArgumentError) { Cluster::Cluster.new cluster_name: '/' } end should "have a version" do @subject.unstub(:version) @subject.expects(:__determine_version).returns('2.0') assert_equal '2.0', @subject.version end should "have a default network host" do Cluster::Cluster.any_instance.unstub(:__default_network_host) Cluster::Cluster.any_instance.stubs(:version).returns('5.0') assert_equal '_local_', Cluster::Cluster.new.__default_network_host end should "have a default cluster name" do Socket.stubs(:gethostname).returns('FOOBAR') assert_equal 'elasticsearch-test-foobar', Cluster::Cluster.new.__default_cluster_name end should "have a cluster URL for new versions" do assert_equal 'http://localhost:9250', Cluster::Cluster.new(network_host: '_local_').__cluster_url end should "have a cluster URL for old versions" do assert_equal 'http://192.168.1.1:9250', Cluster::Cluster.new(network_host: '192.168.1.1').__cluster_url end should "return corresponding command to a version" do assert_match /\-D es\.foreground=yes/, @subject.__command('2.0', @subject.arguments, 1) end should "raise an error when a corresponding command cannot be found" do assert_raise ArgumentError do @subject.__command('FOOBAR', @subject.arguments, 1) end end should "remove cluster data" do @subject.unstub(:__remove_cluster_data) FileUtils.expects(:rm_rf).with("/tmp/elasticsearch_test") @subject.__remove_cluster_data end should "not log when :quiet" do c = Cluster::Cluster.new quiet: true STDERR.expects(:puts).never c.__log 'QUIET' end context "when starting a cluster, " do should "return false when it's already running" do Process.expects(:spawn).never c = Cluster::Cluster.new c.expects(:running?).returns(true) assert_equal false, c.start end should "start the specified number of nodes" do Process.expects(:spawn).times(3) Process.expects(:detach).times(3) c = Cluster::Cluster.new number_of_nodes: 3 c.expects(:running?).returns(false) c.unstub(:__remove_cluster_data) c.expects(:__remove_cluster_data).returns(true) c.expects(:wait_for_green).returns(true) c.expects(:__check_for_running_processes).returns(true) c.expects(:__determine_version).returns('5.0') c.expects(:__cluster_info).returns('CLUSTER INFO') assert_equal true, c.start end end context "when stopping a cluster" do setup do @subject = Elasticsearch::Extensions::Test::Cluster::Cluster.new end should "print information about an exception" do @subject.expects(:__get_nodes).raises(Errno::ECONNREFUSED) assert_nothing_raised do assert_equal false, @subject.stop end end should "return false when the nodes are empty" do @subject.expects(:__get_nodes).returns({}) assert_equal false, @subject.stop end should "kill each node" do @subject.expects(:__get_nodes).returns({'nodes' => { 'n1' => { 'process' => { 'id' => 1 }}, 'n2' => { 'process' => { 'id' => 2 }} }}) Kernel.stubs(:sleep) Process.expects(:kill).with('INT', 1) Process.expects(:kill).with('INT', 2) Process.expects(:getpgid).with(1).raises(Errno::ESRCH) Process.expects(:getpgid).with(2).raises(Errno::ESRCH) assert_equal [1, 2], @subject.stop end end context "when checking if the cluster is running" do setup do @subject = Elasticsearch::Extensions::Test::Cluster::Cluster.new \ cluster_name: 'test', number_of_nodes: 2 end should "return true" do @subject.expects(:__get_cluster_health).returns({'cluster_name' => 'test', 'number_of_nodes' => 2}) assert_equal true, @subject.running? end should "return false" do @subject.expects(:__get_cluster_health).returns({'cluster_name' => 'test', 'number_of_nodes' => 1}) assert_equal false, @subject.running? end end context "when waiting for the green state" do should "return true" do @subject.expects(:__wait_for_status).returns(true) assert_equal true, @subject.wait_for_green end end context "when waiting for cluster state" do setup do @subject = Elasticsearch::Extensions::Test::Cluster::Cluster.new \ cluster_name: 'test', number_of_nodes: 1 end should "return true" do @subject .expects(:__get_cluster_health) .with('yellow') .returns({'status' => 'yellow', 'cluster_name' => 'test', 'number_of_nodes' => 1}) @subject.__wait_for_status('yellow') end end context "when getting the cluster health" do should "return the response" do Net::HTTP .expects(:get) .with(URI('http://localhost:9250/_cluster/health')) .returns(JSON.dump({'status' => 'yellow', 'cluster_name' => 'test', 'number_of_nodes' => 1})) @subject.__get_cluster_health end should "wait for status" do Net::HTTP .expects(:get) .with(URI('http://localhost:9250/_cluster/health?wait_for_status=green')) .returns(JSON.dump({'status' => 'yellow', 'cluster_name' => 'test', 'number_of_nodes' => 1})) @subject.__get_cluster_health('green') end end context "when getting the list of nodes" do should "return the response" do Net::HTTP .expects(:get) .with(URI('http://localhost:9250/_nodes/process')) .returns(JSON.dump({'nodes' => { 'n1' => {}, 'n2' => {} } })) assert_equal 'n1', @subject.__get_nodes['nodes'].keys.first end end context "when determining a version" do setup do @subject = Elasticsearch::Extensions::Test::Cluster::Cluster.new command: '/foo/bar/bin/elasticsearch' end should "return version from lib/elasticsearch.X.Y.Z.jar" do File.expects(:exist?).with('/foo/bar/bin/../lib/').returns(true) Dir.expects(:entries).with('/foo/bar/bin/../lib/').returns(['foo.jar', 'elasticsearch-foo-1.0.0.jar', 'elasticsearch-2.3.0.jar', 'elasticsearch-bar-9.9.9.jar']) assert_equal '2.0', @subject.__determine_version end should "return version from `elasticsearch --version`" do File.expects(:exist?).with('/foo/bar/bin/../lib/').returns(false) File.expects(:exist?).with('/foo/bar/bin/elasticsearch').returns(true) io = mock('IO') io.expects(:pid).returns(123) io.expects(:read).returns('Version: 2.3.0-SNAPSHOT, Build: d1c86b0/2016-03-30T10:43:20Z, JVM: 1.8.0_60') io.expects(:closed?).returns(false) io.expects(:close) IO.expects(:popen).returns(io) Process.stubs(:wait) Process.expects(:kill).with('INT', 123) assert_equal '2.0', @subject.__determine_version end should "return version from arguments" do cluster = Elasticsearch::Extensions::Test::Cluster::Cluster.new command: '/foo/bar/bin/elasticsearch', version: '5.2' assert_equal '5.0', cluster.__determine_version end should "raise an exception when the version cannot be parsed from .jar" do # Incorrect jar version (no dots) File.expects(:exist?).with('/foo/bar/bin/../lib/').returns(true) Dir.expects(:entries).with('/foo/bar/bin/../lib/').returns(['elasticsearch-100.jar']) assert_raise(RuntimeError) { @subject.__determine_version } end should "raise an exception when the version cannot be parsed from command output" do File.expects(:exist?).with('/foo/bar/bin/../lib/').returns(false) File.expects(:exist?).with('/foo/bar/bin/elasticsearch').returns(true) io = mock('IO') io.expects(:pid).returns(123) io.expects(:read).returns('Version: FOOBAR') io.expects(:closed?).returns(false) io.expects(:close) IO.expects(:popen).returns(io) Process.stubs(:wait) Process.expects(:kill).with('INT', 123) assert_raise(RuntimeError) { @subject.__determine_version } end should "raise an exception when the version cannot be converted to short version" do # There's no Elasticsearch version 3... File.expects(:exist?).with('/foo/bar/bin/../lib/').returns(true) Dir.expects(:entries).with('/foo/bar/bin/../lib/').returns(['elasticsearch-3.2.1.jar']) assert_raise(RuntimeError) { @subject.__determine_version } end should "raise an exception when the command cannot be found" do @subject = Elasticsearch::Extensions::Test::Cluster::Cluster.new File.expects(:exist?).with('./../lib/').returns(false) File.expects(:exist?).with('elasticsearch').returns(false) @subject.expects(:`).returns('') assert_raise(Errno::ENOENT) { @subject.__determine_version } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-extensions/test/test_helper.rb000066400000000000000000000034241361161326000261520ustar00rootroot00000000000000JRUBY = defined?(JRUBY_VERSION) ELASTICSEARCH_HOSTS = if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end end.freeze TEST_HOST, TEST_PORT = ELASTICSEARCH_HOSTS.first.split(':') if ELASTICSEARCH_HOSTS if ENV['COVERAGE'] && ENV['CI'].nil? && !RUBY_1_8 require 'simplecov' SimpleCov.start { add_filter "/test|test_" } end require 'minitest/autorun' require 'shoulda-context' require 'mocha/setup' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require 'ansi/code' require 'logger' require 'elasticsearch/extensions' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/extensions/test/cluster' module Elasticsearch module Test module Assertions def assert_nothing_raised(*) yield end end class UnitTestCase < ::Minitest::Test include Assertions alias_method :assert_not_nil, :refute_nil alias_method :assert_raise, :assert_raises end class IntegrationTestCase < ::Minitest::Test include Assertions alias_method :assert_not_nil, :refute_nil alias_method :assert_raise, :assert_raises include Elasticsearch::Extensions::Test extend StartupShutdown startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 2) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 2) end shutdown do Elasticsearch::Extensions::Test::Cluster.stop(number_of_nodes: 2) if ENV['SERVER'] and Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 2) end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/000077500000000000000000000000001361161326000221625ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/.gitignore000066400000000000000000000002321361161326000241470ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp elasticsearch-ruby-6.8.1/elasticsearch-transport/Gemfile000066400000000000000000000014441361161326000234600ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-transport.gemspec gemspec if File.exist? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-extensions/elasticsearch-extensions.gemspec", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch", __FILE__), :require => false end group :development do gem 'rspec' gem 'pry-nav' end elasticsearch-ruby-6.8.1/elasticsearch-transport/LICENSE.txt000066400000000000000000000010561361161326000240070ustar00rootroot00000000000000Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-transport/README.md000066400000000000000000000443061361161326000234500ustar00rootroot00000000000000# Elasticsearch::Transport **This library is part of the [`elasticsearch-ruby`](https://github.com/elasticsearch/elasticsearch-ruby/) package; please refer to it, unless you want to use this library standalone.** ---- The `elasticsearch-transport` library provides a low-level Ruby client for connecting to an [Elasticsearch](http://elasticsearch.org) cluster. It handles connecting to multiple nodes in the cluster, rotating across connections, logging and tracing requests and responses, maintaining failed connections, discovering nodes in the cluster, and provides an abstraction for data serialization and transport. It does not handle calling the Elasticsearch API; see the [`elasticsearch-api`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-api) library. The library is compatible with Ruby 1.9 or higher and with all versions of Elasticsearch since 0.90. Features overview: * Pluggable logging and tracing * Pluggable connection selection strategies (round-robin, random, custom) * Pluggable transport implementation, customizable and extendable * Pluggable serializer implementation * Request retries and dead connections handling * Node reloading (based on cluster state) on errors or on demand For optimal performance, use a HTTP library which supports persistent ("keep-alive") connections, such as [Typhoeus](https://github.com/typhoeus/typhoeus). Just require the library (`require 'typhoeus'; require 'typhoeus/adapters/faraday'`) in your code, and it will be automatically used; currently these libraries will be automatically detected and used: [Patron](https://github.com/toland/patron), [HTTPClient](https://rubygems.org/gems/httpclient) and [Net::HTTP::Persistent](https://rubygems.org/gems/net-http-persistent). For detailed information, see example configurations [below](#transport-implementations). ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch-transport To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch-transport', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git' or install it from a source code checkout: git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch-transport bundle install rake install ## Example Usage In the simplest form, connect to Elasticsearch running on without any configuration: require 'elasticsearch/transport' client = Elasticsearch::Client.new response = client.perform_request 'GET', '_cluster/health' # => # Full documentation is available at . ## Configuration The client supports many configurations options for setting up and managing connections, configuring logging, customizing the transport library, etc. ### Setting Hosts To connect to a specific Elasticsearch host: Elasticsearch::Client.new host: 'search.myserver.com' To connect to a host with specific port: Elasticsearch::Client.new host: 'myhost:8080' To connect to multiple hosts: Elasticsearch::Client.new hosts: ['myhost1', 'myhost2'] Instead of Strings, you can pass host information as an array of Hashes: Elasticsearch::Client.new hosts: [ { host: 'myhost1', port: 8080 }, { host: 'myhost2', port: 8080 } ] **NOTE:** When specifying multiple hosts, you probably want to enable the `retry_on_failure` option to perform a failed request on another node (see the _Retrying on Failures_ chapter). Common URL parts -- scheme, HTTP authentication credentials, URL prefixes, etc -- are handled automatically: Elasticsearch::Client.new url: 'https://username:password@api.server.org:4430/search' You can pass multiple URLs separated by a comma: Elasticsearch::Client.new urls: 'http://localhost:9200,http://localhost:9201' Another way to configure the URL(s) is to export the `ELASTICSEARCH_URL` variable. The client will automatically round-robin across the hosts (unless you select or implement a different [connection selector](#connection-selector)). ### Authentication You can pass the authentication credentials, scheme and port in the host configuration hash: Elasticsearch::Client.new hosts: [ { host: 'my-protected-host', port: '443', user: 'USERNAME', password: 'PASSWORD', scheme: 'https' } ] ... or simply use the common URL format: Elasticsearch::Client.new url: 'https://username:password@example.com:9200' To pass a custom certificate for SSL peer verification to Faraday-based clients, use the `transport_options` option: Elasticsearch::Client.new url: 'https://username:password@example.com:9200', transport_options: { ssl: { ca_file: '/path/to/cacert.pem' } } ### Logging To log requests and responses to standard output with the default logger (an instance of Ruby's {::Logger} class), set the `log` argument: Elasticsearch::Client.new log: true To trace requests and responses in the _Curl_ format, set the `trace` argument: Elasticsearch::Client.new trace: true You can customize the default logger or tracer: client.transport.logger.formatter = proc { |s, d, p, m| "#{s}: #{m}\n" } client.transport.logger.level = Logger::INFO Or, you can use a custom {::Logger} instance: Elasticsearch::Client.new logger: Logger.new(STDERR) You can pass the client any conforming logger implementation: require 'logging' # https://github.com/TwP/logging/ log = Logging.logger['elasticsearch'] log.add_appenders Logging.appenders.stdout log.level = :info client = Elasticsearch::Client.new logger: log ### Setting Timeouts For many operations in Elasticsearch, the default timeouts of HTTP libraries are too low. To increase the timeout, you can use the `request_timeout` parameter: Elasticsearch::Client.new request_timeout: 5*60 You can also use the `transport_options` argument documented below. ### Randomizing Hosts If you pass multiple hosts to the client, it rotates across them in a round-robin fashion, by default. When the same client would be running in multiple processes (eg. in a Ruby web server such as Thin), it might keep connecting to the same nodes "at once". To prevent this, you can randomize the hosts collection on initialization and reloading: Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], randomize_hosts: true ### Retrying on Failures When the client is initialized with multiple hosts, it makes sense to retry a failed request on a different host: Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], retry_on_failure: true You can specify how many times should the client retry the request before it raises an exception (the default is 3 times): Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], retry_on_failure: 5 ### Reloading Hosts Elasticsearch by default dynamically discovers new nodes in the cluster. You can leverage this in the client, and periodically check for new nodes to spread the load. To retrieve and use the information from the [_Nodes Info API_](http://www.elasticsearch.org/guide/reference/api/admin-cluster-nodes-info/) on every 10,000th request: Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], reload_connections: true You can pass a specific number of requests after which the reloading should be performed: Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], reload_connections: 1_000 To reload connections on failures, use: Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], reload_on_failure: true The reloading will timeout if not finished under 1 second by default. To change the setting: Elasticsearch::Client.new hosts: ['localhost:9200', 'localhost:9201'], sniffer_timeout: 3 **NOTE:** When using reloading hosts ("sniffing") together with authentication, just pass the scheme, user and password with the host info -- or, for more clarity, in the `http` options: Elasticsearch::Client.new host: 'localhost:9200', http: { scheme: 'https', user: 'U', password: 'P' }, reload_connections: true, reload_on_failure: true ### Connection Selector By default, the client will rotate the connections in a round-robin fashion, using the {Elasticsearch::Transport::Transport::Connections::Selector::RoundRobin} strategy. You can implement your own strategy to customize the behaviour. For example, let's have a "rack aware" strategy, which will prefer the nodes with a specific [attribute](https://github.com/elasticsearch/elasticsearch/blob/1.0/config/elasticsearch.yml#L81-L85). Only when these would be unavailable, the strategy will use the other nodes: class RackIdSelector include Elasticsearch::Transport::Transport::Connections::Selector::Base def select(options={}) connections.select do |c| # Try selecting the nodes with a `rack_id:x1` attribute first c.host[:attributes] && c.host[:attributes][:rack_id] == 'x1' end.sample || connections.to_a.sample end end Elasticsearch::Client.new hosts: ['x1.search.org', 'x2.search.org'], selector_class: RackIdSelector ### Transport Implementations By default, the client will use the [_Faraday_](https://rubygems.org/gems/faraday) HTTP library as a transport implementation. It will auto-detect and use an _adapter_ for _Faraday_ based on gems loaded in your code, preferring HTTP clients with support for persistent connections. To use the [_Patron_](https://github.com/toland/patron) HTTP, for example, just require it: require 'patron' Then, create a new client, and the _Patron_ gem will be used as the "driver": client = Elasticsearch::Client.new client.transport.connections.first.connection.builder.handlers # => [Faraday::Adapter::Patron] 10.times do client.nodes.stats(metric: 'http')['nodes'].values.each do |n| puts "#{n['name']} : #{n['http']['total_opened']}" end end # => Stiletoo : 24 # => Stiletoo : 24 # => Stiletoo : 24 # => ... To use a specific adapter for _Faraday_, pass it as the `adapter` argument: client = Elasticsearch::Client.new adapter: :net_http_persistent client.transport.connections.first.connection.builder.handlers # => [Faraday::Adapter::NetHttpPersistent] To pass options to the [`Faraday::Connection`](https://github.com/lostisland/faraday/blob/master/lib/faraday/connection.rb) constructor, use the `transport_options` key: client = Elasticsearch::Client.new transport_options: { request: { open_timeout: 1 }, headers: { user_agent: 'MyApp' }, params: { :format => 'yaml' }, ssl: { verify: false } } To configure the _Faraday_ instance directly, use a block: require 'typhoeus' require 'typhoeus/adapters/faraday' client = Elasticsearch::Client.new(host: 'localhost', port: '9200') do |f| f.response :logger f.adapter :typhoeus end You can use any standard Faraday middleware and plugins in the configuration block, for example sign the requests for the [AWS Elasticsearch service](https://aws.amazon.com/elasticsearch-service/): require 'faraday_middleware/aws_signers_v4' client = Elasticsearch::Client.new url: 'https://search-my-cluster-abc123....es.amazonaws.com' do |f| f.request :aws_signers_v4, credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY'], ENV['AWS_SECRET_ACCESS_KEY']), service_name: 'es', region: 'us-east-1' end You can also initialize the transport class yourself, and pass it to the client constructor as the `transport` argument: require 'typhoeus' require 'typhoeus/adapters/faraday' transport_configuration = lambda do |f| f.response :logger f.adapter :typhoeus end transport = Elasticsearch::Transport::Transport::HTTP::Faraday.new \ hosts: [ { host: 'localhost', port: '9200' } ], &transport_configuration # Pass the transport to the client # client = Elasticsearch::Client.new transport: transport Instead of passing the transport to the constructor, you can inject it at run time: # Set up the transport # faraday_configuration = lambda do |f| f.instance_variable_set :@ssl, { verify: false } f.adapter :excon end faraday_client = Elasticsearch::Transport::Transport::HTTP::Faraday.new \ hosts: [ { host: 'my-protected-host', port: '443', user: 'USERNAME', password: 'PASSWORD', scheme: 'https' }], &faraday_configuration # Create a default client # client = Elasticsearch::Client.new # Inject the transport to the client # client.transport = faraday_client You can also use a bundled [_Curb_](https://rubygems.org/gems/curb) based transport implementation: require 'curb' require 'elasticsearch/transport/transport/http/curb' client = Elasticsearch::Client.new transport_class: Elasticsearch::Transport::Transport::HTTP::Curb client.transport.connections.first.connection # => # It's possible to customize the _Curb_ instance by passing a block to the constructor as well (in this case, as an inline block): transport = Elasticsearch::Transport::Transport::HTTP::Curb.new \ hosts: [ { host: 'localhost', port: '9200' } ], & lambda { |c| c.verbose = true } client = Elasticsearch::Client.new transport: transport You can write your own transport implementation easily, by including the {Elasticsearch::Transport::Transport::Base} module, implementing the required contract, and passing it to the client as the `transport_class` parameter -- or injecting it directly. ### Serializer Implementations By default, the [MultiJSON](http://rubygems.org/gems/multi_json) library is used as the serializer implementation, and it will pick up the "right" adapter based on gems available. The serialization component is pluggable, though, so you can write your own by including the {Elasticsearch::Transport::Transport::Serializer::Base} module, implementing the required contract, and passing it to the client as the `serializer_class` or `serializer` parameter. ### Exception Handling The library defines a [number of exception classes](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/lib/elasticsearch/transport/transport/errors.rb) for various client and server errors, as well as unsuccessful HTTP responses, making it possible to `rescue` specific exceptions with desired granularity. The highest-level exception is {Elasticsearch::Transport::Transport::Error} and will be raised for any generic client *or* server errors. {Elasticsearch::Transport::Transport::ServerError} will be raised for server errors only. As an example for response-specific errors, a `404` response status will raise an {Elasticsearch::Transport::Transport::Errors::NotFound} exception. Finally, {Elasticsearch::Transport::Transport::SnifferTimeoutError} will be raised when connection reloading ("sniffing") times out. ## Development and Community For local development, clone the repository and run `bundle install`. See `rake -T` for a list of available Rake tasks for running tests, generating documentation, starting a testing cluster, etc. Bug fixes and features must be covered by unit tests. Integration tests are written in Ruby 1.9 syntax. Github's pull requests and issues are used to communicate, send bug reports and code contributions. ## The Architecture * {Elasticsearch::Transport::Client} is composed of {Elasticsearch::Transport::Transport} * {Elasticsearch::Transport::Transport} is composed of {Elasticsearch::Transport::Transport::Connections}, and an instance of logger, tracer, serializer and sniffer. * Logger and tracer can be any object conforming to Ruby logging interface, ie. an instance of [`Logger`](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html), [_log4r_](https://rubygems.org/gems/log4r), [_logging_](https://github.com/TwP/logging/), etc. * The {Elasticsearch::Transport::Transport::Serializer::Base} implementations handle converting data for Elasticsearch (eg. to JSON). You can implement your own serializer. * {Elasticsearch::Transport::Transport::Sniffer} allows to discover nodes in the cluster and use them as connections. * {Elasticsearch::Transport::Transport::Connections::Collection} is composed of {Elasticsearch::Transport::Transport::Connections::Connection} instances and a selector instance. * {Elasticsearch::Transport::Transport::Connections::Connection} contains the connection attributes such as hostname and port, as well as the concrete persistent "session" connected to a specific node. * The {Elasticsearch::Transport::Transport::Connections::Selector::Base} implementations allow to choose connections from the pool, eg. in a round-robin or random fashion. You can implement your own selector strategy. ## Development To work on the code, clone and bootstrap the main repository first -- please see instructions in the main [README](../README.md#development). To run tests, launch a testing cluster -- again, see instructions in the main [README](../README.md#development) -- and use the Rake tasks: ``` time rake test:unit time rake test:integration ``` Unit tests have to use Ruby 1.8 compatible syntax, integration tests can use Ruby 2.x syntax and features. ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-transport/Rakefile000066400000000000000000000041101361161326000236230ustar00rootroot00000000000000require "bundler/gem_tasks" desc "Run unit tests" task :default => 'test:unit' task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' require 'rspec/core/rake_task' namespace :test do RSpec::Core::RakeTask.new(:spec) desc "Wait for Elasticsearch to be in a green state" task :wait_for_green do sh '../scripts/wait-cluster.sh' end Rake::TestTask.new(:unit) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] test.verbose = false test.warning = false end Rake::TestTask.new(:integration) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/**/*_test.rb"] test.deps = [ :wait_for_green, :spec ] test.verbose = false test.warning = false end Rake::TestTask.new(:all) do |test| test.deps = [ :unit, :integration ] end Rake::TestTask.new(:profile) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/profile/**/*_test.rb"] end namespace :cluster do desc "Start Elasticsearch nodes for tests" task :start do $LOAD_PATH << File.expand_path('../lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start end desc "Stop Elasticsearch nodes for tests" task :stop do $LOAD_PATH << File.expand_path('../lib', __FILE__) << File.expand_path('../test', __FILE__) require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.stop end end end # ----- Documentation tasks --------------------------------------------------- require 'yard' YARD::Rake::YardocTask.new(:doc) do |t| t.options = %w| --embed-mixins --markup=markdown | end # ----- Code analysis tasks --------------------------------------------------- if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'cane/rake_task' Cane::RakeTask.new(:quality) do |cane| cane.abc_max = 15 cane.no_style = true end end elasticsearch-ruby-6.8.1/elasticsearch-transport/elasticsearch-transport.gemspec000066400000000000000000000056361361161326000304050ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/transport/version' Gem::Specification.new do |s| s.name = "elasticsearch-transport" s.version = Elasticsearch::Transport::VERSION s.authors = ["Karel Minarik"] s.email = ["karel.minarik@elasticsearch.org"] s.summary = "Ruby client for Elasticsearch." s.homepage = "https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-transport" s.license = "Apache-2.0" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] s.extra_rdoc_files = [ "README.md", "LICENSE.txt" ] s.rdoc_options = [ "--charset=UTF-8" ] s.required_ruby_version = '>= 1.9' s.add_dependency "multi_json" s.add_dependency "faraday", '>= 0.14', "< 1" if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_dependency "system_timer" end s.add_development_dependency "bundler" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "rake", "~> 11.1" else s.add_development_dependency "rake", "< 11.0" end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "elasticsearch-extensions" end s.add_development_dependency "ansi" s.add_development_dependency "shoulda-context" s.add_development_dependency "mocha" s.add_development_dependency "turn" s.add_development_dependency "yard" s.add_development_dependency "pry" # Gems for testing integrations s.add_development_dependency "curb" unless defined? JRUBY_VERSION s.add_development_dependency "patron" unless defined? JRUBY_VERSION s.add_development_dependency "typhoeus", '~> 0.6' s.add_development_dependency "net-http-persistent" s.add_development_dependency "manticore", '~> 0.5.2' if defined? JRUBY_VERSION s.add_development_dependency "hashie" # Prevent unit test failures on Ruby 1.8 if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_development_dependency "test-unit", '~> 2' s.add_development_dependency "json", '~> 1.8' end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "minitest", "~> 4.0" s.add_development_dependency "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) s.add_development_dependency "require-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) s.add_development_dependency "simplecov" s.add_development_dependency "simplecov-rcov" s.add_development_dependency "cane" end if defined?(RUBY_VERSION) && RUBY_VERSION > '2.2' s.add_development_dependency "test-unit", '~> 2' end s.description = <<-DESC.gsub(/^ /, '') Ruby client for Elasticsearch. See the `elasticsearch` gem for full integration. DESC end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/000077500000000000000000000000001361161326000227305ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch-transport.rb000066400000000000000000000000421361161326000301150ustar00rootroot00000000000000require 'elasticsearch/transport' elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/000077500000000000000000000000001361161326000255425ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport.rb000066400000000000000000000017451361161326000301320ustar00rootroot00000000000000require "uri" require "time" require "timeout" require "multi_json" require "faraday" require "elasticsearch/transport/transport/serializer/multi_json" require "elasticsearch/transport/transport/sniffer" require "elasticsearch/transport/transport/response" require "elasticsearch/transport/transport/errors" require "elasticsearch/transport/transport/base" require "elasticsearch/transport/transport/connections/selector" require "elasticsearch/transport/transport/connections/connection" require "elasticsearch/transport/transport/connections/collection" require "elasticsearch/transport/transport/http/faraday" require "elasticsearch/transport/client" require "elasticsearch/transport/redacted" require "elasticsearch/transport/version" module Elasticsearch module Client # A convenience wrapper for {::Elasticsearch::Transport::Client#initialize}. # def new(arguments={}, &block) Elasticsearch::Transport::Client.new(arguments, &block) end extend self end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/000077500000000000000000000000001361161326000275765ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/client.rb000066400000000000000000000230041361161326000314000ustar00rootroot00000000000000module Elasticsearch module Transport # Handles communication with an Elasticsearch cluster. # # See {file:README.md README} for usage and code examples. # class Client DEFAULT_TRANSPORT_CLASS = Transport::HTTP::Faraday DEFAULT_LOGGER = lambda do require 'logger' logger = Logger.new(STDERR) logger.progname = 'elasticsearch' logger.formatter = proc { |severity, datetime, progname, msg| "#{datetime}: #{msg}\n" } logger end DEFAULT_TRACER = lambda do require 'logger' logger = Logger.new(STDERR) logger.progname = 'elasticsearch.tracer' logger.formatter = proc { |severity, datetime, progname, msg| "#{msg}\n" } logger end # The default host and port to use if not otherwise specified. # # @since 7.0.0 DEFAULT_HOST = 'localhost:9200'.freeze # Returns the transport object. # # @see Elasticsearch::Transport::Transport::Base # @see Elasticsearch::Transport::Transport::HTTP::Faraday # attr_accessor :transport # Create a client connected to an Elasticsearch cluster. # # Specify the URL via arguments or set the `ELASTICSEARCH_URL` environment variable. # # @option arguments [String,Array] :hosts Single host passed as a String or Hash, or multiple hosts # passed as an Array; `host` or `url` keys are also valid # # @option arguments [Boolean] :log Use the default logger (disabled by default) # # @option arguments [Boolean] :trace Use the default tracer (disabled by default) # # @option arguments [Object] :logger An instance of a Logger-compatible object # # @option arguments [Object] :tracer An instance of a Logger-compatible object # # @option arguments [Number] :resurrect_after After how many seconds a dead connection should be tried again # # @option arguments [Boolean,Number] :reload_connections Reload connections after X requests (false by default) # # @option arguments [Boolean] :randomize_hosts Shuffle connections on initialization and reload (false by default) # # @option arguments [Integer] :sniffer_timeout Timeout for reloading connections in seconds (1 by default) # # @option arguments [Boolean,Number] :retry_on_failure Retry X times when request fails before raising and # exception (false by default) # @option arguments Array :retry_on_status Retry when specific status codes are returned # # @option arguments [Boolean] :reload_on_failure Reload connections after failure (false by default) # # @option arguments [Integer] :request_timeout The request timeout to be passed to transport in options # # @option arguments [Symbol] :adapter A specific adapter for Faraday (e.g. `:patron`) # # @option arguments [Hash] :transport_options Options to be passed to the `Faraday::Connection` constructor # # @option arguments [Constant] :transport_class A specific transport class to use, will be initialized by # the client and passed hosts and all arguments # # @option arguments [Object] :transport A specific transport instance # # @option arguments [Constant] :serializer_class A specific serializer class to use, will be initialized by # the transport and passed the transport instance # # @option arguments [Constant] :selector An instance of selector strategy implemented with # {Elasticsearch::Transport::Transport::Connections::Selector::Base}. # # @option arguments [String] :send_get_body_as Specify the HTTP method to use for GET requests with a body. # (Default: GET) # # @yield [faraday] Access and configure the `Faraday::Connection` instance directly with a block # def initialize(arguments={}, &block) @options = arguments @arguments = arguments @arguments[:logger] ||= @arguments[:log] ? DEFAULT_LOGGER.call() : nil @arguments[:tracer] ||= @arguments[:trace] ? DEFAULT_TRACER.call() : nil @arguments[:reload_connections] ||= false @arguments[:retry_on_failure] ||= false @arguments[:reload_on_failure] ||= false @arguments[:randomize_hosts] ||= false @arguments[:transport_options] ||= {} @arguments[:http] ||= {} @options[:http] ||= {} @seeds = __extract_hosts(@arguments[:hosts] || @arguments[:host] || @arguments[:url] || @arguments[:urls] || ENV['ELASTICSEARCH_URL'] || DEFAULT_HOST) @send_get_body_as = @arguments[:send_get_body_as] || 'GET' if @arguments[:request_timeout] @arguments[:transport_options][:request] = { :timeout => @arguments[:request_timeout] } end @arguments[:transport_options][:headers] ||= {} unless @arguments[:transport_options][:headers].keys.any? {|k| k.to_s.downcase =~ /content\-?\_?type/} @arguments[:transport_options][:headers]['Content-Type'] = 'application/json' end if @arguments[:transport] @transport = @arguments[:transport] else transport_class = @arguments[:transport_class] || DEFAULT_TRANSPORT_CLASS if transport_class == Transport::HTTP::Faraday @transport = transport_class.new(:hosts => @seeds, :options => @arguments) do |faraday| block.call faraday if block unless (h = faraday.builder.handlers.last) && h.name.start_with?("Faraday::Adapter") faraday.adapter(@arguments[:adapter] || __auto_detect_adapter) end end else @transport = transport_class.new(:hosts => @seeds, :options => @arguments) end end end # Performs a request through delegation to {#transport}. # def perform_request(method, path, params={}, body=nil, headers=nil) method = @send_get_body_as if 'GET' == method && body transport.perform_request(method, path, params, body, headers) end private # Normalizes and returns hosts configuration. # # Arrayifies the `hosts_config` argument and extracts `host` and `port` info from strings. # Performs shuffling when the `randomize_hosts` option is set. # # TODO: Refactor, so it's available in Elasticsearch::Transport::Base as well # # @return [Array] # @raise [ArgumentError] # # @api private # def __extract_hosts(hosts_config) hosts = case hosts_config when String hosts_config.split(',').map { |h| h.strip! || h } when Array hosts_config when Hash, URI [ hosts_config ] else Array(hosts_config) end host_list = hosts.map { |host| __parse_host(host) } @options[:randomize_hosts] ? host_list.shuffle! : host_list end def __parse_host(host) host_parts = case host when String if host =~ /^[a-z]+\:\/\// uri = URI.parse(host) { :scheme => uri.scheme, :user => uri.user, :password => uri.password, :host => uri.host, :path => uri.path, :port => uri.port } else host, port = host.split(':') { :host => host, :port => port } end when URI { :scheme => host.scheme, :user => host.user, :password => host.password, :host => host.host, :path => host.path, :port => host.port } when Hash host else raise ArgumentError, "Please pass host as a String, URI or Hash -- #{host.class} given." end @options[:http][:user] ||= host_parts[:user] @options[:http][:password] ||= host_parts[:password] host_parts[:port] = host_parts[:port].to_i if host_parts[:port] host_parts[:path].chomp!('/') if host_parts[:path] host_parts end # Auto-detect the best adapter (HTTP "driver") available, based on libraries # loaded by the user, preferring those with persistent connections # ("keep-alive") by default # # @return [Symbol] # # @api private # def __auto_detect_adapter case when defined?(::Patron) :patron when defined?(::Typhoeus) :typhoeus when defined?(::HTTPClient) :httpclient when defined?(::Net::HTTP::Persistent) :net_http_persistent else ::Faraday.default_adapter end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/redacted.rb000066400000000000000000000042351361161326000317020ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. module Elasticsearch module Transport # Class for wrapping a hash that could have sensitive data. # When printed, the sensitive values will be redacted. # # @since 6.2.0 class Redacted < ::Hash def initialize(elements = nil) super() (elements || {}).each_pair{ |key, value| self[key] = value } end # The keys whose values will be redacted. # # @since 6.2.0 SENSITIVE_KEYS = [ :password, :pwd ].freeze # The replacement string used in place of the value for sensitive keys. # # @since 6.2.0 STRING_REPLACEMENT = ''.freeze # Get a string representation of the hash. # # @return [ String ] The string representation of the hash. # # @since 6.2.0 def inspect redacted_string(:inspect) end # Get a string representation of the hash. # # @return [ String ] The string representation of the hash. # # @since 6.2.0 def to_s redacted_string(:to_s) end private def redacted_string(method) '{' + reduce([]) do |list, (k, v)| list << "#{k.send(method)}=>#{redact(k, v, method)}" end.join(', ') + '}' end def redact(k, v, method) return STRING_REPLACEMENT if SENSITIVE_KEYS.include?(k.to_sym) v.send(method) end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/000077500000000000000000000000001361161326000316325ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/base.rb000066400000000000000000000346071361161326000331030ustar00rootroot00000000000000module Elasticsearch module Transport module Transport # @abstract Module with common functionality for transport implementations. # module Base DEFAULT_PORT = 9200 DEFAULT_PROTOCOL = 'http' DEFAULT_RELOAD_AFTER = 10_000 # Requests DEFAULT_RESURRECT_AFTER = 60 # Seconds DEFAULT_MAX_RETRIES = 3 # Requests DEFAULT_SERIALIZER_CLASS = Serializer::MultiJson SANITIZED_PASSWORD = '*' * (rand(14)+1) attr_reader :hosts, :options, :connections, :counter, :last_request_at, :protocol attr_accessor :serializer, :sniffer, :logger, :tracer, :reload_connections, :reload_after, :resurrect_after, :max_retries # Creates a new transport object # # @param arguments [Hash] Settings and options for the transport # @param block [Proc] Lambda or Proc which can be evaluated in the context of the "session" object # # @option arguments [Array] :hosts An Array of normalized hosts information # @option arguments [Array] :options A Hash with options (usually passed by {Client}) # # @see Client#initialize # def initialize(arguments={}, &block) @state_mutex = Mutex.new @hosts = arguments[:hosts] || [] @options = arguments[:options] ? arguments[:options].dup : {} @options[:http] ||= {} @options[:retry_on_status] ||= [] @block = block @connections = __build_connections @serializer = options[:serializer] || ( options[:serializer_class] ? options[:serializer_class].new(self) : DEFAULT_SERIALIZER_CLASS.new(self) ) @protocol = options[:protocol] || DEFAULT_PROTOCOL @logger = options[:logger] @tracer = options[:tracer] @sniffer = options[:sniffer_class] ? options[:sniffer_class].new(self) : Sniffer.new(self) @counter = 0 @counter_mtx = Mutex.new @last_request_at = Time.now @reload_connections = options[:reload_connections] @reload_after = options[:reload_connections].is_a?(Integer) ? options[:reload_connections] : DEFAULT_RELOAD_AFTER @resurrect_after = options[:resurrect_after] || DEFAULT_RESURRECT_AFTER @max_retries = options[:retry_on_failure].is_a?(Integer) ? options[:retry_on_failure] : DEFAULT_MAX_RETRIES @retry_on_status = Array(options[:retry_on_status]).map { |d| d.to_i } end # Returns a connection from the connection pool by delegating to {Connections::Collection#get_connection}. # # Resurrects dead connection if the `resurrect_after` timeout has passed. # Increments the counter and performs connection reloading if the `reload_connections` option is set. # # @return [Connections::Connection] # @see Connections::Collection#get_connection # def get_connection(options={}) resurrect_dead_connections! if Time.now > @last_request_at + @resurrect_after @counter_mtx.synchronize { @counter += 1 } reload_connections! if reload_connections && counter % reload_after == 0 connections.get_connection(options) end # Reloads and replaces the connection collection based on cluster information # # @see Sniffer#hosts # def reload_connections! hosts = sniffer.hosts __rebuild_connections :hosts => hosts, :options => options self rescue SnifferTimeoutError logger.error "[SnifferTimeoutError] Timeout when reloading connections." if logger self end # Tries to "resurrect" all eligible dead connections # # @see Connections::Connection#resurrect! # def resurrect_dead_connections! connections.dead.each { |c| c.resurrect! } end # Rebuilds the connections collection in the transport. # # The methods *adds* new connections from the passed hosts to the collection, # and *removes* all connections not contained in the passed hosts. # # @return [Connections::Collection] # @api private # def __rebuild_connections(arguments={}) @state_mutex.synchronize do @hosts = arguments[:hosts] || [] @options = arguments[:options] || {} __close_connections new_connections = __build_connections stale_connections = @connections.all.select { |c| ! new_connections.include?(c) } new_connections = new_connections.reject { |c| @connections.all.include?(c) } @connections.remove(stale_connections) @connections.add(new_connections) @connections end end # Builds and returns a collection of connections # # The adapters have to implement the {Base#__build_connection} method. # # @return [Connections::Collection] # @api private # def __build_connections Connections::Collection.new \ :connections => hosts.map { |host| host[:protocol] = host[:scheme] || options[:scheme] || options[:http][:scheme] || DEFAULT_PROTOCOL host[:port] ||= options[:port] || options[:http][:port] || DEFAULT_PORT if (options[:user] || options[:http][:user]) && !host[:user] host[:user] ||= options[:user] || options[:http][:user] host[:password] ||= options[:password] || options[:http][:password] end __build_connection(host, (options[:transport_options] || {}), @block) }, :selector_class => options[:selector_class], :selector => options[:selector] end # @abstract Build and return a connection. # A transport implementation *must* implement this method. # See {HTTP::Faraday#__build_connection} for an example. # # @return [Connections::Connection] # @api private # def __build_connection(host, options={}, block=nil) raise NoMethodError, "Implement this method in your class" end # Closes the connections collection # # @api private # def __close_connections # A hook point for specific adapters when they need to close connections end # Log request and response information # # @api private # def __log(method, path, params, body, url, response, json, took, duration) sanitized_url = url.to_s.gsub(/\/\/(.+):(.+)@/, '//' + '\1:' + SANITIZED_PASSWORD + '@') logger.info "#{method.to_s.upcase} #{sanitized_url} " + "[status:#{response.status}, request:#{sprintf('%.3fs', duration)}, query:#{took}]" logger.debug "> #{__convert_to_json(body)}" if body logger.debug "< #{response.body}" end # Log failed request # # @api private # def __log_failed(response) logger.fatal "[#{response.status}] #{response.body}" end # Trace the request in the `curl` format # # @api private # def __trace(method, path, params, headers, body, url, response, json, took, duration) trace_url = "http://localhost:9200/#{path}?pretty" + ( params.empty? ? '' : "&#{::Faraday::Utils::ParamsHash[params].to_query}" ) trace_body = body ? " -d '#{__convert_to_json(body, :pretty => true)}'" : '' trace_command = "curl -X #{method.to_s.upcase}" trace_command += " -H '#{headers.inject('') { |memo,item| memo << item[0] + ': ' + item[1] }}'" if headers && !headers.empty? trace_command += " '#{trace_url}'#{trace_body}\n" tracer.info trace_command tracer.debug "# #{Time.now.iso8601} [#{response.status}] (#{format('%.3f', duration)}s)\n#" tracer.debug json ? serializer.dump(json, :pretty => true).gsub(/^/, '# ').sub(/\}$/, "\n# }")+"\n" : "# #{response.body}\n" end # Raise error specific for the HTTP response status or a generic server error # # @api private # def __raise_transport_error(response) error = ERRORS[response.status] || ServerError raise error.new "[#{response.status}] #{response.body}" end # Converts any non-String object to JSON # # @api private # def __convert_to_json(o=nil, options={}) o = o.is_a?(String) ? o : serializer.dump(o, options) end # Returns a full URL based on information from host # # @param host [Hash] Host configuration passed in from {Client} # # @api private def __full_url(host) url = "#{host[:protocol]}://" url += "#{CGI.escape(host[:user])}:#{CGI.escape(host[:password])}@" if host[:user] url += "#{host[:host]}:#{host[:port]}" url += "#{host[:path]}" if host[:path] url end # Performs a request to Elasticsearch, while handling logging, tracing, marking dead connections, # retrying the request and reloading the connections. # # @abstract The transport implementation has to implement this method either in full, # or by invoking this method with a block. See {HTTP::Faraday#perform_request} for an example. # # @param method [String] Request method # @param path [String] The API endpoint # @param params [Hash] Request parameters (will be serialized by {Connections::Connection#full_url}) # @param body [Hash] Request body (will be serialized by the {#serializer}) # @param headers [Hash] Request headers (will be serialized by the {#serializer}) # @param block [Proc] Code block to evaluate, passed from the implementation # # @return [Response] # @raise [NoMethodError] If no block is passed # @raise [ServerError] If request failed on server # @raise [Error] If no connection is available # def perform_request(method, path, params={}, body=nil, headers=nil, &block) raise NoMethodError, "Implement this method in your transport class" unless block_given? start = Time.now if logger || tracer tries = 0 params = params.clone ignore = Array(params.delete(:ignore)).compact.map { |s| s.to_i } begin tries += 1 connection = get_connection or raise Error.new("Cannot get new connection from pool.") if connection.connection.respond_to?(:params) && connection.connection.params.respond_to?(:to_hash) params = connection.connection.params.merge(params.to_hash) end url = connection.full_url(path, params) response = block.call(connection, url) connection.healthy! if connection.failures > 0 # Raise an exception so we can catch it for `retry_on_status` __raise_transport_error(response) if response.status.to_i >= 300 && @retry_on_status.include?(response.status.to_i) rescue Elasticsearch::Transport::Transport::ServerError => e if @retry_on_status.include?(response.status) logger.warn "[#{e.class}] Attempt #{tries} to get response from #{url}" if logger if tries <= max_retries retry else logger.fatal "[#{e.class}] Cannot get response from #{url} after #{tries} tries" if logger raise e end else raise e end rescue *host_unreachable_exceptions => e logger.error "[#{e.class}] #{e.message} #{connection.host.inspect}" if logger connection.dead! if @options[:reload_on_failure] and tries < connections.all.size logger.warn "[#{e.class}] Reloading connections (attempt #{tries} of #{connections.all.size})" if logger reload_connections! and retry end if @options[:retry_on_failure] logger.warn "[#{e.class}] Attempt #{tries} connecting to #{connection.host.inspect}" if logger if tries <= max_retries retry else logger.fatal "[#{e.class}] Cannot connect to #{connection.host.inspect} after #{tries} tries" if logger raise e end else raise e end rescue Exception => e logger.fatal "[#{e.class}] #{e.message} (#{connection.host.inspect if connection})" if logger raise e end #/begin duration = Time.now-start if logger || tracer if response.status.to_i >= 300 __log method, path, params, body, url, response, nil, 'N/A', duration if logger __trace method, path, params, headers, body, url, response, nil, 'N/A', duration if tracer # Log the failure only when `ignore` doesn't match the response status __log_failed response if logger && !ignore.include?(response.status.to_i) __raise_transport_error response unless ignore.include?(response.status.to_i) end json = serializer.load(response.body) if response.body && !response.body.empty? && response.headers && response.headers["content-type"] =~ /json/ took = (json['took'] ? sprintf('%.3fs', json['took']/1000.0) : 'n/a') rescue 'n/a' if logger || tracer __log method, path, params, body, url, response, json, took, duration if logger && !ignore.include?(response.status.to_i) __trace method, path, params, headers, body, url, response, json, took, duration if tracer Response.new response.status, json || response.body, response.headers ensure @last_request_at = Time.now end # @abstract Returns an Array of connection errors specific to the transport implementation. # See {HTTP::Faraday#host_unreachable_exceptions} for an example. # # @return [Array] # def host_unreachable_exceptions [Errno::ECONNREFUSED] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/connections/000077500000000000000000000000001361161326000341545ustar00rootroot00000000000000collection.rb000066400000000000000000000063451361161326000365650ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/connectionsmodule Elasticsearch module Transport module Transport module Connections # Wraps the collection of connections for the transport object as an Enumerable object. # # @see Base#connections # @see Selector::Base#select # @see Connection # class Collection include Enumerable DEFAULT_SELECTOR = Selector::RoundRobin attr_reader :selector # @option arguments [Array] :connections An array of {Connection} objects. # @option arguments [Constant] :selector_class The class to be used as a connection selector strategy. # @option arguments [Object] :selector The selector strategy object. # def initialize(arguments={}) selector_class = arguments[:selector_class] || DEFAULT_SELECTOR @connections = arguments[:connections] || [] @selector = arguments[:selector] || selector_class.new(arguments.merge(:connections => self)) end # Returns an Array of hosts information in this collection as Hashes. # # @return [Array] # def hosts @connections.to_a.map { |c| c.host } end # Returns an Array of alive connections. # # @return [Array] # def connections @connections.reject { |c| c.dead? } end alias :alive :connections # Returns an Array of dead connections. # # @return [Array] # def dead @connections.select { |c| c.dead? } end # Returns an Array of all connections, both dead and alive # # @return [Array] # def all @connections end # Returns a connection. # # If there are no alive connections, resurrects a connection with least failures. # Delegates to selector's `#select` method to get the connection. # # @return [Connection] # def get_connection(options={}) if connections.empty? && dead_connection = dead.sort { |a,b| a.failures <=> b.failures }.first dead_connection.alive! end selector.select(options) end def each(&block) connections.each(&block) end def slice(*args) connections.slice(*args) end alias :[] :slice def size connections.size end # Add connection(s) to the collection # # @param connections [Connection,Array] A connection or an array of connections to add # @return [self] # def add(connections) @connections += Array(connections).to_a self end # Remove connection(s) from the collection # # @param connections [Connection,Array] A connection or an array of connections to remove # @return [self] # def remove(connections) @connections -= Array(connections).to_a self end end end end end end connection.rb000066400000000000000000000111201361161326000365540ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/connectionsmodule Elasticsearch module Transport module Transport module Connections # Wraps the connection information and logic. # # The Connection instance wraps the host information (hostname, port, attributes, etc), # as well as the "session" (a transport client object, such as a {HTTP::Faraday} instance). # # It provides methods to construct and properly encode the URLs and paths for passing them # to the transport client object. # # It provides methods to handle connection livecycle (dead, alive, healthy). # class Connection DEFAULT_RESURRECT_TIMEOUT = 60 attr_reader :host, :connection, :options, :failures, :dead_since # @option arguments [Hash] :host Host information (example: `{host: 'localhost', port: 9200}`) # @option arguments [Object] :connection The transport-specific physical connection or "session" # @option arguments [Hash] :options Options (usually passed in from transport) # def initialize(arguments={}) @host = arguments[:host].is_a?(Hash) ? Redacted.new(arguments[:host]) : arguments[:host] @connection = arguments[:connection] @options = arguments[:options] || {} @state_mutex = Mutex.new @options[:resurrect_timeout] ||= DEFAULT_RESURRECT_TIMEOUT @dead = false @failures = 0 end # Returns the complete endpoint URL with host, port, path and serialized parameters. # # @return [String] # def full_url(path, params={}) url = "#{host[:protocol]}://" url += "#{CGI.escape(host[:user])}:#{CGI.escape(host[:password])}@" if host[:user] url += "#{host[:host]}:#{host[:port]}" url += "#{host[:path]}" if host[:path] url += "/#{full_path(path, params)}" end # Returns the complete endpoint path with serialized parameters. # # @return [String] # def full_path(path, params={}) path + (params.empty? ? '' : "?#{::Faraday::Utils::ParamsHash[params].to_query}") end # Returns true when this connection has been marked dead, false otherwise. # # @return [Boolean] # def dead? @dead || false end # Marks this connection as dead, incrementing the `failures` counter and # storing the current time as `dead_since`. # # @return [self] # def dead! @state_mutex.synchronize do @dead = true @failures += 1 @dead_since = Time.now end self end # Marks this connection as alive, ie. it is eligible to be returned from the pool by the selector. # # @return [self] # def alive! @state_mutex.synchronize do @dead = false end self end # Marks this connection as healthy, ie. a request has been successfully performed with it. # # @return [self] # def healthy! @state_mutex.synchronize do @dead = false @failures = 0 end self end # Marks this connection as alive, if the required timeout has passed. # # @return [self,nil] # @see DEFAULT_RESURRECT_TIMEOUT # @see #resurrectable? # def resurrect! alive! if resurrectable? end # Returns true if the connection is eligible to be resurrected as alive, false otherwise. # # @return [Boolean] # def resurrectable? @state_mutex.synchronize { Time.now > @dead_since + ( @options[:resurrect_timeout] * 2 ** (@failures-1) ) } end # Equality operator based on connection protocol, host and port # # @return [Boolean] # def ==(other) self.host[:protocol] == other.host[:protocol] && \ self.host[:host] == other.host[:host] && \ self.host[:port].to_i == other.host[:port].to_i end # @return [String] # def to_s "<#{self.class.name} host: #{host} (#{dead? ? 'dead since ' + dead_since.to_s : 'alive'})>" end end end end end end selector.rb000066400000000000000000000035721361161326000362510ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/connectionsmodule Elasticsearch module Transport module Transport module Connections module Selector # @abstract Common functionality for connection selector implementations. # module Base attr_reader :connections # @option arguments [Connections::Collection] :connections Collection with connections. # def initialize(arguments={}) @connections = arguments[:connections] end # @abstract Selector strategies implement this method to # select and return a connection from the pool. # # @return [Connection] # def select(options={}) raise NoMethodError, "Implement this method in the selector implementation." end end # "Random connection" selector strategy. # class Random include Base # Returns a random connection from the collection. # # @return [Connections::Connection] # def select(options={}) connections.to_a.send( defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' ? :sample : :choice) end end # "Round-robin" selector strategy (default). # class RoundRobin include Base # Returns the next connection from the collection, rotating them in round-robin fashion. # # @return [Connections::Connection] # def select(options={}) # On Ruby 1.9, Array#rotate could be used instead @current = !defined?(@current) || @current.nil? ? 0 : @current+1 @current = 0 if @current >= connections.size connections[@current] end end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/errors.rb000066400000000000000000000037501361161326000335000ustar00rootroot00000000000000module Elasticsearch module Transport module Transport # Generic client error # class Error < StandardError; end # Reloading connections timeout (1 sec by default) # class SnifferTimeoutError < Timeout::Error; end # Elasticsearch server error (HTTP status 5xx) # class ServerError < Error; end module Errors; end HTTP_STATUSES = { 300 => 'MultipleChoices', 301 => 'MovedPermanently', 302 => 'Found', 303 => 'SeeOther', 304 => 'NotModified', 305 => 'UseProxy', 307 => 'TemporaryRedirect', 308 => 'PermanentRedirect', 400 => 'BadRequest', 401 => 'Unauthorized', 402 => 'PaymentRequired', 403 => 'Forbidden', 404 => 'NotFound', 405 => 'MethodNotAllowed', 406 => 'NotAcceptable', 407 => 'ProxyAuthenticationRequired', 408 => 'RequestTimeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'LengthRequired', 412 => 'PreconditionFailed', 413 => 'RequestEntityTooLarge', 414 => 'RequestURITooLong', 415 => 'UnsupportedMediaType', 416 => 'RequestedRangeNotSatisfiable', 417 => 'ExpectationFailed', 418 => 'ImATeapot', 421 => 'TooManyConnectionsFromThisIP', 426 => 'UpgradeRequired', 450 => 'BlockedByWindowsParentalControls', 494 => 'RequestHeaderTooLarge', 497 => 'HTTPToHTTPS', 499 => 'ClientClosedRequest', 500 => 'InternalServerError', 501 => 'NotImplemented', 502 => 'BadGateway', 503 => 'ServiceUnavailable', 504 => 'GatewayTimeout', 505 => 'HTTPVersionNotSupported', 506 => 'VariantAlsoNegotiates', 510 => 'NotExtended' } ERRORS = HTTP_STATUSES.inject({}) do |sum, error| status, name = error sum[status] = Errors.const_set name, Class.new(ServerError) sum end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/http/000077500000000000000000000000001361161326000326115ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/http/curb.rb000066400000000000000000000053651361161326000341020ustar00rootroot00000000000000module Elasticsearch module Transport module Transport module HTTP # Alternative HTTP transport implementation, using the [_Curb_](https://rubygems.org/gems/curb) client. # # @see Transport::Base # class Curb include Base # Performs the request by invoking {Transport::Base#perform_request} with a block. # # @return [Response] # @see Transport::Base#perform_request # def perform_request(method, path, params={}, body=nil, headers=nil) super do |connection,url| connection.connection.url = url case method when 'HEAD' connection.connection.set :nobody, true when 'GET', 'POST', 'PUT', 'DELETE' connection.connection.set :nobody, false connection.connection.put_data = __convert_to_json(body) if body connection.connection.headers = headers if headers else raise ArgumentError, "Unsupported HTTP method: #{method}" end connection.connection.http(method.to_sym) response_headers = {} response_headers['content-type'] = 'application/json' if connection.connection.header_str =~ /\/json/ Response.new connection.connection.response_code, connection.connection.body_str, response_headers end end # Builds and returns a connection # # @return [Connections::Connection] # def __build_connection(host, options={}, block=nil) client = ::Curl::Easy.new headers = options[:headers] || {} headers.update('User-Agent' => "Curb #{Curl::CURB_VERSION}") client.headers = headers client.url = __full_url(host) if host[:user] client.http_auth_types = host[:auth_type] || :basic client.username = host[:user] client.password = host[:password] end client.instance_eval(&block) if block Connections::Connection.new :host => host, :connection => client end # Returns an array of implementation specific connection errors. # # @return [Array] # def host_unreachable_exceptions [ ::Curl::Err::HostResolutionError, ::Curl::Err::ConnectionFailedError, ::Curl::Err::GotNothingError, ::Curl::Err::RecvError, ::Curl::Err::SendError, ::Curl::Err::TimeoutError ] end end end end end end faraday.rb000066400000000000000000000034021361161326000344650ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/httpmodule Elasticsearch module Transport module Transport module HTTP # The default transport implementation, using the [_Faraday_](https://rubygems.org/gems/faraday) # library for abstracting the HTTP client. # # @see Transport::Base # class Faraday include Base # Performs the request by invoking {Transport::Base#perform_request} with a block. # # @return [Response] # @see Transport::Base#perform_request # def perform_request(method, path, params={}, body=nil, headers=nil) super do |connection, url| headers = headers || connection.connection.headers response = connection.connection.run_request(method.downcase.to_sym, url, ( body ? __convert_to_json(body) : nil ), headers) Response.new response.status, response.body, response.headers end end # Builds and returns a connection # # @return [Connections::Connection] # def __build_connection(host, options={}, block=nil) client = ::Faraday::Connection.new(__full_url(host), options, &block) Connections::Connection.new :host => host, :connection => client end # Returns an array of implementation specific connection errors. # # @return [Array] # def host_unreachable_exceptions [::Faraday::Error::ConnectionFailed, ::Faraday::Error::TimeoutError] end end end end end end manticore.rb000066400000000000000000000121551361161326000350440ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/httprequire 'manticore' module Elasticsearch module Transport module Transport module HTTP # Alternative HTTP transport implementation for JRuby, # using the [_Manticore_](https://github.com/cheald/manticore) client, # # @example HTTP # # require 'elasticsearch/transport/transport/http/manticore' # # client = Elasticsearch::Client.new transport_class: Elasticsearch::Transport::Transport::HTTP::Manticore # # client.transport.connections.first.connection # => # # # client.info['status'] # => 200 # # @example HTTPS (All SSL settings are optional, # see http://www.rubydoc.info/gems/manticore/Manticore/Client:initialize) # # require 'elasticsearch/transport/transport/http/manticore' # # client = Elasticsearch::Client.new \ # url: 'https://elasticsearch.example.com', # transport_class: Elasticsearch::Transport::Transport::HTTP::Manticore, # ssl: { # truststore: '/tmp/truststore.jks', # truststore_password: 'password', # keystore: '/tmp/keystore.jks', # keystore_password: 'secret', # } # # client.transport.connections.first.connection # => # # # client.info['status'] # => 200 # # @see Transport::Base # class Manticore include Base def initialize(arguments={}, &block) @manticore = build_client(arguments[:options] || {}) super(arguments, &block) end # Should just be run once at startup def build_client(options={}) client_options = options[:transport_options] || {} client_options[:ssl] = options[:ssl] || {} @manticore = ::Manticore::Client.new(client_options) end # Performs the request by invoking {Transport::Base#perform_request} with a block. # # @return [Response] # @see Transport::Base#perform_request # def perform_request(method, path, params={}, body=nil, headers=nil) super do |connection, url| params[:body] = __convert_to_json(body) if body params[:headers] = headers if headers params = params.merge @request_options case method when "GET" resp = connection.connection.get(url, params) when "HEAD" resp = connection.connection.head(url, params) when "PUT" resp = connection.connection.put(url, params) when "POST" resp = connection.connection.post(url, params) when "DELETE" resp = connection.connection.delete(url, params) else raise ArgumentError.new "Method #{method} not supported" end Response.new resp.code, resp.read_body, resp.headers end end # Builds and returns a collection of connections. # Each connection is a Manticore::Client # # @return [Connections::Collection] # def __build_connections @request_options = {} if options[:transport_options] && options[:transport_options][:headers] @request_options[:headers] = options[:transport_options][:headers] end if options.key?(:headers) @request_options[:headers] = options[:headers] end Connections::Collection.new \ :connections => hosts.map { |host| host[:protocol] = host[:scheme] || DEFAULT_PROTOCOL host[:port] ||= DEFAULT_PORT host.delete(:user) # auth is not supported here. host.delete(:password) # use the headers Connections::Connection.new \ :host => host, :connection => @manticore }, :selector_class => options[:selector_class], :selector => options[:selector] end # Closes all connections by marking them as dead # and closing the underlying HttpClient instances # # @return [Connections::Collection] # def __close_connections # The Manticore adapter uses a single long-lived instance # of Manticore::Client, so we don't close the connections. end # Returns an array of implementation specific connection errors. # # @return [Array] # def host_unreachable_exceptions [ ::Manticore::Timeout, ::Manticore::SocketException, ::Manticore::ClientProtocolException, ::Manticore::ResolutionFailure ] end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/response.rb000066400000000000000000000010761361161326000340210ustar00rootroot00000000000000module Elasticsearch module Transport module Transport # Wraps the response from Elasticsearch. # class Response attr_reader :status, :body, :headers # @param status [Integer] Response status code # @param body [String] Response body # @param headers [Hash] Response headers def initialize(status, body, headers={}) @status, @body, @headers = status, body, headers @body = body.force_encoding('UTF-8') if body.respond_to?(:force_encoding) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/serializer/000077500000000000000000000000001361161326000340035ustar00rootroot00000000000000multi_json.rb000066400000000000000000000016041361161326000364350ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/serializermodule Elasticsearch module Transport module Transport module Serializer # An abstract class for implementing serializer implementations # module Base # @param transport [Object] The instance of transport which uses this serializer # def initialize(transport=nil) @transport = transport end end # A default JSON serializer (using [MultiJSON](http://rubygems.org/gems/multi_json)) # class MultiJson include Base # De-serialize a Hash from JSON string # def load(string, options={}) ::MultiJson.load(string, options) end # Serialize a Hash to JSON string # def dump(object, options={}) ::MultiJson.dump(object, options) end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/transport/sniffer.rb000066400000000000000000000032341361161326000336150ustar00rootroot00000000000000module Elasticsearch module Transport module Transport # Handles node discovery ("sniffing") # class Sniffer PROTOCOL = 'http' attr_reader :transport attr_accessor :timeout # @param transport [Object] A transport instance # def initialize(transport) @transport = transport @timeout = transport.options[:sniffer_timeout] || 1 end # Retrieves the node list from the Elasticsearch's # [_Nodes Info API_](http://www.elasticsearch.org/guide/reference/api/admin-cluster-nodes-info/) # and returns a normalized Array of information suitable for passing to transport. # # Shuffles the collection before returning it when the `randomize_hosts` option is set for transport. # # @return [Array] # @raise [SnifferTimeoutError] # def hosts Timeout::timeout(timeout, SnifferTimeoutError) do nodes = transport.perform_request('GET', '_nodes/http').body hosts = nodes['nodes'].map do |id,info| if info[PROTOCOL] host, port = info[PROTOCOL]['publish_address'].split(':') { :id => id, :name => info['name'], :version => info['version'], :host => host, :port => port, :roles => info['roles'], :attributes => info['attributes'] } end end.compact hosts.shuffle! if transport.options[:randomize_hosts] hosts end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/lib/elasticsearch/transport/version.rb000066400000000000000000000001101361161326000316000ustar00rootroot00000000000000module Elasticsearch module Transport VERSION = '6.8.1' end end elasticsearch-ruby-6.8.1/elasticsearch-transport/spec/000077500000000000000000000000001361161326000231145ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/spec/elasticsearch/000077500000000000000000000000001361161326000257265ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/spec/elasticsearch/transport/000077500000000000000000000000001361161326000277625ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/spec/elasticsearch/transport/base_spec.rb000066400000000000000000000046251361161326000322420ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. require 'spec_helper' describe Elasticsearch::Transport::Transport::Base do context 'when a host is printed in a logged message' do shared_examples_for 'a redacted string' do let(:client) do Elasticsearch::Transport::Client.new(arguments) end let(:logger) do double('logger', error?: true, error: '') end it 'does not include the password in the logged string' do expect(logger).not_to receive(:error).with(/secret_password/) expect { client.cluster.stats }.to raise_exception(Faraday::ConnectionFailed) end it 'replaces the password with the string \'REDACTED\'' do expect(logger).to receive(:error).with(/REDACTED/) expect { client.cluster.stats }.to raise_exception(Faraday::ConnectionFailed) end end context 'when the user and password are provided as separate arguments' do let(:arguments) do { hosts: 'fake', logger: logger, password: 'secret_password', user: 'test' } end it_behaves_like 'a redacted string' end context 'when the user and password are provided in the string URI' do let(:arguments) do { hosts: 'https://test:secret_password@fake_local_elasticsearch', logger: logger } end it_behaves_like 'a redacted string' end context 'when the user and password are provided in the URI object' do let(:arguments) do { hosts: URI.parse('https://test:secret_password@fake_local_elasticsearch'), logger: logger } end it_behaves_like 'a redacted string' end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb000066400000000000000000000615361361161326000326120ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. require 'spec_helper' describe Elasticsearch::Transport::Client do let(:client) do described_class.new.tap do |_client| allow(_client).to receive(:__build_connections) end end it 'is aliased as Elasticsearch::Client' do expect(Elasticsearch::Client.new).to be_a(described_class) end it 'has a default transport' do expect(client.transport).to be_a(Elasticsearch::Transport::Client::DEFAULT_TRANSPORT_CLASS) end it 'uses Faraday as the default transport' do expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/Faraday/) end it 'sets the \'Content-Type\' header to \'application/json\' by default' do expect(client.transport.options[:transport_options][:headers]['Content-Type']).to eq('application/json') end it 'uses localhost by default' do expect(client.transport.hosts[0][:host]).to eq('localhost') end describe 'adapter' do context 'when no adapter is specified' do let(:adapter) do client.transport.connections.all.first.connection.builder.handlers end it 'uses Faraday NetHttp' do expect(adapter).to include(Faraday::Adapter::NetHttp) end end context 'when the adapter is specified' do let(:adapter) do client.transport.connections.all.first.connection.builder.handlers end let(:client) do described_class.new(adapter: :typhoeus) end it 'uses Faraday' do expect(adapter).to include(Faraday::Adapter::Typhoeus) end end context 'when the adapter can be detected', unless: jruby? do around do |example| require 'patron'; load 'patron.rb' example.run end let(:adapter) do client.transport.connections.all.first.connection.builder.handlers end it 'uses the detected adapter' do expect(adapter).to include(Faraday::Adapter::Patron) end end context 'when the Faraday adapter is configured' do let(:client) do described_class.new do |faraday| faraday.adapter :typhoeus faraday.response :logger end end let(:handlers) do client.transport.connections.all.first.connection.builder.handlers end it 'sets the adapter' do expect(handlers).to include(Faraday::Adapter::Typhoeus) end it 'sets the logger' do expect(handlers).to include(Faraday::Response::Logger) end end end shared_examples_for 'a client that extracts hosts' do context 'when the hosts are a String' do let(:host) do 'myhost' end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:protocol]).to eq('http') expect(hosts[0][:port]).to be(9200) end context 'when a path is specified' do let(:host) do 'https://myhost:8080/api' end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:path]).to eq('/api') expect(hosts[0][:port]).to be(8080) end end context 'when a scheme is specified' do let(:host) do 'https://myhost:8080' end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(8080) end end context 'when credentials are specified' do let(:host) do 'http://USERNAME:PASSWORD@myhost:8080' end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('http') expect(hosts[0][:user]).to eq('USERNAME') expect(hosts[0][:password]).to eq('PASSWORD') expect(hosts[0][:port]).to be(8080) end end context 'when there is a trailing slash' do let(:host) do 'http://myhost/' end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('http') expect(hosts[0][:path]).to eq('') end end context 'when there is a trailing slash with a path' do let(:host) do 'http://myhost/foo/bar/' end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('http') expect(hosts[0][:path]).to eq('/foo/bar') end end end context 'when the hosts are a Hash' do let(:host) do { :host => 'myhost', :scheme => 'https' } end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(9200) end context 'when the port is specified as a String' do let(:host) do { host: 'myhost', scheme: 'https', port: '443' } end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(443) end end context 'when the port is specified as an Integer' do let(:host) do { host: 'myhost', scheme: 'https', port: 443 } end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(443) end end end context 'when the hosts are a Hashie:Mash' do let(:host) do Hashie::Mash.new(host: 'myhost', scheme: 'https') end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(9200) end context 'when the port is specified as a String' do let(:host) do Hashie::Mash.new(host: 'myhost', scheme: 'https', port: '443') end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(443) end end context 'when the port is specified as an Integer' do let(:host) do Hashie::Mash.new(host: 'myhost', scheme: 'https', port: 443) end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(443) end end end context 'when the hosts are an array' do context 'when there is one host' do let(:host) do ['myhost'] end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:protocol]).to eq('http') expect(hosts[0][:port]).to be(9200) end end context 'when there is more than one host' do let(:host) do ['host1', 'host2'] end it 'extracts the host' do expect(hosts[0][:host]).to eq('host1') expect(hosts[0][:protocol]).to eq('http') expect(hosts[0][:port]).to be(9200) expect(hosts[1][:host]).to eq('host2') expect(hosts[1][:protocol]).to eq('http') expect(hosts[1][:port]).to be(9200) end end context 'when ports are also specified' do let(:host) do ['host1:1000', 'host2:2000'] end it 'extracts the host' do expect(hosts[0][:host]).to eq('host1') expect(hosts[0][:protocol]).to eq('http') expect(hosts[0][:port]).to be(1000) expect(hosts[1][:host]).to eq('host2') expect(hosts[1][:protocol]).to eq('http') expect(hosts[1][:port]).to be(2000) end end end context 'when the hosts is an instance of URI' do let(:host) do URI.parse('https://USERNAME:PASSWORD@myhost:4430') end it 'extracts the host' do expect(hosts[0][:host]).to eq('myhost') expect(hosts[0][:scheme]).to eq('https') expect(hosts[0][:port]).to be(4430) expect(hosts[0][:user]).to eq('USERNAME') expect(hosts[0][:password]).to eq('PASSWORD') end end context 'when the hosts is invalid' do let(:host) do 123 end it 'extracts the host' do expect { hosts }.to raise_exception(ArgumentError) end end end context 'when hosts are specified with the \'host\' key' do let(:client) do described_class.new(hosts: ['host1', 'host2', 'host3', 'host4'], randomize_hosts: true) end let(:hosts) do client.transport.hosts end it 'sets the hosts in random order' do expect(hosts.all? { |host| client.transport.hosts.include?(host) }).to be(true) end end context 'when hosts are specified with the \'host\' key' do let(:client) do described_class.new(host: host) end let(:hosts) do client.transport.hosts end it_behaves_like 'a client that extracts hosts' end context 'when hosts are specified with the \'hosts\' key' do let(:client) do described_class.new(host: host) end let(:hosts) do client.transport.hosts end it_behaves_like 'a client that extracts hosts' end context 'when hosts are specified with the \'url\' key' do let(:client) do described_class.new(host: host) end let(:hosts) do client.transport.hosts end it_behaves_like 'a client that extracts hosts' end context 'when hosts are specified with the \'urls\' key' do let(:client) do described_class.new(host: host) end let(:hosts) do client.transport.hosts end it_behaves_like 'a client that extracts hosts' end context 'when the URL is set in the ELASTICSEARCH_URL environment variable' do context 'when there is only one host specified' do around do |example| before_url = ENV['ELASTICSEARCH_URL'] ENV['ELASTICSEARCH_URL'] = 'example.com' example.run ENV['ELASTICSEARCH_URL'] = before_url end it 'sets the host' do expect(client.transport.hosts[0][:host]).to eq('example.com') expect(client.transport.hosts.size).to eq(1) end end context 'when mutliple hosts are specified as a comma-separated String list' do around do |example| before_url = ENV['ELASTICSEARCH_URL'] ENV['ELASTICSEARCH_URL'] = 'example.com, other.com' example.run ENV['ELASTICSEARCH_URL'] = before_url end it 'sets the hosts' do expect(client.transport.hosts[0][:host]).to eq('example.com') expect(client.transport.hosts[1][:host]).to eq('other.com') expect(client.transport.hosts.size).to eq(2) end end end context 'when options are defined' do context 'when scheme is specified' do let(:client) do described_class.new(scheme: 'https') end it 'sets the scheme' do expect(client.transport.connections[0].full_url('')).to match(/https/) end end context 'when user and password are specified' do let(:client) do described_class.new(user: 'USERNAME', password: 'PASSWORD') end it 'sets the user and password' do expect(client.transport.connections[0].full_url('')).to match(/USERNAME/) expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/) end context 'when the connections are reloaded' do before do allow(client.transport.sniffer).to receive(:hosts).and_return([{ host: 'foobar', port: 4567, id: 'foobar4567' }]) client.transport.reload_connections! end it 'sets keeps user and password' do expect(client.transport.connections[0].full_url('')).to match(/USERNAME/) expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/) expect(client.transport.connections[0].full_url('')).to match(/foobar/) end end end context 'when port is specified' do let(:client) do described_class.new(host: 'node1', port: 1234) end it 'sets the port' do expect(client.transport.connections[0].full_url('')).to match(/1234/) end end context 'when the log option is true' do let(:client) do described_class.new(log: true) end it 'has a default logger for transport' do expect(client.transport.logger.info).to eq(described_class::DEFAULT_LOGGER.call.info) end end context 'when the trace option is true' do let(:client) do described_class.new(trace: true) end it 'has a default logger for transport' do expect(client.transport.tracer.info).to eq(described_class::DEFAULT_TRACER.call.info) end end context 'when a custom transport class is specified' do let(:transport_class) do Class.new { def initialize(*); end } end let(:client) do described_class.new(transport_class: transport_class) end it 'allows the custom transport class to be defined' do expect(client.transport).to be_a(transport_class) end end context 'when a custom transport instance is specified' do let(:transport_instance) do Class.new { def initialize(*); end }.new end let(:client) do described_class.new(transport: transport_instance) end it 'allows the custom transport class to be defined' do expect(client.transport).to be(transport_instance) end end context 'when \'transport_options\' are defined' do let(:client) do described_class.new(transport_options: { request: { timeout: 1 } }) end it 'sets the options on the transport' do expect(client.transport.options[:transport_options][:request]).to eq(timeout: 1) end end context 'when \'request_timeout\' is defined' do let(:client) do described_class.new(request_timeout: 120) end it 'sets the options on the transport' do expect(client.transport.options[:transport_options][:request]).to eq(timeout: 120) end end end describe '#perform_request' do let(:transport_instance) do Class.new { def initialize(*); end }.new end let(:client) do described_class.new(transport: transport_instance) end it 'delegates performing requests to the transport' do expect(transport_instance).to receive(:perform_request).and_return(true) expect(client.perform_request('GET', '/')).to be(true) end context 'when the \'send_get_body_as\' option is specified' do let(:client) do described_class.new(transport: transport_instance, :send_get_body_as => 'POST') end before do expect(transport_instance).to receive(:perform_request).with('POST', '/', {}, '{"foo":"bar"}', '{"Content-Type":"application/x-ndjson"}').and_return(true) end let(:request) do client.perform_request('POST', '/', {}, '{"foo":"bar"}', '{"Content-Type":"application/x-ndjson"}') end it 'sets the option' do expect(request).to be(true) end end end context 'when the client connects to Elasticsearch' do let(:logger) do Logger.new(STDERR).tap do |logger| logger.formatter = proc do |severity, datetime, progname, msg| color = case severity when /INFO/ then :green when /ERROR|WARN|FATAL/ then :red when /DEBUG/ then :cyan else :white end ANSI.ansi(severity[0] + ' ', color, :faint) + ANSI.ansi(msg, :white, :faint) + "\n" end end unless ENV['QUIET'] end let(:port) do (ENV['TEST_CLUSTER_PORT'] || 9250).to_i end let(:transport_options) do {} end let(:options) do {} end let(:client) do described_class.new({ host: hosts, logger: logger }.merge!(transport_options: transport_options).merge!(options)) end context 'when a request is made' do let!(:response) do client.perform_request('GET', '_cluster/health') end it 'connects to the cluster' do expect(response.body['number_of_nodes']).to be >(1) end end describe '#initialize' do context 'when options are specified' do let(:transport_options) do { headers: { accept: 'application/yaml', content_type: 'application/yaml' } } end let(:response) do client.perform_request('GET', '_cluster/health') end it 'applies the options to the client' do expect(response.body).to match(/---\n/) expect(response.headers['content-type']).to eq('application/yaml') end end context 'when a block is provided' do let(:client) do Elasticsearch::Client.new(host: ELASTICSEARCH_HOSTS.first, logger: logger) do |client| client.headers['Accept'] = 'application/yaml' end end let(:response) do client.perform_request('GET', '_cluster/health') end it 'executes the block' do expect(response.body).to match(/---\n/) expect(response.headers['content-type']).to eq('application/yaml') end context 'when the Faraday adapter is set in the block' do let(:client) do Elasticsearch::Client.new(host: ELASTICSEARCH_HOSTS.first, logger: logger) do |client| client.adapter(:net_http_persistent) end end let(:connection_handler) do client.transport.connections.first.connection.builder.handlers.first end let(:response) do client.perform_request('GET', '_cluster/health') end it 'sets the adapter' do expect(connection_handler.name).to eq('Faraday::Adapter::NetHttpPersistent') end it 'uses the adapter to connect' do expect(response.status).to eq(200) end end end end describe '#options' do context 'when retry_on_failure is true' do context 'when a node is unreachable' do let(:hosts) do [ELASTICSEARCH_HOSTS.first, "foobar1", "foobar2"] end let(:options) do { retry_on_failure: true } end let(:responses) do 5.times.collect do client.perform_request('GET', '_nodes/_local') end end it 'retries on failure' do expect(responses.all? { true }).to be(true) end end end context 'when retry_on_failure is an integer' do let(:hosts) do [ELASTICSEARCH_HOSTS.first, 'foobar1', 'foobar2', 'foobar3'] end let(:options) do { retry_on_failure: 1 } end it 'retries only the specified number of times' do expect(client.perform_request('GET', '_nodes/_local')) expect { client.perform_request('GET', '_nodes/_local') }.to raise_exception(Faraday::Error::ConnectionFailed) end end context 'when reload_on_failure is true' do let(:hosts) do [ELASTICSEARCH_HOSTS.first, 'foobar1', 'foobar2'] end let(:options) do { reload_on_failure: true } end let(:responses) do 5.times.collect do client.perform_request('GET', '_nodes/_local') end end it 'reloads the connections' do expect(client.transport.connections.size).to eq(3) expect(responses.all? { true }).to be(true) expect(client.transport.connections.size).to eq(2) end end context 'when retry_on_status is specified' do let(:options) do { retry_on_status: 400 } end let(:logger) do double('logger', :fatal => false) end before do expect(logger).to receive(:warn).exactly(4).times end it 'retries when the status matches' do expect { client.perform_request('PUT', '_foobar') }.to raise_exception(Elasticsearch::Transport::Transport::Errors::BadRequest) end end end describe '#perform_request' do context 'when a request is made' do before do client.perform_request('DELETE', '_all') client.perform_request('DELETE', 'myindex') rescue client.perform_request('PUT', 'myindex', {}, { settings: { number_of_shards: 10 } }) client.perform_request('PUT', 'myindex/mydoc/1', { routing: 'XYZ', timeout: '1s' }, { foo: 'bar' }) client.perform_request('GET', '_cluster/health?wait_for_status=green', {}) end let(:response) do client.perform_request('GET', 'myindex/mydoc/1?routing=XYZ') end it 'handles paths and URL paramters' do expect(response.status).to eq(200) end it 'returns response body' do expect(response.body['_source']).to eq('foo' => 'bar') end end context 'when an invalid url is specified' do it 'raises an exception' do expect { client.perform_request('GET', 'myindex/mydoc/1?routing=FOOBARBAZ') }.to raise_exception(Elasticsearch::Transport::Transport::Errors::NotFound) end end context 'when the \'ignore\' parameter is specified' do let(:response) do client.perform_request('PUT', '_foobar', ignore: 400) end it 'exposes the status in the response' do expect(response.status).to eq(400) end it 'exposes the body of the response' do expect(response.body).to be_a(Hash) expect(response.body.inspect).to match(/invalid_index_name_exception/) end end context 'when request headers are specified' do let(:response) do client.perform_request('GET', '/', {}, nil, { 'Content-Type' => 'application/yaml' }) end it 'passes them to the transport' do expect(response.body).to match(/---/) end end describe 'selector' do context 'when the round-robin selector is used' do let(:nodes) do 3.times.collect do client.perform_request('GET', '_nodes/_local').body['nodes'].to_a[0][1]['name'] end end let(:node_names) do client.nodes.stats['nodes'].collect do |name, stats| stats['name'] end end let(:expected_names) do 3.times.collect do |i| node_names[i % node_names.size] end end # it 'rotates nodes' do # pending 'Better way to detect rotating nodes' # expect(nodes).to eq(expected_names) # end end end context 'when patron is used as an adapter', unless: jruby? do before do require 'patron' end let(:options) do { adapter: :patron } end let(:connection_handler) do client.transport.connections.first.connection.builder.handlers.first end it 'uses the patron connection handler' do expect(connection_handler).to eq('Faraday::Adapter::Patron') end it 'keeps connections open' do response = client.perform_request('GET', '_nodes/stats/http') connections_before = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened'] client.transport.reload_connections! response = client.perform_request('GET', '_nodes/stats/http') connections_after = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened'] expect(connections_after).to be >= (connections_before) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/spec/spec_helper.rb000066400000000000000000000024731361161326000257400ustar00rootroot00000000000000require 'elasticsearch' require 'elasticsearch-transport' require 'logger' require 'ansi/code' require 'hashie/mash' require 'pry-nav' # The hosts to use for creating a elasticsearch client. # # @since 7.0.0 ELASTICSEARCH_HOSTS = if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end end.freeze # Are we testing on JRuby? # # @return [ true, false ] Whether JRuby is being used. # # @since 7.0.0 def jruby? RUBY_PLATFORM =~ /\bjava\b/ end # The names of the connected nodes. # # @return [ Array ] The node names. # # @since 7.0.0 def node_names $node_names ||= default_client.nodes.stats['nodes'].collect do |name, stats| stats['name'] end end # The default client. # # @return [ Elasticsearch::Client ] The default client. # # @since 7.0.0 def default_client $client ||= Elasticsearch::Client.new(hosts: ELASTICSEARCH_HOSTS) end module Config def self.included(context) # Get the hosts to use to connect an elasticsearch client. # # @since 7.0.0 context.let(:hosts) { ELASTICSEARCH_HOSTS } end end RSpec.configure do |config| config.include(Config) config.formatter = 'documentation' config.color = true end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/000077500000000000000000000000001361161326000231415ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/test/integration/000077500000000000000000000000001361161326000254645ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/test/integration/transport_test.rb000066400000000000000000000054171361161326000311130ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::ClientIntegrationTest < Elasticsearch::Test::IntegrationTestCase startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 2) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 2) end shutdown do Elasticsearch::Extensions::Test::Cluster.stop(number_of_nodes: 2) if ENV['SERVER'] and Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 2) end context "Transport" do setup do @host, @port = ELASTICSEARCH_HOSTS.first.split(':') begin; Object.send(:remove_const, :Patron); rescue NameError; end end should "allow to customize the Faraday adapter" do require 'typhoeus' require 'typhoeus/adapters/faraday' transport = Elasticsearch::Transport::Transport::HTTP::Faraday.new \ :hosts => [ { host: @host, port: @port } ] do |f| f.response :logger f.adapter :typhoeus end client = Elasticsearch::Transport::Client.new transport: transport client.perform_request 'GET', '' end should "allow to define connection parameters and pass them" do transport = Elasticsearch::Transport::Transport::HTTP::Faraday.new \ :hosts => [ { host: @host, port: @port } ], :options => { :transport_options => { :params => { :format => 'yaml' } } } client = Elasticsearch::Transport::Client.new transport: transport response = client.perform_request 'GET', '' assert response.body.start_with?("---\n"), "Response body should be YAML: #{response.body.inspect}" end should "use the Curb client" do require 'curb' require 'elasticsearch/transport/transport/http/curb' transport = Elasticsearch::Transport::Transport::HTTP::Curb.new \ :hosts => [ { host: @host, port: @port } ] do |curl| curl.verbose = true end client = Elasticsearch::Transport::Client.new transport: transport client.perform_request 'GET', '' end unless JRUBY should "deserialize JSON responses in the Curb client" do require 'curb' require 'elasticsearch/transport/transport/http/curb' transport = Elasticsearch::Transport::Transport::HTTP::Curb.new \ :hosts => [ { host: @host, port: @port } ] do |curl| curl.verbose = true end client = Elasticsearch::Transport::Client.new transport: transport response = client.perform_request 'GET', '' assert_respond_to(response.body, :to_hash) assert_not_nil response.body['name'] assert_equal 'application/json', response.headers['content-type'] end unless JRUBY end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/profile/000077500000000000000000000000001361161326000246015ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/test/profile/client_benchmark_test.rb000066400000000000000000000104271361161326000314610ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::ClientProfilingTest < Elasticsearch::Test::ProfilingTest startup do Elasticsearch::Extensions::Test::Cluster.start if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end context "Elasticsearch client benchmark" do setup do @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i client = Elasticsearch::Client.new host: "localhost:#{@port}", adapter: ::Faraday.default_adapter client.perform_request 'DELETE', 'ruby_test_benchmark' rescue nil client.perform_request 'PUT', 'ruby_test_benchmark', {}, {settings: {index: {number_of_shards: 1, number_of_replicas: 0}}} 100.times do client.perform_request 'POST', 'ruby_test_benchmark_search/test', {}, {foo: 'bar'}; end client.perform_request 'POST', 'ruby_test_benchmark_search/_refresh' end teardown do client = Elasticsearch::Client.new host: "localhost:#{@port}" client.perform_request 'DELETE', 'ruby_test_benchmark' rescue nil client.perform_request 'DELETE', 'ruby_test_benchmark_search' rescue nil end context "with a single-node cluster and the default adapter" do setup do @client = Elasticsearch::Client.new hosts: "localhost:#{@port}", adapter: ::Faraday.default_adapter end measure "get the cluster info", count: 1_000 do @client.perform_request 'GET', '' end measure "index a document" do @client.perform_request 'POST', 'ruby_test_benchmark/test', {}, {foo: 'bar'} end measure "search" do @client.perform_request 'GET', 'ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end context "with a two-node cluster and the default adapter" do setup do @client = Elasticsearch::Client.new hosts: ["localhost:#{@port}", "localhost:#{@port+1}"], adapter: ::Faraday.default_adapter end measure "get the cluster info", count: 1_000 do @client.perform_request 'GET', '' end measure "index a document"do @client.perform_request 'POST', 'ruby_test_benchmark/test', {}, {foo: 'bar'} end measure "search" do @client.perform_request 'GET', 'ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end context "with a single-node cluster and the Curb client" do setup do require 'curb' require 'elasticsearch/transport/transport/http/curb' @client = Elasticsearch::Client.new host: "localhost:#{@port}", transport_class: Elasticsearch::Transport::Transport::HTTP::Curb end measure "get the cluster info", count: 1_000 do @client.perform_request 'GET', '' end measure "index a document" do @client.perform_request 'POST', 'ruby_test_benchmark/test', {}, {foo: 'bar'} end measure "search" do @client.perform_request 'GET', 'ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end context "with a single-node cluster and the Typhoeus client" do setup do require 'typhoeus' require 'typhoeus/adapters/faraday' @client = Elasticsearch::Client.new host: "localhost:#{@port}", adapter: :typhoeus end measure "get the cluster info", count: 1_000 do @client.perform_request 'GET', '' end measure "index a document" do @client.perform_request 'POST', 'ruby_test_benchmark/test', {}, {foo: 'bar'} end measure "search" do @client.perform_request 'GET', 'ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end context "with a single-node cluster and the Patron adapter" do setup do require 'patron' @client = Elasticsearch::Client.new host: "localhost:#{@port}", adapter: :patron end measure "get the cluster info", count: 1_000 do @client.perform_request 'GET', '' end measure "index a document" do @client.perform_request 'POST', 'ruby_test_benchmark/test', {}, {foo: 'bar'} end measure "search" do @client.perform_request 'GET', 'ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/test_helper.rb000066400000000000000000000050101361161326000260000ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) ELASTICSEARCH_HOSTS = if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end end.freeze if RUBY_1_8 and not ENV['BUNDLE_GEMFILE'] require 'rubygems' gem 'test-unit' end require 'rubygems' if RUBY_1_8 if ENV['COVERAGE'] && ENV['CI'].nil? && !RUBY_1_8 require 'simplecov' SimpleCov.start { add_filter "/test|test_/" } end if ENV['CI'] && !RUBY_1_8 require 'simplecov' require 'simplecov-rcov' SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start { add_filter "/test|test_" } end # Register `at_exit` handler for integration tests shutdown. # MUST be called before requiring `test/unit`. if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' at_exit { Elasticsearch::Test::IntegrationTestCase.__run_at_exit_hooks } end require 'test/unit' require 'shoulda-context' require 'mocha/setup' require 'ansi/code' require 'turn' unless ENV["TM_FILEPATH"] || ENV["NOTURN"] || RUBY_1_8 require 'require-prof' if ENV["REQUIRE_PROF"] require 'elasticsearch-transport' require 'logger' require 'hashie' RequireProf.print_timing_infos if ENV["REQUIRE_PROF"] if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/extensions/test/profiling' unless JRUBY end class Test::Unit::TestCase def setup end def teardown end end module Elasticsearch module Test class IntegrationTestCase < ::Test::Unit::TestCase extend Elasticsearch::Extensions::Test::StartupShutdown shutdown { Elasticsearch::Extensions::Test::Cluster.stop if ENV['SERVER'] && started? && Elasticsearch::Extensions::Test::Cluster.running? } context "IntegrationTest" do; should "noop on Ruby 1.8" do; end; end if RUBY_1_8 end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' end module Test class ProfilingTest < ::Test::Unit::TestCase extend Elasticsearch::Extensions::Test::StartupShutdown extend Elasticsearch::Extensions::Test::Profiling shutdown { Elasticsearch::Extensions::Test::Cluster.stop if ENV['SERVER'] && started? && Elasticsearch::Extensions::Test::Cluster.running? } context "IntegrationTest" do; should "noop on Ruby 1.8" do; end; end if RUBY_1_8 end unless RUBY_1_8 || JRUBY end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/000077500000000000000000000000001361161326000241205ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/connection_collection_test.rb000066400000000000000000000105451361161326000320630ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::Connections::CollectionTest < Test::Unit::TestCase include Elasticsearch::Transport::Transport::Connections context "Connection collection" do should "have empty array as default connections array" do assert_equal [], Collection.new.connections end should "have default selector class" do assert_not_nil Collection.new.selector end should "initialize a custom selector class" do c = Collection.new :selector_class => Selector::Random assert_instance_of Selector::Random, c.selector end should "take a custom selector instance" do c = Collection.new :selector => Selector::Random.new assert_instance_of Selector::Random, c.selector end should "get connection from selector" do c = Collection.new c.selector.expects(:select).returns('OK') assert_equal 'OK', c.get_connection end should "return an array of hosts" do c = Collection.new :connections => [ Connection.new(:host => 'foo'), Connection.new(:host => 'bar') ] assert_equal ['foo', 'bar'], c.hosts end should "be enumerable" do c = Collection.new :connections => [ Connection.new(:host => 'foo'), Connection.new(:host => 'bar') ] assert_equal ['FOO', 'BAR'], c.map { |i| i.host.upcase } assert_equal 'foo', c[0].host assert_equal 'bar', c[1].host assert_equal 2, c.size end should "add connections" do c = Collection.new :connections => [ Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 1}) ] assert_equal 1, c.size c.add([ Connection.new(:host => { :protocol => 'http', :host => 'bar', :port => 1 }), Connection.new(:host => { :protocol => 'http', :host => 'bam', :port => 1 }) ]) assert_equal 3, c.size end should "add connection" do c = Collection.new :connections => [ Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 1}) ] assert_equal 1, c.size c.add(Connection.new(:host => { :protocol => 'http', :host => 'bar', :port => 1 })) assert_equal 2, c.size end should "remove connections" do c = Collection.new :connections => [ Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 1 }), Connection.new(:host => { :protocol => 'http', :host => 'bar', :port => 1 }) ] assert_equal 2, c.size c.remove([c.first]) assert_equal 1, c.size c.remove(c) assert_equal 0, c.size end should "remove connection" do c = Collection.new :connections => [ Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 1 }), Connection.new(:host => { :protocol => 'http', :host => 'bar', :port => 1 }) ] assert_equal 2, c.size c.remove(c.first) assert_equal 1, c.size end context "with the dead pool" do setup do @collection = Collection.new :connections => [ Connection.new(:host => 'foo'), Connection.new(:host => 'bar') ] @collection[1].dead! end should "not iterate over dead connections" do assert_equal 1, @collection.size assert_equal ['FOO'], @collection.map { |c| c.host.upcase } assert_equal @collection.connections, @collection.alive end should "have dead connections collection" do assert_equal 1, @collection.dead.size assert_equal ['BAR'], @collection.dead.map { |c| c.host.upcase } end should "not return dead connections, when alive connections exist" do assert_equal 1, @collection.size @collection.all.size.times { refute @collection.get_connection.dead? } end should "resurrect dead connection with least failures when no alive is available" do c1 = Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 123 }).dead!.dead! c2 = Connection.new(:host => { :protocol => 'http', :host => 'bar', :port => 123 }).dead! @collection = Collection.new :connections => [ c1, c2 ] assert_equal 0, @collection.size assert_not_nil @collection.get_connection assert_equal 1, @collection.size assert_equal c2, @collection.first end should "return all connections" do assert_equal 2, @collection.all.size end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/connection_selector_test.rb000066400000000000000000000036271361161326000315530ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::Connections::SelectorTest < Test::Unit::TestCase include Elasticsearch::Transport::Transport::Connections::Selector class DummyStrategySelector include Elasticsearch::Transport::Transport::Connections::Selector::Base end class BackupStrategySelector include Elasticsearch::Transport::Transport::Connections::Selector::Base def select(options={}) connections.reject do |c| c.host[:attributes] && c.host[:attributes][:backup] end.send( defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' ? :sample : :choice) end end context "Connection selector" do should "be initialized with connections" do assert_equal [1, 2], Random.new(:connections => [1, 2]).connections end should "have the abstract select method" do assert_raise(NoMethodError) { DummyStrategySelector.new.select } end context "in random strategy" do setup do @selector = Random.new :connections => ['A', 'B', 'C'] end should "pick a connection" do assert_not_nil @selector.select end end context "in round-robin strategy" do setup do @selector = RoundRobin.new :connections => ['A', 'B', 'C'] end should "rotate over connections" do assert_equal 'A', @selector.select assert_equal 'B', @selector.select assert_equal 'C', @selector.select assert_equal 'A', @selector.select end end context "with a custom strategy" do should "return proper connection" do selector = BackupStrategySelector.new :connections => [ stub(:host => { :hostname => 'host1' }), stub(:host => { :hostname => 'host2', :attributes => { :backup => true }}) ] 10.times { assert_equal 'host1', selector.select.host[:hostname] } end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/connection_test.rb000066400000000000000000000073761361161326000276600ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::Connections::ConnectionTest < Test::Unit::TestCase include Elasticsearch::Transport::Transport::Connections context "Connection" do should "be initialized with :host, :connection, and :options" do c = Connection.new :host => 'x', :connection => 'y', :options => {} assert_equal 'x', c.host assert_equal 'y', c.connection assert_instance_of Hash, c.options end should "return full path" do c = Connection.new assert_equal '_search', c.full_path('_search') assert_equal '_search', c.full_path('_search', {}) assert_equal '_search?foo=bar', c.full_path('_search', {:foo => 'bar'}) assert_equal '_search?foo=bar+bam', c.full_path('_search', {:foo => 'bar bam'}) end should "return full url" do c = Connection.new :host => { :protocol => 'http', :host => 'localhost', :port => '9200' } assert_equal 'http://localhost:9200/_search?foo=bar', c.full_url('_search', {:foo => 'bar'}) end should "return full url with credentials" do c = Connection.new :host => { :protocol => 'http', :user => 'U', :password => 'P', :host => 'localhost', :port => '9200' } assert_equal 'http://U:P@localhost:9200/_search?foo=bar', c.full_url('_search', {:foo => 'bar'}) end should "return full url with escaped credentials" do c = Connection.new :host => { :protocol => 'http', :user => 'U$$$', :password => 'P^^^', :host => 'localhost', :port => '9200' } assert_equal 'http://U%24%24%24:P%5E%5E%5E@localhost:9200/_search?foo=bar', c.full_url('_search', {:foo => 'bar'}) end should "return full url with path" do c = Connection.new :host => { :protocol => 'http', :host => 'localhost', :port => '9200', :path => '/foo' } assert_equal 'http://localhost:9200/foo/_search?foo=bar', c.full_url('_search', {:foo => 'bar'}) end should "have a string representation" do c = Connection.new :host => 'x' assert_match /host: x/, c.to_s assert_match /alive/, c.to_s end should "not be dead by default" do c = Connection.new assert ! c.dead? end should "be dead when marked" do c = Connection.new.dead! assert c.dead? assert_equal 1, c.failures assert_in_delta c.dead_since, Time.now, 1 end should "be alive when marked" do c = Connection.new.dead! assert c.dead? assert_equal 1, c.failures assert_in_delta c.dead_since, Time.now, 1 c.alive! assert ! c.dead? assert_equal 1, c.failures end should "be healthy when marked" do c = Connection.new.dead! assert c.dead? assert_equal 1, c.failures assert_in_delta c.dead_since, Time.now, 1 c.healthy! assert ! c.dead? assert_equal 0, c.failures end should "be resurrected if timeout passed" do c = Connection.new.dead! now = Time.now + 60 Time.stubs(:now).returns(now) assert c.resurrect!, c.inspect assert ! c.dead?, c.inspect end should "be resurrected if timeout passed for multiple failures" do c = Connection.new.dead!.dead! now = Time.now + 60*2 Time.stubs(:now).returns(now) assert c.resurrect!, c.inspect assert ! c.dead?, c.inspect end should "implement the equality operator" do c1 = Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 123 }) c2 = Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 123 }) c3 = Connection.new(:host => { :protocol => 'http', :host => 'foo', :port => 456 }) assert c1 == c2, "Connection #{c1} should be equal to #{c2}" assert c2 != c3, "Connection #{c2} should NOT be equal to #{c3}" end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/response_test.rb000066400000000000000000000007061361161326000273450ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::ResponseTest < Test::Unit::TestCase context "Response" do should "force-encode the body into UTF" do body = "Hello Encoding!".encode(Encoding::ISO_8859_1) assert_equal 'ISO-8859-1', body.encoding.name response = Elasticsearch::Transport::Transport::Response.new 200, body assert_equal 'UTF-8', response.body.encoding.name end unless RUBY_1_8 end endelasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/serializer_test.rb000066400000000000000000000006411361161326000276560ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::SerializerTest < Test::Unit::TestCase context "Serializer" do should "use MultiJson by default" do ::MultiJson.expects(:load) ::MultiJson.expects(:dump) Elasticsearch::Transport::Transport::Serializer::MultiJson.new.load('{}') Elasticsearch::Transport::Transport::Serializer::MultiJson.new.dump({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/sniffer_test.rb000066400000000000000000000120661361161326000271450ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::SnifferTest < Test::Unit::TestCase class DummyTransport include Elasticsearch::Transport::Transport::Base def __build_connections; hosts; end end def __nodes_info(json) Elasticsearch::Transport::Transport::Response.new 200, MultiJson.load(json) end DEFAULT_NODES_INFO_RESPONSE = <<-JSON { "cluster_name" : "elasticsearch_test", "nodes" : { "N1" : { "name" : "Node 1", "transport_address" : "127.0.0.1:9300", "host" : "testhost1", "ip" : "127.0.0.1", "version" : "5.0.0", "roles": [ "master", "data", "ingest" ], "attributes": { "testattr": "test" }, "http": { "bound_address": [ "[fe80::1]:9250", "[::1]:9250", "127.0.0.1:9250" ], "publish_address": "127.0.0.1:9250", "max_content_length_in_bytes": 104857600 } } } } JSON context "Sniffer" do setup do @transport = DummyTransport.new @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport end should "be initialized with a transport instance" do assert_equal @transport, @sniffer.transport end should "return an array of hosts as hashes" do @transport.expects(:perform_request).returns __nodes_info(DEFAULT_NODES_INFO_RESPONSE) hosts = @sniffer.hosts assert_equal 1, hosts.size assert_equal '127.0.0.1', hosts.first[:host] assert_equal '9250', hosts.first[:port] assert_equal 'Node 1', hosts.first[:name] end should "return an array of hosts as hostnames when a hostname is returned" do @transport.expects(:perform_request).returns __nodes_info <<-JSON { "nodes" : { "N1" : { "http": { "publish_address": "testhost1.com:9250" } } } } JSON hosts = @sniffer.hosts assert_equal 1, hosts.size assert_equal 'testhost1.com', hosts.first[:host] assert_equal '9250', hosts.first[:port] end should "return HTTP hosts for the HTTPS protocol in the transport" do @transport = DummyTransport.new :options => { :protocol => 'https' } @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport @transport.expects(:perform_request).returns __nodes_info(DEFAULT_NODES_INFO_RESPONSE) assert_equal 1, @sniffer.hosts.size end should "skip hosts without a matching transport protocol" do @transport = DummyTransport.new @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport @transport.expects(:perform_request).returns __nodes_info <<-JSON { "nodes" : { "N1" : { "foobar": { "publish_address": "foobar:1234" } } } } JSON assert_empty @sniffer.hosts end should "have configurable timeout" do @transport = DummyTransport.new :options => { :sniffer_timeout => 0.001 } @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport assert_equal 0.001, @sniffer.timeout end should "have settable timeout" do @transport = DummyTransport.new @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport assert_equal 1, @sniffer.timeout @sniffer.timeout = 2 assert_equal 2, @sniffer.timeout end should "raise error on timeout" do @transport.expects(:perform_request).raises(Elasticsearch::Transport::Transport::SnifferTimeoutError) # TODO: Try to inject sleep into `perform_request` or make this test less ridiculous anyhow... assert_raise Elasticsearch::Transport::Transport::SnifferTimeoutError do @sniffer.hosts end end should "randomize hosts" do @transport = DummyTransport.new :options => { :randomize_hosts => true } @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport @transport.expects(:perform_request).returns __nodes_info <<-JSON { "ok" : true, "cluster_name" : "elasticsearch_test", "nodes" : { "N1" : { "name" : "Node 1", "http_address" : "inet[/192.168.1.23:9200]" }, "N2" : { "name" : "Node 2", "http_address" : "inet[/192.168.1.23:9201]" }, "N3" : { "name" : "Node 3", "http_address" : "inet[/192.168.1.23:9202]" }, "N4" : { "name" : "Node 4", "http_address" : "inet[/192.168.1.23:9203]" }, "N5" : { "name" : "Node 5", "http_address" : "inet[/192.168.1.23:9204]" } } } JSON Array.any_instance.expects(:shuffle!) hosts = @sniffer.hosts end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/transport_base_test.rb000066400000000000000000000557051361161326000305460ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::BaseTest < Test::Unit::TestCase class EmptyTransport include Elasticsearch::Transport::Transport::Base end class DummyTransport include Elasticsearch::Transport::Transport::Base def __build_connection(host, options={}, block=nil) Elasticsearch::Transport::Transport::Connections::Connection.new :host => host, :connection => Object.new end end class DummyTransportPerformer < DummyTransport def perform_request(method, path, params={}, body=nil, &block); super; end end class DummySerializer def initialize(*); end end class DummySniffer def initialize(*); end end context "Transport::Base" do should "raise exception when it doesn't implement __build_connection" do assert_raise NoMethodError do EmptyTransport.new.__build_connection({ :host => 'foo'}, {}) end end should "build connections on initialization" do DummyTransport.any_instance.expects(:__build_connections) transport = DummyTransport.new end should "have default serializer" do transport = DummyTransport.new assert_instance_of Elasticsearch::Transport::Transport::Base::DEFAULT_SERIALIZER_CLASS, transport.serializer end should "have custom serializer" do transport = DummyTransport.new :options => { :serializer_class => DummySerializer } assert_instance_of DummySerializer, transport.serializer transport = DummyTransport.new :options => { :serializer => DummySerializer.new } assert_instance_of DummySerializer, transport.serializer end should "have default sniffer" do transport = DummyTransport.new assert_instance_of Elasticsearch::Transport::Transport::Sniffer, transport.sniffer end should "have custom sniffer" do transport = DummyTransport.new :options => { :sniffer_class => DummySniffer } assert_instance_of DummySniffer, transport.sniffer end context "when combining the URL" do setup do @transport = DummyTransport.new @basic_parts = { :protocol => 'http', :host => 'myhost', :port => 8080 } end should "combine basic parts" do assert_equal 'http://myhost:8080', @transport.__full_url(@basic_parts) end should "combine path" do assert_equal 'http://myhost:8080/api', @transport.__full_url(@basic_parts.merge :path => '/api') end should "combine authentication credentials" do assert_equal 'http://U:P@myhost:8080', @transport.__full_url(@basic_parts.merge :user => 'U', :password => 'P') end should "escape the username and password" do assert_equal 'http://user%40domain:foo%2Fbar@myhost:8080', @transport.__full_url(@basic_parts.merge :user => 'user@domain', :password => 'foo/bar') end end end context "getting a connection" do setup do @transport = DummyTransportPerformer.new :options => { :reload_connections => 5 } @transport.stubs(:connections).returns(stub :get_connection => Object.new) @transport.stubs(:sniffer).returns(stub :hosts => []) end should "get a connection" do assert_not_nil @transport.get_connection end should "increment the counter" do assert_equal 0, @transport.counter 3.times { @transport.get_connection } assert_equal 3, @transport.counter end should "reload connections when it hits the threshold" do @transport.expects(:reload_connections!).twice 12.times { @transport.get_connection } assert_equal 12, @transport.counter end should "not reload connections by default" do @transport = DummyTransportPerformer.new @transport.stubs(:connections).returns(stub :get_connection => Object.new) @transport.expects(:reload_connections!).never 10_010.times { @transport.get_connection } assert_equal 10_010, @transport.counter end should "not reload connections when the option is set to false" do @transport = DummyTransportPerformer.new :options => { :reload_connections => false } @transport.stubs(:connections).returns(stub :get_connection => Object.new) @transport.expects(:reload_connections!).never 10_010.times { @transport.get_connection } assert_equal 10_010, @transport.counter end end context "performing a request" do setup do @transport = DummyTransportPerformer.new end should "raise an error when no block is passed" do assert_raise NoMethodError do @transport.peform_request 'GET', '/' end end should "get the connection" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) @transport.perform_request 'GET', '/' do; Elasticsearch::Transport::Transport::Response.new 200, 'OK'; end end should "raise an error when no connection is available" do @transport.expects(:get_connection).returns(nil) assert_raise Elasticsearch::Transport::Transport::Error do @transport.perform_request 'GET', '/' do; Elasticsearch::Transport::Transport::Response.new 200, 'OK'; end end end should "call the passed block" do x = 0 @transport.expects(:get_connection).returns(stub_everything :failures => 1) @transport.perform_request 'GET', '/' do |connection, url| x += 1 Elasticsearch::Transport::Transport::Response.new 200, 'OK' end assert_equal 1, x end should "deserialize a response JSON body" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) @transport.serializer.expects(:load).returns({'foo' => 'bar'}) response = @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 200, '{"foo":"bar"}', {"content-type" => 'application/json'} end assert_instance_of Elasticsearch::Transport::Transport::Response, response assert_equal 'bar', response.body['foo'] end should "not deserialize a response string body" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) @transport.serializer.expects(:load).never response = @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 200, 'FOOBAR', {"content-type" => 'text/plain'} end assert_instance_of Elasticsearch::Transport::Transport::Response, response assert_equal 'FOOBAR', response.body end should "not deserialize an empty response body" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) @transport.serializer.expects(:load).never response = @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 200, '', {"content-type" => 'application/json'} end assert_instance_of Elasticsearch::Transport::Transport::Response, response assert_equal '', response.body end should "serialize non-String objects" do @transport.serializer.expects(:dump).times(3) @transport.__convert_to_json({:foo => 'bar'}) @transport.__convert_to_json([1, 2, 3]) @transport.__convert_to_json(nil) end should "not serialize a String object" do @transport.serializer.expects(:dump).never @transport.__convert_to_json('{"foo":"bar"}') end should "raise an error for HTTP status 404" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) assert_raise Elasticsearch::Transport::Transport::Errors::NotFound do @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 404, 'NOT FOUND' end end end should "raise an error for HTTP status 404 with application/json content type" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) assert_raise Elasticsearch::Transport::Transport::Errors::NotFound do @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 404, 'NOT FOUND', {"content-type" => 'application/json'} end end end should "raise an error on server failure" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) assert_raise Elasticsearch::Transport::Transport::Errors::InternalServerError do @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 500, 'ERROR' end end end should "raise an error on connection failure" do @transport.expects(:get_connection).returns(stub_everything :failures => 1) # `block.expects(:call).raises(::Errno::ECONNREFUSED)` fails on Ruby 1.8 block = lambda { |a, b| raise ::Errno::ECONNREFUSED } assert_raise ::Errno::ECONNREFUSED do @transport.perform_request 'GET', '/', &block end end should "not raise an error when the :ignore argument has been passed" do @transport.stubs(:get_connection).returns(stub_everything :failures => 1) assert_raise Elasticsearch::Transport::Transport::Errors::BadRequest do @transport.perform_request 'GET', '/' do Elasticsearch::Transport::Transport::Response.new 400, 'CLIENT ERROR' end end # No `BadRequest` error @transport.perform_request 'GET', '/', :ignore => 400 do Elasticsearch::Transport::Transport::Response.new 400, 'CLIENT ERROR' end end should "mark the connection as dead on failure" do c = stub_everything :failures => 1 @transport.expects(:get_connection).returns(c) block = lambda { |a,b| raise ::Errno::ECONNREFUSED } c.expects(:dead!) assert_raise( ::Errno::ECONNREFUSED ) { @transport.perform_request 'GET', '/', &block } end end context "performing a request with reload connections on connection failures" do setup do fake_collection = stub_everything :get_connection => stub_everything(:failures => 1), :all => stub_everything(:size => 2) @transport = DummyTransportPerformer.new :options => { :reload_on_failure => 2 } @transport.stubs(:connections). returns(fake_collection) @block = lambda { |c, u| puts "UNREACHABLE" } end should "reload connections when host is unreachable" do @block.expects(:call).times(2). raises(Errno::ECONNREFUSED). then.returns(stub_everything :failures => 1) @transport.expects(:reload_connections!).returns([]) @transport.perform_request('GET', '/', &@block) assert_equal 2, @transport.counter end end unless RUBY_1_8 context "performing a request with retry on connection failures" do setup do @transport = DummyTransportPerformer.new :options => { :retry_on_failure => true } @transport.stubs(:connections).returns(stub :get_connection => stub_everything(:failures => 1)) @block = Proc.new { |c, u| puts "UNREACHABLE" } end should "retry DEFAULT_MAX_RETRIES when host is unreachable" do @block.expects(:call).times(4). raises(Errno::ECONNREFUSED). then.raises(Errno::ECONNREFUSED). then.raises(Errno::ECONNREFUSED). then.returns(stub_everything :failures => 1) assert_nothing_raised do @transport.perform_request('GET', '/', &@block) assert_equal 4, @transport.counter end end should "raise an error after max tries" do @block.expects(:call).times(4). raises(Errno::ECONNREFUSED). then.raises(Errno::ECONNREFUSED). then.raises(Errno::ECONNREFUSED). then.raises(Errno::ECONNREFUSED). then.returns(stub_everything :failures => 1) assert_raise Errno::ECONNREFUSED do @transport.perform_request('GET', '/', &@block) end end end unless RUBY_1_8 context "performing a request with retry on status" do setup do DummyTransportPerformer.any_instance.stubs(:connections).returns(stub :get_connection => stub_everything(:failures => 1)) logger = Logger.new(STDERR) logger.level = Logger::DEBUG DummyTransportPerformer.any_instance.stubs(:logger).returns(logger) @block = Proc.new { |c, u| puts "ERROR" } end should "not retry when the status code does not match" do @transport = DummyTransportPerformer.new :options => { :retry_on_status => 500 } assert_equal [500], @transport.instance_variable_get(:@retry_on_status) @block.expects(:call). returns(Elasticsearch::Transport::Transport::Response.new 400, 'Bad Request'). times(1) @transport.logger. expects(:warn). with( regexp_matches(/Attempt \d to get response/) ). never assert_raise Elasticsearch::Transport::Transport::Errors::BadRequest do @transport.perform_request('GET', '/', {}, nil, &@block) end end should "retry when the status code does match" do @transport = DummyTransportPerformer.new :options => { :retry_on_status => 500 } assert_equal [500], @transport.instance_variable_get(:@retry_on_status) @block.expects(:call). returns(Elasticsearch::Transport::Transport::Response.new 500, 'Internal Error'). times(4) @transport.logger. expects(:warn). with( regexp_matches(/Attempt \d to get response/) ). times(4) assert_raise Elasticsearch::Transport::Transport::Errors::InternalServerError do @transport.perform_request('GET', '/', &@block) end end end unless RUBY_1_8 context "logging" do setup do @transport = DummyTransportPerformer.new :options => { :logger => Logger.new('/dev/null') } fake_connection = stub :full_url => 'localhost:9200/_search?size=1', :host => 'localhost', :connection => stub_everything, :failures => 0, :healthy! => true @transport.stubs(:get_connection).returns(fake_connection) @transport.serializer.stubs(:load).returns 'foo' => 'bar' @transport.serializer.stubs(:dump).returns '{"foo":"bar"}' end should "log the request and response" do @transport.logger.expects(:info). with do |line| line =~ %r|POST localhost\:9200/_search\?size=1 \[status\:200, request:.*s, query:n/a\]| end @transport.logger.expects(:debug). with '> {"foo":"bar"}' @transport.logger.expects(:debug). with '< {"foo":"bar"}' @transport.perform_request 'POST', '_search', {:size => 1}, {:foo => 'bar'} do Elasticsearch::Transport::Transport::Response.new 200, '{"foo":"bar"}' end end should "sanitize password in the URL" do fake_connection = stub :full_url => 'http://user:password@localhost:9200/_search?size=1', :host => 'localhost', :connection => stub_everything, :failures => 0, :healthy! => true @transport.stubs(:get_connection).returns(fake_connection) @transport.logger.expects(:info).with do |message| assert_match /http:\/\/user:\*{1,15}@localhost\:9200/, message true end @transport.perform_request('GET', '/') {Elasticsearch::Transport::Transport::Response.new 200, '{"foo":"bar"}' } end should "log a failed Elasticsearch request as fatal" do @block = Proc.new { |c, u| puts "ERROR" } @block.expects(:call).returns(Elasticsearch::Transport::Transport::Response.new 500, 'ERROR') @transport.expects(:__log) @transport.logger.expects(:fatal) assert_raise Elasticsearch::Transport::Transport::Errors::InternalServerError do @transport.perform_request('POST', '_search', &@block) end end unless RUBY_1_8 should "not log a failed Elasticsearch request as fatal" do @block = Proc.new { |c, u| puts "ERROR" } @block.expects(:call).returns(Elasticsearch::Transport::Transport::Response.new 500, 'ERROR') @transport.expects(:__log).once @transport.logger.expects(:fatal).never # No `BadRequest` error @transport.perform_request('POST', '_search', :ignore => 500, &@block) end unless RUBY_1_8 should "log and re-raise a Ruby exception" do @block = Proc.new { |c, u| puts "ERROR" } @block.expects(:call).raises(Exception) @transport.expects(:__log).never @transport.logger.expects(:fatal) assert_raise(Exception) { @transport.perform_request('POST', '_search', &@block) } end unless RUBY_1_8 end context "tracing" do setup do @transport = DummyTransportPerformer.new :options => { :tracer => Logger.new('/dev/null') } fake_connection = stub :full_url => 'localhost:9200/_search?size=1', :host => 'localhost', :connection => stub_everything, :failures => 0, :healthy! => true @transport.stubs(:get_connection).returns(fake_connection) @transport.serializer.stubs(:load).returns 'foo' => 'bar' @transport.serializer.stubs(:dump).returns <<-JSON.gsub(/^ /, '') { "foo" : { "bar" : { "bam" : true } } } JSON end should "trace the request" do @transport.tracer.expects(:info). with do |message| message == <<-CURL.gsub(/^ /, '') curl -X POST 'http://localhost:9200/_search?pretty&size=1' -d '{ "foo" : { "bar" : { "bam" : true } } } ' CURL end.once @transport.perform_request 'POST', '_search', {:size => 1}, {:q => 'foo'} do Elasticsearch::Transport::Transport::Response.new 200, '{"foo":"bar"}' end end should "trace a failed Elasticsearch request" do @block = Proc.new { |c, u| puts "ERROR" } @block.expects(:call).returns(Elasticsearch::Transport::Transport::Response.new 500, 'ERROR') @transport.expects(:__trace) assert_raise Elasticsearch::Transport::Transport::Errors::InternalServerError do @transport.perform_request('POST', '_search', &@block) end end unless RUBY_1_8 end context "reloading connections" do setup do @transport = DummyTransport.new :options => { :logger => Logger.new('/dev/null') } end should "rebuild connections" do @transport.sniffer.expects(:hosts).returns([]) @transport.expects(:__rebuild_connections) @transport.reload_connections! end should "log error and continue when timing out while sniffing hosts" do @transport.sniffer.expects(:hosts).raises(Elasticsearch::Transport::Transport::SnifferTimeoutError) @transport.logger.expects(:error) assert_nothing_raised do @transport.reload_connections! end end should "keep existing connections" do @transport.__rebuild_connections :hosts => [ { :host => 'node1', :port => 1 } ], :options => { :http => {} } assert_equal 1, @transport.connections.size old_connection_id = @transport.connections.first.object_id @transport.__rebuild_connections :hosts => [ { :host => 'node1', :port => 1 }, { :host => 'node2', :port => 2 } ], :options => { :http => {} } assert_equal 2, @transport.connections.size assert_equal old_connection_id, @transport.connections.first.object_id end should "remove dead connections" do @transport.__rebuild_connections :hosts => [ { :host => 'node1', :port => 1 }, { :host => 'node2', :port => 2 } ], :options => { :http => {} } assert_equal 2, @transport.connections.size @transport.connections[1].dead! @transport.__rebuild_connections :hosts => [ { :host => 'node1', :port => 1 } ], :options => { :http => {} } assert_equal 1, @transport.connections.size assert_equal 1, @transport.connections.all.size end should "not duplicate connections" do @transport.__rebuild_connections :hosts => [ { :host => 'node1', :port => 1 }, { :host => 'node2', :port => 2 } ], :options => { :http => {} } assert_equal 2, @transport.connections.size @transport.connections[0].dead! @transport.__rebuild_connections :hosts => [ { :host => 'node1', :port => 1 }, { :host => 'node2', :port => 2 } ], :options => { :http => {} } assert_equal 2, @transport.connections.all.size assert_equal 1, @transport.connections.size end end context "rebuilding connections" do setup do @transport = DummyTransport.new end should "close connections" do @transport.expects(:__close_connections) @transport.__rebuild_connections :hosts => [ { :scheme => 'http', :host => 'foo', :port => 1 } ], :options => { :http => {} } end should "should replace the connections" do assert_equal 0, @transport.connections.size @transport.__rebuild_connections :hosts => [{ :scheme => 'http', :host => 'foo', :port => 1 }], :options => { :http => {} } assert_equal 1, @transport.connections.size end end context "resurrecting connections" do setup do @transport = DummyTransportPerformer.new end should "delegate to dead connections" do @transport.connections.expects(:dead).returns([]) @transport.resurrect_dead_connections! end should "not resurrect connections until timeout" do @transport.connections.expects(:get_connection).returns(stub_everything :failures => 1).times(5) @transport.expects(:resurrect_dead_connections!).never 5.times { @transport.get_connection } end should "resurrect connections after timeout" do @transport.connections.expects(:get_connection).returns(stub_everything :failures => 1).times(5) @transport.expects(:resurrect_dead_connections!) 4.times { @transport.get_connection } now = Time.now + 60*2 Time.stubs(:now).returns(now) @transport.get_connection end should "mark connection healthy if it succeeds" do c = stub_everything(:failures => 1) @transport.expects(:get_connection).returns(c) c.expects(:healthy!) @transport.perform_request('GET', '/') { |connection, url| Elasticsearch::Transport::Transport::Response.new 200, 'OK' } end end context "errors" do should "raise highest-level Error exception for any ServerError" do assert_kind_of Elasticsearch::Transport::Transport::Error, Elasticsearch::Transport::Transport::ServerError.new end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/transport_curb_test.rb000066400000000000000000000124021361161326000305520ustar00rootroot00000000000000require 'test_helper' if JRUBY puts "'#{File.basename(__FILE__)}' not supported on JRuby #{RUBY_VERSION}" else require 'elasticsearch/transport/transport/http/curb' require 'curb' class Elasticsearch::Transport::Transport::HTTP::FaradayTest < Test::Unit::TestCase include Elasticsearch::Transport::Transport::HTTP context "Curb transport" do setup do @transport = Curb.new :hosts => [ { :host => 'foobar', :port => 1234 } ] end should "implement host_unreachable_exceptions" do assert_instance_of Array, @transport.host_unreachable_exceptions end should "implement __build_connections" do assert_equal 1, @transport.hosts.size assert_equal 1, @transport.connections.size assert_instance_of ::Curl::Easy, @transport.connections.first.connection assert_equal 'http://foobar:1234', @transport.connections.first.connection.url end should "perform the request" do @transport.connections.first.connection.expects(:http).returns(stub_everything) @transport.perform_request 'GET', '/' end should "set body for GET request" do @transport.connections.first.connection.expects(:put_data=).with('{"foo":"bar"}') @transport.connections.first.connection.expects(:http).with(:GET).returns(stub_everything) @transport.perform_request 'GET', '/', {}, '{"foo":"bar"}' end should "perform request with headers" do @transport.connections.first.connection.expects(:put_data=).with('{"foo":"bar"}') @transport.connections.first.connection.expects(:http).with(:POST).returns(stub_everything) @transport.connections.first.connection.expects(:headers=).with({"Content-Type" => "application/x-ndjson"}) @transport.perform_request 'POST', '/', {}, {:foo => 'bar'}, {"Content-Type" => "application/x-ndjson"} end should "set body for PUT request" do @transport.connections.first.connection.expects(:put_data=) @transport.connections.first.connection.expects(:http).with(:PUT).returns(stub_everything) @transport.perform_request 'PUT', '/', {}, {:foo => 'bar'} end should "serialize the request body" do @transport.connections.first.connection.expects(:http).with(:POST).returns(stub_everything) @transport.serializer.expects(:dump) @transport.perform_request 'POST', '/', {}, {:foo => 'bar'} end should "not serialize a String request body" do @transport.connections.first.connection.expects(:http).with(:POST).returns(stub_everything) @transport.serializer.expects(:dump).never @transport.perform_request 'POST', '/', {}, '{"foo":"bar"}' end should "set application/json response header" do @transport.connections.first.connection.expects(:http).with(:GET).returns(stub_everything) @transport.connections.first.connection.expects(:body_str).returns('{"foo":"bar"}') @transport.connections.first.connection.expects(:header_str).returns('HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\nContent-Length: 311\r\n\r\n') response = @transport.perform_request 'GET', '/' assert_equal 'application/json', response.headers['content-type'] end should "handle HTTP methods" do @transport.connections.first.connection.expects(:http).with(:HEAD).returns(stub_everything) @transport.connections.first.connection.expects(:http).with(:GET).returns(stub_everything) @transport.connections.first.connection.expects(:http).with(:PUT).returns(stub_everything) @transport.connections.first.connection.expects(:http).with(:POST).returns(stub_everything) @transport.connections.first.connection.expects(:http).with(:DELETE).returns(stub_everything) %w| HEAD GET PUT POST DELETE |.each { |method| @transport.perform_request method, '/' } assert_raise(ArgumentError) { @transport.perform_request 'FOOBAR', '/' } end should "properly pass the Content-Type header option" do transport = Curb.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :transport_options => { :headers => { 'Content-Type' => 'foo/bar' } } } assert_equal "foo/bar", transport.connections.first.connection.headers["Content-Type"] end should "allow to set options for Curb" do transport = Curb.new :hosts => [ { :host => 'foobar', :port => 1234 } ] do |curl| curl.headers["User-Agent"] = "myapp-0.0" end assert_equal "myapp-0.0", transport.connections.first.connection.headers["User-Agent"] end should "set the credentials if passed" do transport = Curb.new :hosts => [ { :host => 'foobar', :port => 1234, :user => 'foo', :password => 'bar' } ] assert_equal 'foo', transport.connections.first.connection.username assert_equal 'bar', transport.connections.first.connection.password end should "use global http configuration" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :http => { :scheme => 'https', :user => 'U', :password => 'P' } } assert_equal 'https://U:P@foobar:1234/', transport.connections.first.full_url('') end end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/transport_faraday_test.rb000066400000000000000000000230041361161326000312260ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::Transport::HTTP::FaradayTest < Test::Unit::TestCase include Elasticsearch::Transport::Transport::HTTP context "Faraday transport" do setup do @transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ] end should "implement host_unreachable_exceptions" do assert_instance_of Array, @transport.host_unreachable_exceptions end should "implement __build_connections" do assert_equal 1, @transport.hosts.size assert_equal 1, @transport.connections.size assert_instance_of ::Faraday::Connection, @transport.connections.first.connection assert_equal 'http://foobar:1234/', @transport.connections.first.connection.url_prefix.to_s end should "perform the request" do @transport.connections.first.connection.expects(:run_request).returns(stub_everything) @transport.perform_request 'GET', '/' end should "return a Response" do @transport.connections.first.connection.expects(:run_request).returns(stub_everything) response = @transport.perform_request 'GET', '/' assert_instance_of Elasticsearch::Transport::Transport::Response, response end should "properly prepare the request" do @transport.connections.first.connection.expects(:run_request).with do |method, url, body, headers| assert_equal :post, method assert_equal '{"foo":"bar"}', body assert_nil headers['Accept'] true end.returns(stub_everything) @transport.perform_request 'POST', '/', {}, {:foo => 'bar'} end should "properly prepare the request with custom headers" do @transport.connections.first.connection.expects(:run_request).with do |method, url, body, headers| assert_equal :post, method assert_equal '{"foo":"bar"}', body assert_nil headers['Accept'] assert_equal "application/x-ndjson", headers['Content-Type'] true end.returns(stub_everything) @transport.perform_request 'POST', '/', {}, {:foo => 'bar'}, {"Content-Type" => "application/x-ndjson"} end should "properly pass the Content-Type header option" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :transport_options => { :headers => { 'Content-Type' => 'foo/bar' } } } transport.connections.first.connection.expects(:run_request).with do |method, url, body, headers| assert_equal 'foo/bar', headers['Content-Type'] true end.returns(stub_everything) transport.perform_request 'GET', '/' end should "serialize the request body" do @transport.connections.first.connection.expects(:run_request).returns(stub_everything) @transport.serializer.expects(:dump) @transport.perform_request 'POST', '/', {}, {:foo => 'bar'} end should "not serialize a String request body" do @transport.connections.first.connection.expects(:run_request).returns(stub_everything) @transport.serializer.expects(:dump).never @transport.perform_request 'POST', '/', {}, '{"foo":"bar"}' end should "pass the selector_class options to collection" do @transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :selector_class => Elasticsearch::Transport::Transport::Connections::Selector::Random } assert_instance_of Elasticsearch::Transport::Transport::Connections::Selector::Random, @transport.connections.selector end should "pass the selector option to collection" do @transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :selector => Elasticsearch::Transport::Transport::Connections::Selector::Random.new } assert_instance_of Elasticsearch::Transport::Transport::Connections::Selector::Random, @transport.connections.selector end should "pass a configuration block to the Faraday constructor" do config_block = lambda do |f| f.response :logger f.path_prefix = '/moo' end transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], &config_block handlers = transport.connections.first.connection.builder.handlers assert_equal 1, handlers.size assert handlers.include?(::Faraday::Response::Logger), "#{handlers.inspect} does not include <::Faraday::Adapter::Logger>" assert_equal '/moo', transport.connections.first.connection.path_prefix assert_equal 'http://foobar:1234/moo', transport.connections.first.connection.url_prefix.to_s end should "pass transport_options to the Faraday constructor" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :transport_options => { :request => { :open_timeout => 1 }, :headers => { :foo_bar => 'bar' }, :ssl => { :verify => false } } } assert_equal 1, transport.connections.first.connection.options.open_timeout assert_equal 'bar', transport.connections.first.connection.headers['Foo-Bar'] assert_equal false, transport.connections.first.connection.ssl.verify? end should "merge in parameters defined in the Faraday connection parameters" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :transport_options => { :params => { :format => 'yaml' } } } # transport.logger = Logger.new(STDERR) transport.connections.first.connection.expects(:run_request). with do |method, url, params, body| assert_match /\?format=yaml/, url true end. returns(stub_everything) transport.perform_request 'GET', '' end should "not overwrite request parameters with the Faraday connection parameters" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :transport_options => { :params => { :format => 'yaml' } } } # transport.logger = Logger.new(STDERR) transport.connections.first.connection.expects(:run_request). with do |method, url, params, body| assert_match /\?format=json/, url true end. returns(stub_everything) transport.perform_request 'GET', '', { :format => 'json' } end should "set the credentials if passed" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234, :user => 'foo', :password => 'bar' } ] assert_equal 'Basic Zm9vOmJhcg==', transport.connections.first.connection.headers['Authorization'] end should "set the credentials if they exist in options" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :user => 'foo', :password => 'bar' } assert_equal 'Basic Zm9vOmJhcg==', transport.connections.first.connection.headers['Authorization'] end should "override options credentials if passed explicitly" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234, :user => 'foo', :password => 'bar' }, { :host => 'foobar2', :port => 1234 } ], :options => { :user => 'foo2', :password => 'bar2' } assert_equal 'Basic Zm9vOmJhcg==', transport.connections.first.connection.headers['Authorization'] assert_equal 'Basic Zm9vMjpiYXIy', transport.connections[1].connection.headers['Authorization'] end should "set connection scheme to https if passed" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234, :scheme => 'https' } ] assert_instance_of ::Faraday::Connection, transport.connections.first.connection assert_equal 'https://foobar:1234/', transport.connections.first.connection.url_prefix.to_s end should "set connection scheme to https if it exist in options" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234} ], :options => { :scheme => 'https' } assert_instance_of ::Faraday::Connection, transport.connections.first.connection assert_equal 'https://foobar:1234/', transport.connections.first.connection.url_prefix.to_s end should "override options scheme if passed explicitly" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234, :scheme => 'http'} ], :options => { :scheme => 'https' } assert_instance_of ::Faraday::Connection, transport.connections.first.connection assert_equal 'http://foobar:1234/', transport.connections.first.connection.url_prefix.to_s end should "use global http configuration" do transport = Faraday.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => { :http => { :scheme => 'https', :user => 'U', :password => 'P' } } assert_equal 'https://U:P@foobar:1234/', transport.connections.first.full_url('') end end end elasticsearch-ruby-6.8.1/elasticsearch-transport/test/unit/transport_manticore_test.rb000066400000000000000000000135731361161326000316120ustar00rootroot00000000000000require 'test_helper' unless JRUBY version = ( defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'Ruby' ) + ' ' + RUBY_VERSION puts "SKIP: '#{File.basename(__FILE__)}' only supported on JRuby (you're running #{version})" else require 'elasticsearch/transport/transport/http/manticore' require 'manticore' class Elasticsearch::Transport::Transport::HTTP::ManticoreTest < Test::Unit::TestCase include Elasticsearch::Transport::Transport::HTTP context "Manticore transport" do setup do @transport = Manticore.new :hosts => [ { :host => '127.0.0.1', :port => 8080 } ] end should "implement host_unreachable_exceptions" do assert_instance_of Array, @transport.host_unreachable_exceptions end should "implement __build_connections" do assert_equal 1, @transport.hosts.size assert_equal 1, @transport.connections.size assert_instance_of ::Manticore::Client, @transport.connections.first.connection end should "not close connections in __close_connections" do assert_equal 1, @transport.connections.size @transport.__close_connections assert_equal 1, @transport.connections.size end should "perform the request" do @transport.connections.first.connection.expects(:get).returns(stub_everything) @transport.perform_request 'GET', '/' end should "set body for GET request" do @transport.connections.first.connection.expects(:get). with('http://127.0.0.1:8080//', {:body => '{"foo":"bar"}'}).returns(stub_everything) @transport.perform_request 'GET', '/', {}, '{"foo":"bar"}' end should "set body for PUT request" do @transport.connections.first.connection.expects(:put). with('http://127.0.0.1:8080//', {:body => '{"foo":"bar"}'}).returns(stub_everything) @transport.perform_request 'PUT', '/', {}, {:foo => 'bar'} end should "serialize the request body" do @transport.connections.first.connection.expects(:post). with('http://127.0.0.1:8080//', {:body => '{"foo":"bar"}'}).returns(stub_everything) @transport.perform_request 'POST', '/', {}, {'foo' => 'bar'} end should "set custom headers for PUT request" do @transport.connections.first.connection.expects(:put). with('http://127.0.0.1:8080//', {:body => '{"foo":"bar"}', :headers => {"Content-Type" => "application/x-ndjson"}}) .returns(stub_everything) @transport.perform_request 'PUT', '/', {}, '{"foo":"bar"}', {"Content-Type" => "application/x-ndjson"} end should "not serialize a String request body" do @transport.connections.first.connection.expects(:post). with('http://127.0.0.1:8080//', {:body => '{"foo":"bar"}'}).returns(stub_everything) @transport.serializer.expects(:dump).never @transport.perform_request 'POST', '/', {}, '{"foo":"bar"}' end should "set application/json header" do options = { :headers => { "content-type" => "application/json"} } transport = Manticore.new :hosts => [ { :host => 'localhost', :port => 8080 } ], :options => options transport.connections.first.connection.stub("http://localhost:8080//", :body => "\"\"", :headers => {"content-type" => "application/json"}, :code => 200 ) response = transport.perform_request 'GET', '/', {} assert_equal response.status, 200 end should "set headers from 'transport_options'" do options = { :transport_options => { :headers => { "Content-Type" => "foo/bar"} } } transport = Manticore.new :hosts => [ { :host => 'localhost', :port => 8080 } ], :options => options assert_equal('foo/bar', transport.connections.first.connection.instance_variable_get(:@options)[:headers]['Content-Type']) # TODO: Needs to check @request_options end should "handle HTTP methods" do @transport.connections.first.connection.expects(:delete).with('http://127.0.0.1:8080//', {}).returns(stub_everything) @transport.connections.first.connection.expects(:head).with('http://127.0.0.1:8080//', {}).returns(stub_everything) @transport.connections.first.connection.expects(:get).with('http://127.0.0.1:8080//', {}).returns(stub_everything) @transport.connections.first.connection.expects(:put).with('http://127.0.0.1:8080//', {}).returns(stub_everything) @transport.connections.first.connection.expects(:post).with('http://127.0.0.1:8080//', {}).returns(stub_everything) %w| HEAD GET PUT POST DELETE |.each { |method| @transport.perform_request method, '/' } assert_raise(ArgumentError) { @transport.perform_request 'FOOBAR', '/' } end should "allow to set options for Manticore" do options = { :headers => {"User-Agent" => "myapp-0.0" }} transport = Manticore.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => options transport.connections.first.connection.expects(:get). with('http://foobar:1234//', options).returns(stub_everything) transport.perform_request 'GET', '/', {} end should "allow to set ssl options for Manticore" do options = { :ssl => { :truststore => "test.jks", :truststore_password => "test", :verify => false } } ::Manticore::Client.expects(:new).with(options) transport = Manticore.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => options end should "pass :transport_options to Manticore::Client" do options = { :transport_options => { :potatoes => 1 } } ::Manticore::Client.expects(:new).with(:potatoes => 1, :ssl => {}) transport = Manticore.new :hosts => [ { :host => 'foobar', :port => 1234 } ], :options => options end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/000077500000000000000000000000001361161326000212345ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/.gitignore000066400000000000000000000002321361161326000232210ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp elasticsearch-ruby-6.8.1/elasticsearch-xpack/Gemfile000066400000000000000000000017321361161326000225320ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-xpack.gemspec gemspec group :development do gem 'rspec' gem 'pry-nav' end if File.exist? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-transport/elasticsearch-transport.gemspec", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch/", __FILE__) end if File.exist? File.expand_path("../../elasticsearch/elasticsearch-extensions.gemspec", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions/", __FILE__) endelasticsearch-ruby-6.8.1/elasticsearch-xpack/LICENSE.txt000066400000000000000000000020701361161326000230560ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2016 Karel Minarik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. elasticsearch-ruby-6.8.1/elasticsearch-xpack/README.md000066400000000000000000000044071361161326000225200ustar00rootroot00000000000000# Elasticsearch::XPack A Ruby integration for the [X-Pack extension](https://www.elastic.co/guide/en/x-pack/current/xpack-introduction.html) for Elasticsearch. ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch-xpack To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch-xpack', git: 'https://github.com/elastic/elasticsearch-ruby.git' ## Usage If you use the official [Ruby client for Elasticsearch](https://github.com/elastic/elasticsearch-ruby), require the library in your code, and all the methods will be automatically available in the `xpack` namespace: ```ruby require 'elasticsearch' require 'elasticsearch/xpack' client = Elasticsearch::Client.new url: 'http://elastic:changeme@localhost:9200' client.xpack.info # => {"build"=> ..., "features"=> ...} ``` The integration is designed as a standalone `Elasticsearch::XPack::API` module, so it's easy to mix it into a different client, and the methods will be available in the top namespace. For documentation, look into the RDoc annotations in the source files, which contain links to the official [X-Pack for the Elastic Stack](https://www.elastic.co/guide/en/x-pack/current/index.html) documentation. For examples, look into the [`examples`](examples) folder in this repository. You can use the provided `test:elasticsearch` Rake task to launch a [Docker-based](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html) Elasticsearch node with the full X-Pack license preinstalled. ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2016 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch-xpack/Rakefile000066400000000000000000000033351361161326000227050ustar00rootroot00000000000000require 'bundler/gem_tasks' require 'rake/testtask' require 'rspec/core/rake_task' task :default do exec "rake --tasks" end Rake::TestTask.new('test:unit') do |test| test.libs << 'test' test.test_files = FileList['test/unit/**/*_test.rb'] test.verbose = false test.warning = false end namespace :test do RSpec::Core::RakeTask.new(:spec) desc "Run rest api yaml tests" Rake::TestTask.new(:rest_api) do |test| test.deps = [ :spec ] end desc "Run integration tests" task :integration do sh <<-COMMAND bundle exec ruby -I ../elasticsearch/lib:../elasticsearch-transport/lib:../elasticsearch-api/lib:./lib:./test test/integration/yaml_test_runner.rb COMMAND end desc "Run Elasticsearch with X-Pack installed (Docker)" task :elasticsearch do sh <<-COMMAND.gsub(/^\s*/, '').gsub(/\s{1,}/, ' ') docker run \ --name elasticsearch-xpack \ --env "discovery.type=single-node" \ --env "cluster.name=elasticsearch-api-test" \ --env "node.name=es-01" \ --env "http.port=9200" \ --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 "bootstrap.memory_lock=true" \ --env "ELASTIC_PASSWORD=MagicWord" \ --ulimit nofile=65536:65536 \ --ulimit memlock=-1:-1 \ --publish 9260:9200 \ --volume $(pwd)/tmp/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml \ --memory 4g \ --rm \ docker.elastic.co/elasticsearch/elasticsearch:7.0.0-alpha1-SNAPSHOT COMMAND end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/elasticsearch-xpack.gemspec000066400000000000000000000032461361161326000265240ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/xpack/version' Gem::Specification.new do |spec| spec.name = "elasticsearch-xpack" spec.version = Elasticsearch::XPack::VERSION spec.authors = ["Karel Minarik"] spec.email = ["karel@elastic.co"] spec.summary = "Ruby integrations for the X-Pack extensions for Elasticsearch" spec.description = "Ruby integrations for the X-Pack extensions for Elasticsearch" spec.homepage = "https://github.com/elastic/elasticsearch-ruby/tree/master/elasticsearch-xpack" spec.license = "Apache-2.0" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler" spec.add_development_dependency "rake", "~> 11.1" spec.add_development_dependency "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) spec.add_dependency "elasticsearch-api", '~> 6' spec.add_development_dependency "elasticsearch", '~> 6' spec.add_development_dependency "elasticsearch-transport", '~> 6' spec.add_development_dependency "elasticsearch-extensions" spec.add_development_dependency "activesupport" spec.add_development_dependency "ansi" spec.add_development_dependency "minitest" spec.add_development_dependency "minitest-reporters" spec.add_development_dependency "shoulda-context" spec.add_development_dependency "mocha" spec.add_development_dependency "yard" spec.add_development_dependency "pry" end elasticsearch-ruby-6.8.1/elasticsearch-xpack/examples/000077500000000000000000000000001361161326000230525ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/examples/watcher/000077500000000000000000000000001361161326000245075ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/examples/watcher/error_500.rb000066400000000000000000000126061361161326000265560ustar00rootroot00000000000000# An example of a complex configuration for Elasticsearch Watcher alerting and notification system. # # Execute this file from the root of the repository: # # ALERT_EMAIL=email@example.com bundle exec ruby -I lib ./examples/watcher/error_500.rb # # The watch searches for `500` errors in a specific index on a periodic basis, and performs three # actions when at least 3 errors have been received in the last 5 minutes: # # 1. indexes the error documents and aggregations returned from search, # 2. sends a notification via e-mail, and # 3. sends the data to a webhook. # # If you want to test sending the e-mail, you have to configure Watcher: # # # NOTE: If you want to use Gmail and you have 2-factor authentication enabled, # generate an "App password", and use it in the `password` field. # # You can run a simple Sinatra application to test the webhook action with this script: # # $ ruby -r sinatra -r json -e 'post("/") { json = JSON.parse(request.body.read); puts %Q~Received [#{json["watch_id"]}] with payload: #{json["payload"]}~ }' # require 'elasticsearch' require 'elasticsearch/xpack' password = ENV.fetch('ELASTIC_PASSWORD', 'changeme') client = Elasticsearch::Client.new url: "http://elastic:#{password}@localhost:9260", log: true client.transport.logger.formatter = proc do |severity, datetime, progname, msg| "\e[2m#{msg}\e[0m\n" end # Print information about the Watcher plugin # cluster_info = client.info xpack_info = client.xpack.info puts "Elasticsearch #{cluster_info['version']['number']} | X-Pack build [#{xpack_info['build']['hash']}]" # Delete the Watcher and test indices # ['test_errors', 'alerts', '.watcher-history-*'].each do |index| client.indices.delete index: index, ignore: 404 end # Register a new watch # client.xpack.watcher.put_watch id: 'error_500', body: { # Label the watch # metadata: { tags: ['errors'] }, # Run the watch every 10 seconds # trigger: { schedule: { interval: '10s' } }, # Search for at least 3 documents matching the condition # condition: { compare: { 'ctx.payload.hits.total' => { gt: 3 } } }, # Throttle the watch execution for 30 seconds # throttle_period: '30s', # The search request to execute # input: { search: { request: { indices: ['test_errors'], body: { query: { bool: { must: [ { match: { status: 500 } } , { range: { timestamp: { from: '{{ctx.trigger.scheduled_time}}||-5m', to: '{{ctx.trigger.triggered_time}}' } } } ] } }, # Return hosts with most errors # aggregations: { hosts: { terms: { field: 'host' } } } }}} }, # The actions to perform # actions: { send_email: { transform: { # Transform the data for the template # script: { source: "[ 'total': ctx.payload.hits.total, 'hosts': ctx.payload.aggregations.hosts.buckets.collect(bucket -> [ 'host': bucket.key, 'errors': bucket.doc_count ]), 'errors': ctx.payload.hits.hits.collect(d -> d._source) ]" } }, email: { to: ENV.fetch('ALERT_EMAIL', 'alert@example.com'), subject: '[ALERT] {{ctx.watch_id}}', body: <<-BODY.gsub(/^ {28}/, ''), Received {{ctx.payload.total}} errors in the last 5 minutes. Hosts: {{#ctx.payload.hosts}}- {{host}} ({{errors}} errors)\n{{/ctx.payload.hosts}} A file with complete data is attached to this message.\n BODY attachments: { 'data.yml' => { data: { format: 'yaml' } } } } }, index_payload: { # Transform the data to be stored # transform: { script: { lang: 'painless', source: "[ 'watch_id': ctx.watch_id, 'payload': ctx.payload ]" } }, index: { index: 'alerts', doc_type: 'alert' } }, ping_webhook: { webhook: { method: 'post', url: 'http://localhost:4567', body: %q|{"watch_id" : "{{ctx.watch_id}}", "payload" : "{{ctx.payload}}"}| } } } } # Create the index with example documents # client.indices.create index: 'test_errors', body: { mappings: { d: { properties: { host: { type: 'keyword' } } } } } # Index documents to trigger the watch # 10.times do client.index index: 'test_errors', type: 'd', body: { timestamp: Time.now.utc.iso8601, status: "#{rand(4..5)}00", host: "10.0.0.#{rand(1..3)}" } end # Wait a bit... # print "Waiting 30 seconds..." $i=0; while $i < 30 do sleep(1); print('.'); $i+=1 end; puts "\n" # Display information about watch execution # client.search(index: '.watcher-history-*', q: 'watch_id:error_500', sort: 'trigger_event.triggered_time:asc')['hits']['hits'].each do |r| print "[#{r['_source']['watch_id']}] #{r['_source']['state'].upcase} at #{r['_source']['result']['execution_time']}" if r['_source']['state'] == 'executed' print " > Actions: " print r['_source']['result']['actions'].map { |a| "[#{a['id']}] #{a['status']}#{a['error'] ? ': '+a['error']['type'] : ''}" }.join(', ') end print "\n" end # Delete the watch # client.xpack.watcher.delete_watch id: 'error_500' elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/000077500000000000000000000000001361161326000220025ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/000077500000000000000000000000001361161326000246145ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack.rb000066400000000000000000000021501361161326000262450ustar00rootroot00000000000000require "elasticsearch/api" require "elasticsearch/xpack/version" Dir[ File.expand_path('../xpack/api/actions/**/*.rb', __FILE__) ].each { |f| require f } Dir[ File.expand_path('../xpack/api/namespace/**/*.rb', __FILE__) ].each { |f| require f } module Elasticsearch module XPack module API def self.included(base) Elasticsearch::XPack::API.constants.reject {|c| c == :Client }.each do |m| base.__send__ :include, Elasticsearch::XPack::API.const_get(m) end end class Client include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base include Elasticsearch::XPack::API end end end end Elasticsearch::API::COMMON_PARAMS.push :job_id, :datafeed_id, :filter_id, :snapshot_id, :category_id module Elasticsearch module Transport class Client def xpack @xpack_client ||= Elasticsearch::XPack::API::Client.new(self) end def security @security ||= xpack.security end def ml @ml ||= xpack.ml end end end end if defined?(Elasticsearch::Transport::Client) elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/000077500000000000000000000000001361161326000257225ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/000077500000000000000000000000001361161326000264735ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/000077500000000000000000000000001361161326000301335ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/graph/000077500000000000000000000000001361161326000312345ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/graph/explore.rb000066400000000000000000000031261361161326000332410ustar00rootroot00000000000000module Elasticsearch module XPack module API module Graph module Actions # Get structured information about the vertices and connections in a dataset # # @option arguments [List] :index A comma-separated list of index names to search; # use `_all` or empty string to perform the operation on all indices # @option arguments [List] :type A comma-separated list of document types to search; # leave empty to perform the operation on all types # @option arguments [Hash] :body The Graph Query DSL definition # @option arguments [String] :routing Specific routing value # @option arguments [Time] :timeout Explicit operation timeout # # @see https://www.elastic.co/guide/en/graph/current/explore.html # def explore(arguments={}) valid_params = [ :routing, :timeout ] arguments = arguments.clone index = arguments.delete(:index) type = arguments.delete(:type) method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify Elasticsearch::API::Utils.__listify(index), Elasticsearch::API::Utils.__listify(type), '_xpack/_graph/_explore' params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/info.rb000066400000000000000000000017701361161326000314200ustar00rootroot00000000000000module Elasticsearch module XPack module API module Actions # Retrieve information about xpack, including build number/timestamp and license status # # @option arguments [Boolean] :human Presents additional info for humans # (feature descriptions and X-Pack tagline) # @option arguments [List] :categories Comma-separated list of info categories. # (Options: build, license, features) # # @see https://www.elastic.co/guide/en/x-pack/current/info-api.html # def info(arguments={}) valid_params = [ :human, :categories ] method = Elasticsearch::API::HTTP_GET path = "_xpack" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/license/000077500000000000000000000000001361161326000315555ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/license/delete.rb000066400000000000000000000010201361161326000333350ustar00rootroot00000000000000module Elasticsearch module XPack module API module License module Actions # Delete a license # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def delete(arguments={}) method = Elasticsearch::API::HTTP_DELETE path = "_xpack/license" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/license/get.rb000066400000000000000000000013371361161326000326650ustar00rootroot00000000000000module Elasticsearch module XPack module API module License module Actions # Get a license # # @option arguments [Boolean] :local Return local information (default: false) # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def get(arguments={}) valid_params = [ :local ] method = Elasticsearch::API::HTTP_GET path = "_xpack/license" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_basic_status.rb000066400000000000000000000010611361161326000353440ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/licensemodule Elasticsearch module XPack module API module License module Actions # TODO: Description # # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def get_basic_status(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/license/basic_status" params = {} body = nil perform_request(method, path, params, body).body end end end end end end get_trial_status.rb000066400000000000000000000010611361161326000353760ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/licensemodule Elasticsearch module XPack module API module License module Actions # TODO: Description # # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def get_trial_status(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/license/trial_status" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/license/post.rb000066400000000000000000000016241361161326000330720ustar00rootroot00000000000000module Elasticsearch module XPack module API module License module Actions # Install a license # # @option arguments [Hash] :body Licenses to be installed # @option arguments [Boolean] :acknowledge Whether the user has acknowledged acknowledge messages # (default: false) # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def post(arguments={}) valid_params = [ :acknowledge ] method = Elasticsearch::API::HTTP_PUT path = "_xpack/license" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end post_start_basic.rb000066400000000000000000000014651361161326000353740ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/licensemodule Elasticsearch module XPack module API module License module Actions # TODO: Description # # @option arguments [Boolean] :acknowledge whether the user has acknowledged acknowledge messages (default: false) # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def post_start_basic(arguments={}) valid_params = [ :acknowledge ] method = Elasticsearch::API::HTTP_POST path = "_xpack/license/start_basic" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end post_start_trial.rb000066400000000000000000000016601361161326000354230ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/licensemodule Elasticsearch module XPack module API module License module Actions # TODO: Description # # @option arguments [String] :type The type of trial license to generate (default: "trial") # @option arguments [Boolean] :acknowledge whether the user has acknowledged acknowledge messages (default: false) # # @see https://www.elastic.co/guide/en/x-pack/current/license-management.html # def post_start_trial(arguments={}) valid_params = [ :type, :acknowledge ] method = Elasticsearch::API::HTTP_POST path = "_xpack/license/start_trial" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learning/000077500000000000000000000000001361161326000334165ustar00rootroot00000000000000close_job.rb000066400000000000000000000025351361161326000356300ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :job_id The name of the job to close (*Required*) # @option arguments [Boolean] :allow_no_jobs Whether to ignore if a wildcard expression matches no jobs. (This includes `_all` string or when no jobs have been specified) # @option arguments [Boolean] :force True if the job should be forcefully closed # @option arguments [Time] :timeout Controls the time to wait until a job has closed. Default to 30 minutes # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-close-job.html # def close_job(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :allow_no_jobs, :force, :timeout ] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_close" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end delete_calendar.rb000066400000000000000000000013321361161326000367560ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to delete (*Required*) # # @see [TODO] # def delete_calendar(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/calendars/#{arguments[:calendar_id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end delete_calendar_event.rb000066400000000000000000000017351361161326000401660ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to modify (*Required*) # @option arguments [String] :event_id The ID of the event to remove from the calendar (*Required*) # # @see [TODO] # def delete_calendar_event(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] raise ArgumentError, "Required argument 'event_id' missing" unless arguments[:event_id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/calendars/#{arguments[:calendar_id]}/events/#{URI.escape(arguments[:event_id])}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end delete_calendar_job.rb000066400000000000000000000017031361161326000376120ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to modify (*Required*) # @option arguments [String] :job_id The ID of the job to remove from the calendar (*Required*) # # @see [TODO] # def delete_calendar_job(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/calendars/#{arguments[:calendar_id]}/jobs/#{arguments[:job_id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end delete_datafeed.rb000066400000000000000000000020141361161326000367400ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :datafeed_id The ID of the datafeed to delete (*Required*) # @option arguments [Boolean] :force True if the datafeed should be forcefully deleted # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-delete-datafeed.html # def delete_datafeed(arguments={}) raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id] valid_params = [ :force ] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end delete_expired_data.rb000066400000000000000000000006501361161326000376400ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions def delete_expired_data(arguments={}) method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/_delete_expired_data" params = {} body = nil perform_request(method, path, params, body).body end end end end end end delete_filter.rb000066400000000000000000000011761361161326000365000ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # @option arguments [String] :filter_id The ID of the filter to delete (*Required*) # def delete_filter(arguments={}) raise ArgumentError, "Required argument 'filter_id' missing" unless arguments[:filter_id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/filters/#{arguments[:filter_id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end delete_forecast.rb000066400000000000000000000024321361161326000370150ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # @option arguments [String] :job_id The ID of the job from which to delete forecasts (*Required*) # @option arguments [String] :forecast_id The ID of the forecast to delete, can be comma delimited list. # Leaving blank implies `_all` # @option arguments [Boolean] :allow_no_forecasts Whether to ignore if `_all` matches no forecasts # @option arguments [Time] :timeout Controls the time to wait until the forecast(s) are deleted. # Default to 30 seconds. # def delete_forecast(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_forecast/#{arguments[:forecast_id]}" valid_params = [ :forecast_id, :allow_no_forecasts, :timeout ] params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end delete_job.rb000066400000000000000000000020031361161326000357530ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Delete an existing anomaly detection job # # @option arguments [String] :job_id The ID of the job to delete (*Required*) # @option arguments [Boolean] :force True if the job should be forcefully deleted # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-delete-job.html # def delete_job(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :force ] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end delete_model_snapshot.rb000066400000000000000000000020451361161326000402260ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Delete an existing model snapshot # # @option arguments [String] :job_id The ID of the job to fetch (*Required*) # @option arguments [String] :snapshot_id The ID of the snapshot to delete (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-delete-snapshot.html # def delete_model_snapshot(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] raise ArgumentError, "Required argument 'snapshot_id' missing" unless arguments[:snapshot_id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/model_snapshots/#{arguments[:snapshot_id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end find_file_structure.rb000066400000000000000000000016401361161326000377240ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Finds the structure of a text file. The text file must contain data that is suitable to be # ingested into Elasticsearch. # # @option arguments [Hash] :body The contents of the file to be analyzed (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-file-structure.html # def find_file_structure(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/find_file_structure" body = Elasticsearch::API::Utils.__bulkify(arguments.delete(:body)) perform_request(method, path, arguments, body).body end end end end end end flush_job.rb000066400000000000000000000035431361161326000356440ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Force any buffered data to be processed by the job # # @option arguments [String] :job_id The name of the job to flush (*Required*) # @option arguments [Hash] :body Flush parameters # @option arguments [Boolean] :calc_interim Calculates interim results for the most recent bucket or all buckets within the latency period # @option arguments [String] :start When used in conjunction with calc_interim, specifies the range of buckets on which to calculate interim results # @option arguments [String] :end When used in conjunction with calc_interim, specifies the range of buckets on which to calculate interim results # @option arguments [String] :advance_time Setting this tells the Engine API that no data prior to advance_time is expected # @option arguments [String] :skip_time Skips time to the given value without generating results or updating the model for the skipped interval # # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-flush-job.html # def flush_job(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :calc_interim, :start, :end, :advance_time, :skip_time ] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_flush" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end forecast.rb000066400000000000000000000023011361161326000354660ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Predict the future behavior of a time series # # @option arguments [String] :job_id The ID of the job to forecast for (*Required*) # @option arguments [Time] :duration The duration of the forecast # @option arguments [Time] :expires_in The time interval after which the forecast expires. Expired forecasts will be deleted at the first opportunity. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-forecast.html # def forecast(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :duration, :expires_in ] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_forecast" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_buckets.rb000066400000000000000000000042551361161326000361710ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve job results for one or more buckets # # @option arguments [String] :job_id ID of the job to get bucket results from (*Required*) # @option arguments [String] :timestamp The timestamp of the desired single bucket result # @option arguments [Hash] :body Bucket selection details if not provided in URI # @option arguments [Boolean] :expand Include anomaly records # @option arguments [Boolean] :exclude_interim Exclude interim results # @option arguments [Int] :from skips a number of buckets # @option arguments [Int] :size specifies a max number of buckets to get # @option arguments [String] :start Start time filter for buckets # @option arguments [String] :end End time filter for buckets # @option arguments [Double] :anomaly_score Filter for the most anomalous buckets # @option arguments [String] :sort Sort buckets by a particular field # @option arguments [Boolean] :desc Set the sort direction # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-bucket.html # def get_buckets(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :timestamp, :expand, :exclude_interim, :from, :size, :start, :end, :anomaly_score, :sort, :desc ] arguments = arguments.clone timestamp = arguments.delete(:timestamp) method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/ml/anomaly_detectors", arguments[:job_id], "results/buckets", timestamp params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_calendar_events.rb000066400000000000000000000027261361161326000376670ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar containing the events (*Required*) # @option arguments [String] :job_id Get events for the job. When this option is used calendar_id must be '_all' # @option arguments [String] :start Get events after this time # @option arguments [Date] :end Get events before this time # @option arguments [Int] :from Skips a number of events # @option arguments [Int] :size Specifies a max number of events to get # # @see [TODO] # def get_calendar_events(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] valid_params = [ :calendar_id, :job_id, :start, :end, :from, :size ] arguments = arguments.clone calendar_id = arguments.delete(:calendar_id) method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/calendars/#{calendar_id}/events" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_calendars.rb000066400000000000000000000020001361161326000364470ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to fetch # @option arguments [Int] :from skips a number of calendars # @option arguments [Int] :size specifies a max number of calendars to get # # @see [TODO] # def get_calendars(arguments={}) valid_params = [ :calendar_id, :from, :size ] arguments = arguments.clone calendar_id = arguments.delete(:calendar_id) method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/calendars/#{calendar_id}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_categories.rb000066400000000000000000000025751361161326000366610ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve job results for one or more categories # # @option arguments [String] :job_id The name of the job (*Required*) # @option arguments [Long] :category_id The identifier of the category definition of interest # @option arguments [Hash] :body Category selection details if not provided in URI # @option arguments [Int] :from skips a number of categories # @option arguments [Int] :size specifies a max number of categories to get # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-category.html # def get_categories(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :from, :size ] method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/ml/anomaly_detectors", arguments[:job_id], "results/categories", arguments[:category_id] params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_datafeed_stats.rb000066400000000000000000000021231361161326000374740ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve usage information for datafeeds # # @option arguments [String] :datafeed_id The ID of the datafeeds stats to fetch # @option arguments [Boolean] :allow_no_datafeeds Whether to ignore if a wildcard expression matches no datafeeds. (This includes `_all` string or when no datafeeds have been specified) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-datafeed-stats.html # def get_datafeed_stats(arguments={}) valid_params = [ :allow_no_datafeeds ] method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/ml/datafeeds", arguments[:datafeed_id], "/_stats" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_datafeeds.rb000066400000000000000000000021051361161326000364410ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve configuration information for datafeeds # # @option arguments [String] :datafeed_id The ID of the datafeeds stats to fetch # @option arguments [Boolean] :allow_no_datafeeds Whether to ignore if a wildcard expression matches no datafeeds. (This includes `_all` string or when no datafeeds have been specified) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-datafeed.html # def get_datafeeds(arguments={}) valid_params = [ :allow_no_datafeeds ] method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/ml/datafeeds", arguments[:datafeed_id] params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_filters.rb000066400000000000000000000015231361161326000361740ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # @option arguments [String] :filter_id The ID of the filter to fetch # @option arguments [Int] :from skips a number of filters # @option arguments [Int] :size specifies a max number of filters to get # def get_filters(arguments={}) valid_params = [ :from, :size ] method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/ml/filters", arguments[:filter_id] params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_influencers.rb000066400000000000000000000036051361161326000370440ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve job results for one or more influencers # # @option arguments [String] :job_id [TODO] (*Required*) # @option arguments [Hash] :body Influencer selection criteria # @option arguments [Boolean] :exclude_interim Exclude interim results # @option arguments [Int] :from skips a number of influencers # @option arguments [Int] :size specifies a max number of influencers to get # @option arguments [String] :start start timestamp for the requested influencers # @option arguments [String] :end end timestamp for the requested influencers # @option arguments [Double] :influencer_score influencer score threshold for the requested influencers # @option arguments [String] :sort sort field for the requested influencers # @option arguments [Boolean] :desc whether the results should be sorted in decending order # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-influencer.html # def get_influencers(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :exclude_interim, :from, :size, :start, :end, :influencer_score, :sort, :desc ] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/results/influencers" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_job_stats.rb000066400000000000000000000017401361161326000365150ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :job_id The ID of the jobs stats to fetch # @option arguments [Boolean] :allow_no_jobs Whether to ignore if a wildcard expression matches no jobs. (This includes `_all` string or when no jobs have been specified) # # @see http://www.elastic.co/guide/en/x-pack/current/ml-get-job-stats.html # def get_job_stats(arguments={}) valid_params = [ :allow_no_jobs ] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_stats" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_jobs.rb000066400000000000000000000017631361161326000354670ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve configuration information for jobs # # @option arguments [String] :job_id The ID of the jobs to fetch # @option arguments [Boolean] :allow_no_jobs Whether to ignore if a wildcard expression matches no jobs. (This includes `_all` string or when no jobs have been specified) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-job.html # def get_jobs(arguments={}) valid_params = [ :allow_no_jobs ] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_model_snapshots.rb000066400000000000000000000033651361161326000377340ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve information about model snapshots # # @option arguments [String] :job_id The ID of the job to fetch (*Required*) # @option arguments [String] :snapshot_id The ID of the snapshot to fetch # @option arguments [Hash] :body Model snapshot selection criteria # @option arguments [Integer] :from Skips a number of documents # @option arguments [Integer] :size The default number of documents returned in queries as a string. # @option arguments [Date] :start The filter 'start' query parameter # @option arguments [Date] :end The filter 'end' query parameter # @option arguments [String] :sort Name of the field to sort on # @option arguments [Boolean] :desc True if the results should be sorted in descending order # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-snapshot.html # def get_model_snapshots(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :from, :size, :start, :end, :sort, :desc ] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/model_snapshots/#{arguments[:snapshot_id]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_overall_buckets.rb000066400000000000000000000042401361161326000377070ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve overall bucket results that summarize the bucket results of multiple jobs # # @option arguments [String] :job_id The job IDs for which to calculate overall bucket results (*Required*) # @option arguments [Hash] :body Overall bucket selection details if not provided in URI # @option arguments [Int] :top_n The number of top job bucket scores to be used in the overall_score calculation # @option arguments [String] :bucket_span The span of the overall buckets. Defaults to the longest job bucket_span # @option arguments [Double] :overall_score Returns overall buckets with overall scores higher than this value # @option arguments [Boolean] :exclude_interim If true overall buckets that include interim buckets will be excluded # @option arguments [String] :start Returns overall buckets with timestamps after this time # @option arguments [String] :end Returns overall buckets with timestamps earlier than this time # @option arguments [Boolean] :allow_no_jobs Whether to ignore if a wildcard expression matches no jobs. (This includes `_all` string or when no jobs have been specified) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-overall-buckets.html # def get_overall_buckets(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :top_n, :bucket_span, :overall_score, :exclude_interim, :start, :end, :allow_no_jobs ] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/results/overall_buckets" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_records.rb000066400000000000000000000033401361161326000361640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Retrieve anomaly records for a job # # @option arguments [String] :job_id [TODO] (*Required*) # @option arguments [Hash] :body Record selection criteria # @option arguments [Boolean] :exclude_interim Exclude interim results # @option arguments [Int] :from skips a number of records # @option arguments [Int] :size specifies a max number of records to get # @option arguments [String] :start Start time filter for records # @option arguments [String] :end End time filter for records # @option arguments [Double] :record_score [TODO] # @option arguments [String] :sort Sort records by a particular field # @option arguments [Boolean] :desc Set the sort direction # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-record.html # def get_records(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :exclude_interim, :from, :size, :start, :end, :record_score, :sort, :desc ] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/results/records" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end info.rb000066400000000000000000000007401361161326000346200ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # # @see [TODO] # def info(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/info" params = {} body = nil perform_request(method, path, params, body).body end end end end end end open_job.rb000066400000000000000000000020631361161326000354600ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Open a job to receive and analyze data # # @option arguments [String] :job_id The ID of the job to open (*Required*) # @option arguments [Boolean] :ignore_downtime Controls if gaps in data are treated as anomalous or as a maintenance window after a job re-start # @option arguments [Time] :timeout Controls the time to wait until a job has opened. Default to 30 minutes # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-open-job.html # def open_job(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_open" params = {} body = nil perform_request(method, path, params, body).body end end end end end end post_calendar_events.rb000066400000000000000000000016261361161326000400730ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to modify (*Required*) # @option arguments [Hash] :body A list of events (*Required*) # # @see [TODO] # def post_calendar_events(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/calendars/#{arguments[:calendar_id]}/events" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end post_data.rb000066400000000000000000000026031361161326000356430ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Send data to an anomaly detection job for analysis # # @option arguments [String] :job_id The name of the job receiving the data (*Required*) # @option arguments [Hash] :body The data to process (*Required*) # @option arguments [String] :reset_start Optional parameter to specify the start of the bucket resetting range # @option arguments [String] :reset_end Optional parameter to specify the end of the bucket resetting range # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-post-data.html # def post_data(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :reset_start, :reset_end ] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_data" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end preview_datafeed.rb000066400000000000000000000014641361161326000371670ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Preview a datafeed # # @option arguments [String] :datafeed_id The ID of the datafeed to preview (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-preview-datafeed.html # def preview_datafeed(arguments={}) raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id] method = Elasticsearch::API::HTTP_GET path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}/_preview" params = {} body = nil perform_request(method, path, params, body).body end end end end end end put_calendar.rb000066400000000000000000000014411361161326000363250ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to create (*Required*) # @option arguments [Hash] :body The calendar details # # @see [TODO] # def put_calendar(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] method = Elasticsearch::API::HTTP_PUT path = "_xpack/ml/calendars/#{arguments[:calendar_id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_calendar_job.rb000066400000000000000000000016701361161326000371630ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # TODO: Description # # @option arguments [String] :calendar_id The ID of the calendar to modify (*Required*) # @option arguments [String] :job_id The ID of the job to add to the calendar (*Required*) # # @see [TODO] # def put_calendar_job(arguments={}) raise ArgumentError, "Required argument 'calendar_id' missing" unless arguments[:calendar_id] raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] method = Elasticsearch::API::HTTP_PUT path = "_xpack/ml/calendars/#{arguments[:calendar_id]}/jobs/#{arguments[:job_id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end put_datafeed.rb000066400000000000000000000017321361161326000363140ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Create a new datafeed # # @option arguments [String] :datafeed_id The ID of the datafeed to create (*Required*) # @option arguments [Hash] :body The datafeed config (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-put-datafeed.html # def put_datafeed(arguments={}) raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_PUT path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_filter.rb000066400000000000000000000014541361161326000360450ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # @option arguments [String] :filter_id The ID of the filter to create (*Required*) # @option arguments [Hash] :body The filter details (*Required*) # def put_filter(arguments={}) raise ArgumentError, "Required argument 'filter_id' missing" unless arguments[:filter_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_PUT path = "_xpack/ml/filters/#{arguments[:filter_id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_job.rb000066400000000000000000000016561361161326000353360ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Create a new job # # @option arguments [String] :job_id The ID of the job to create (*Required*) # @option arguments [Hash] :body The job (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-put-job.html # def put_job(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_PUT path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end revert_model_snapshot.rb000066400000000000000000000025661361161326000403030ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Revert to a specific snapshot (eg. before a highly-anomalous, but insignificant event) # # @option arguments [String] :job_id The ID of the job to fetch (*Required*) # @option arguments [String] :snapshot_id The ID of the snapshot to revert to # @option arguments [Hash] :body Reversion options # @option arguments [Boolean] :delete_intervening_results Should we reset the results back to the time of the snapshot? # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-revert-snapshot.html # def revert_model_snapshot(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] valid_params = [ :delete_intervening_results ] method = Elasticsearch::API::HTTP_POST path = Elasticsearch::API::Utils.__pathify "_xpack/ml/anomaly_detectors", arguments[:job_id], "model_snapshots", arguments[:snapshot_id], "_revert" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end set_upgrade_mode.rb000066400000000000000000000036611361161326000372000ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learning# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. module Elasticsearch module XPack module API module MachineLearning module Actions # Temporarily halt tasks associated with the jobs and datafeeds and prevent new jobs from opening. # When enabled=true this API temporarily halts all job and datafeed tasks and prohibits new job and # datafeed tasks from starting. # # @option arguments [ true, false ] :enabled Whether to enable upgrade_mode ML setting or not. Defaults to false. # @option arguments [String] :timeout Controls the time to wait before action times out. Defaults to 30 seconds. # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-set-upgrade-mode.html # def set_upgrade_mode(arguments={}) valid_params = [ :enabled, :timeout ] method = Elasticsearch::API::HTTP_POST path = '_ml/set_upgrade_mode' params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params perform_request(method, path, params).body end end end end end end start_datafeed.rb000066400000000000000000000026301361161326000366370ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Start a datafeed # # @option arguments [String] :datafeed_id The ID of the datafeed to start (*Required*) # @option arguments [Hash] :body The start datafeed parameters # @option arguments [String] :start The start time from where the datafeed should begin # @option arguments [String] :end The end time when the datafeed should stop. When not set, the datafeed continues in real time # @option arguments [Time] :timeout Controls the time to wait until a datafeed has started. Default to 20 seconds # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-start-datafeed.html # def start_datafeed(arguments={}) raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id] valid_params = [ :start, :end, :timeout ] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}/_start" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end stop_datafeed.rb000066400000000000000000000026041361161326000364700ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Stop a datafeed # # @option arguments [String] :datafeed_id The ID of the datafeed to stop (*Required*) # @option arguments [Boolean] :allow_no_datafeeds Whether to ignore if a wildcard expression matches no datafeeds. (This includes `_all` string or when no datafeeds have been specified) # @option arguments [Boolean] :force True if the datafeed should be forcefully stopped. # @option arguments [Time] :timeout Controls the time to wait until a datafeed has stopped. Default to 20 seconds # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-stop-datafeed.html # def stop_datafeed(arguments={}) raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id] valid_params = [ :allow_no_datafeeds, :force, :timeout ] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}/_stop" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end update_datafeed.rb000066400000000000000000000020051361161326000367600ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Update certain properties of a datafeed # # @option arguments [String] :datafeed_id The ID of the datafeed to update (*Required*) # @option arguments [Hash] :body The datafeed update settings (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-datafeed.html # def update_datafeed(arguments={}) raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}/_update" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end update_filter.rb000066400000000000000000000016201361161326000365120ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Updates the description of a filter, adds items, or removes items. # # @option arguments [String] :filter_id The ID of the filter to update (*Required*) # @option arguments [Hash] :body The filter update (*Required*) # def update_filter(arguments={}) raise ArgumentError, "Required argument 'filter_id' missing" unless arguments[:filter_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/filters/#{arguments[:filter_id]}/_update" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end update_job.rb000066400000000000000000000017371361161326000360100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Update certain properties of a job # # @option arguments [String] :job_id The ID of the job to create (*Required*) # @option arguments [Hash] :body The job update settings (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-job.html # def update_job(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/_update" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end update_model_snapshot.rb000066400000000000000000000023731361161326000402520ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # Update certain properties of a snapshot # # @option arguments [String] :job_id The ID of the job to fetch (*Required*) # @option arguments [String] :snapshot_id The ID of the snapshot to update (*Required*) # @option arguments [Hash] :body The model snapshot properties to update (*Required*) # # @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-snapshot.html # def update_model_snapshot(arguments={}) raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id] raise ArgumentError, "Required argument 'snapshot_id' missing" unless arguments[:snapshot_id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/#{arguments[:job_id]}/model_snapshots/#{arguments[:snapshot_id]}/_update" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end validate.rb000066400000000000000000000011371361161326000354570ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # @option arguments [Hash] :body The job config (*Required*) # def validate(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/_validate" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end validate_detector.rb000066400000000000000000000011561361161326000373510ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/machine_learningmodule Elasticsearch module XPack module API module MachineLearning module Actions # @option arguments [Hash] :body The detector (*Required*) # def validate_detector(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/ml/anomaly_detectors/_validate/detector" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/migration/000077500000000000000000000000001361161326000321245ustar00rootroot00000000000000deprecations.rb000066400000000000000000000015451361161326000350570ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/migrationmodule Elasticsearch module XPack module API module Migration module Actions # Retrieve information about different cluster, node, and index level settings # that use deprecated features that will be removed or changed in the next major version # # @option arguments [String] :index Index pattern (optional) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/migration-api-deprecation.html # def deprecations(arguments={}) method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify arguments[:index], "_xpack/migration/deprecations" params = {} body = nil perform_request(method, path, params, body).body end end end end end end get_assistance.rb000066400000000000000000000030721361161326000353700ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/migrationmodule Elasticsearch module XPack module API module Migration module Actions # Returns the information about indices that require some changes before the cluster can be upgraded to the next major version # # @option arguments [List] :index A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices # @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) # @option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. (options: open, closed, none, all) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/migration-api-assistance.html # def get_assistance(arguments={}) valid_params = [ :allow_no_indices, :expand_wildcards, :ignore_unavailable ] method = Elasticsearch::API::HTTP_GET path = "_xpack/migration/assistance" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end upgrade.rb000066400000000000000000000021741361161326000340250ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/migrationmodule Elasticsearch module XPack module API module Migration module Actions # Perform the upgrade of internal indices to make them compatible with the next major version # # @option arguments [String] :index The name of the index (*Required*) # @option arguments [Boolean] :wait_for_completion Should the request block until the upgrade operation is completed # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/migration-api-upgrade.html # def upgrade(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :wait_for_completion ] method = Elasticsearch::API::HTTP_POST path = Elasticsearch::API::Utils.__pathify "_xpack/migration/upgrade", arguments[:index] params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/monitoring/000077500000000000000000000000001361161326000323205ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/monitoring/bulk.rb000066400000000000000000000032361361161326000336060ustar00rootroot00000000000000module Elasticsearch module XPack module API module Monitoring module Actions # Insert monitoring data in bulk # # @option arguments [String] :type Default document type for items which don't provide one # @option arguments [Hash] :body The operation definition and data (action-data pairs), separated by newlines (*Required*) # @option arguments [String] :system_id Identifier of the monitored system # @option arguments [String] :system_api_version API version of the monitored system # @option arguments [String] :system_version Version of the monitored system # # @see http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html # def bulk(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :system_id, :system_api_version, :system_version, :interval ] arguments = arguments.clone type = arguments.delete(:type) body = arguments.delete(:body) method = Elasticsearch::API::HTTP_POST path = Elasticsearch::API::Utils.__pathify '_xpack/monitoring', type, '_bulk' params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params if body.is_a? Array payload = Elasticsearch::API::Utils.__bulkify(body) else payload = body end perform_request(method, path, params, payload).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollup/000077500000000000000000000000001361161326000314505ustar00rootroot00000000000000delete_job.rb000066400000000000000000000012321361161326000340100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollupmodule Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :id The ID of the job to delete (*Required*) # # @see # def delete_job(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/rollup/job/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollup/get_jobs.rb000066400000000000000000000011451361161326000335720ustar00rootroot00000000000000module Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :id The ID of the job(s) to fetch. Accepts glob patterns, or left blank for all jobs # # @see # def get_jobs(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/rollup/job/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end get_rollup_caps.rb000066400000000000000000000011171361161326000351000ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollupmodule Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :id The ID of the index to check rollup capabilities on, or left blank for all jobs # def get_rollup_caps(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/rollup/data/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end get_rollup_index_caps.rb000066400000000000000000000013301361161326000362640ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollupmodule Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :index The rollup index or index pattern to obtain rollup capabilities from (*Required*) # # @see # def get_rollup_index_caps(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] method = Elasticsearch::API::HTTP_GET path = "#{arguments[:index]}/_xpack/rollup/data" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollup/put_job.rb000066400000000000000000000015131361161326000334370ustar00rootroot00000000000000module Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :id The ID of the job to create (*Required*) # @option arguments [Hash] :body The job configuration (*Required*) # # @see # def put_job(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_PUT path = "_xpack/rollup/job/#{arguments[:id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end rollup_search.rb000066400000000000000000000021341361161326000345600ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollupmodule Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :index The index or index-pattern (containing rollup or regular data) that should be searched (*Required*) # @option arguments [String] :type The doc type inside the index # @option arguments [Hash] :body The search request body (*Required*) # # @see # def rollup_search(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :typed_keys ] method = Elasticsearch::API::HTTP_GET path = "#{arguments[:index]}/_rollup_search" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollup/start_job.rb000066400000000000000000000012351361161326000337650ustar00rootroot00000000000000module Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :id The ID of the job to start (*Required*) # # @see # def start_job(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = Elasticsearch::API::HTTP_POST path = "_xpack/rollup/job/#{arguments[:id]}/_start" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/rollup/stop_job.rb000066400000000000000000000012321361161326000336120ustar00rootroot00000000000000module Elasticsearch module XPack module API module Rollup module Actions # TODO: Description # # @option arguments [String] :id The ID of the job to stop (*Required*) # # @see # def stop_job(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = Elasticsearch::API::HTTP_POST path = "_xpack/rollup/job/#{arguments[:id]}/_stop" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/security/000077500000000000000000000000001361161326000320025ustar00rootroot00000000000000authenticate.rb000066400000000000000000000011571361161326000347320ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Retrieve details about the currently authenticated user # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-authenticate.html # def authenticate(arguments={}) valid_params = [] method = Elasticsearch::API::HTTP_GET path = "_xpack/security/_authenticate" params = {} body = nil perform_request(method, path, params, body).body end end end end end end change_password.rb000066400000000000000000000023261361161326000354220ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Change the password of a user # # @option arguments [String] :username The username of the user to change the password for # @option arguments [Hash] :body the new password for the user (*Required*) # @option arguments [Boolean] :refresh Refresh the index after performing the operation # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-change-password.html # def change_password(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :refresh ] arguments = arguments.clone username = arguments.delete(:username) method = Elasticsearch::API::HTTP_PUT path = Elasticsearch::API::Utils.__pathify "_xpack/security/user/", username, "/_password" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end clear_cached_realms.rb000066400000000000000000000022741361161326000361750ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Clears the internal user caches for specified realms # # @option arguments [String] :realms Comma-separated list of realms to clear (*Required*) # @option arguments [String] :usernames Comma-separated list of usernames to clear from the cache # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-clear-cache.html # def clear_cached_realms(arguments={}) raise ArgumentError, "Required argument 'realms' missing" unless arguments[:realms] valid_params = [ :usernames ] arguments = arguments.clone realms = arguments.delete(:realms) method = Elasticsearch::API::HTTP_POST path = Elasticsearch::API::Utils.__pathify "_xpack/security/realm/", Elasticsearch::API::Utils.__listify(realms), "_clear_cache" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end clear_cached_roles.rb000066400000000000000000000014521361161326000360330ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Clears the internal caches for specified roles # # @option arguments [String] :name Role name (*Required*) # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-roles.html#security-api-clear-role-cache # def clear_cached_roles(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] method = Elasticsearch::API::HTTP_PUT path = "_xpack/security/role/#{arguments[:name]}/_clear_cache" params = {} body = nil perform_request(method, path, params, body).body end end end end end end create_api_key.rb000066400000000000000000000037301361161326000352170ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/security# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. module Elasticsearch module XPack module API module Security module Actions # Creates an API key for access without requiring basic authentication. # # @option arguments [String] :refresh If `true` (the default) then refresh the affected 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` then do nothing with refreshes. # # @option arguments [Hash] :body The api key request to create an API key. (*Required*) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html # def create_api_key(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :refresh ] method = Elasticsearch::API::HTTP_PUT path = "_security/api_key" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params perform_request(method, path, params, arguments[:body]).body end end end end end end delete_privileges.rb000066400000000000000000000016651361161326000357530ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # @option arguments [String] :application Application name (*Required*) # @option arguments [Boolean] :name Privilege name (*Required*) # def delete_privileges(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] raise ArgumentError, "Required argument 'application' missing" unless arguments[:application] valid_params = [ :refresh ] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/security/privilege/#{arguments.delete(:application)}/#{arguments[:name]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end delete_role.rb000066400000000000000000000022601361161326000345330ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Remove a role from the native realm # # @option arguments [String] :name Role name (*Required*) # @option arguments [Boolean] :refresh Refresh the index after performing the operation # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-roles.html#security-api-delete-role # def delete_role(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] valid_params = [ :refresh ] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/security/role/#{arguments[:name]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil if Array(arguments[:ignore]).include?(404) Elasticsearch::API::Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end end end end end end delete_role_mapping.rb000066400000000000000000000024601361161326000362500ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Delete a role mapping # # @option arguments [String] :name Role-mapping name (*Required*) # @option arguments [String] :refresh If `true` (the default) then refresh the affected 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` then do nothing with refreshes. (options: true, false, wait_for) # # @see https://www.elastic.co/guide/en/x-pack/master/security-api-role-mapping.html#security-api-delete-role-mapping # def delete_role_mapping(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] valid_params = [ :name, :refresh ] arguments = arguments.clone name = arguments.delete(:name) method = Elasticsearch::API::HTTP_DELETE path = "_xpack/security/role_mapping/#{name}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end delete_user.rb000066400000000000000000000023221361161326000345470ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Remove a user from the native realm # # @option arguments [String] :username username (*Required*) # @option arguments [Boolean] :refresh Refresh the index after performing the operation # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-users.html#security-api-delete-user # def delete_user(arguments={}) valid_params = [ :username, :refresh ] arguments = arguments.clone username = arguments.delete(:username) method = Elasticsearch::API::HTTP_DELETE path = "_xpack/security/user/#{username}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil if Array(arguments[:ignore]).include?(404) Elasticsearch::API::Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end end end end end end disable_user.rb000066400000000000000000000022621361161326000347130ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Disable a user # # @option arguments [String] :username The username of the user to disable # @option arguments [String] :refresh If `true` (the default) then refresh the affected 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` then do nothing with refreshes. (options: true, false, wait_for) # # @see https://www.elastic.co/guide/en/x-pack/5.4/security-api-users.html # def disable_user(arguments={}) valid_params = [ :username, :refresh ] arguments = arguments.clone username = arguments.delete(:username) method = Elasticsearch::API::HTTP_PUT path = "_xpack/security/user/#{username}/_disable" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end enable_user.rb000066400000000000000000000022561361161326000345410ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Enable a user # # @option arguments [String] :username The username of the user to enable # @option arguments [String] :refresh If `true` (the default) then refresh the affected 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` then do nothing with refreshes. (options: true, false, wait_for) # # @see https://www.elastic.co/guide/en/x-pack/5.4/security-api-users.html # def enable_user(arguments={}) valid_params = [ :username, :refresh ] arguments = arguments.clone username = arguments.delete(:username) method = Elasticsearch::API::HTTP_PUT path = "_xpack/security/user/#{username}/_enable" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end get_api_key.rb000066400000000000000000000041751361161326000345370ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/security# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. module Elasticsearch module XPack module API module Security module Actions # Retrieves information for one or more API keys. # # @option arguments [String] :id An API key id. This parameter cannot be used with any of name, realm_name or username are used. # # @option arguments [String] :name An API key name. This parameter cannot be used with any of id, realm_name or username are used. # # @option arguments [String] :realm_name The name of an authentication realm. This parameter cannot be used with either id or name. # # @option arguments [String] :username The name of an authentication realm. This parameter cannot be used with either id or name. # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-api-key.html # def get_api_key(arguments={}) valid_params = [ :id, :username, :name, :realm_name ] method = Elasticsearch::API::HTTP_GET path = "_security/api_key" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params perform_request(method, path, params).body end end end end end end get_privileges.rb000066400000000000000000000016001361161326000352550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Retrieve one or more roles from the native realm # # @option arguments [String] :name Role name # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-roles.html#security-api-get-role # def get_privileges(arguments={}) method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/security/privilege", arguments[:application], Elasticsearch::API::Utils.__listify(arguments[:name]) params = {} body = nil perform_request(method, path, params, body).body end end end end end end get_role.rb000066400000000000000000000016711361161326000340550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Retrieve one or more roles from the native realm # # @option arguments [String] :name Role name # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-roles.html#security-api-get-role # def get_role(arguments={}) method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/security/role", Elasticsearch::API::Utils.__listify(arguments[:name]) params = {} body = nil if Array(arguments[:ignore]).include?(404) Elasticsearch::API::Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end end end end end end get_role_mapping.rb000066400000000000000000000013351361161326000355650ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Retrieve the mapping for a role # # @option arguments [String] :name Role-Mapping name # # @see https://www.elastic.co/guide/en/x-pack/master/security-api-role-mapping.html#security-api-get-role-mapping # def get_role_mapping(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/security/role_mapping/#{Elasticsearch::API::Utils.__listify(arguments[:name])}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end get_token.rb000066400000000000000000000014271361161326000342330ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Obtain a token for OAuth 2.0 auhentication # # @option arguments [Hash] :body The token request to get (*Required*) # # @see https://www.elastic.co/guide/en/x-pack/master/security-api-tokens.html#security-api-get-token # def get_token(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/security/oauth2/token" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_user.rb000066400000000000000000000017311361161326000340670ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Retrieve one or more users from the native realm # # @option arguments [List] :username A comma-separated list of usernames # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-users.html#security-api-get-user # def get_user(arguments={}) method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/security/user", Elasticsearch::API::Utils.__listify(arguments[:username]) params = {} body = nil if Array(arguments[:ignore]).include?(404) Elasticsearch::API::Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end end end end end end get_user_privileges.rb000066400000000000000000000006621361161326000363220ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Get user privileges # def get_user_privileges(arguments={}) method = Elasticsearch::API::HTTP_GET params = {} body = nil perform_request(method, '_xpack/security/user/_privileges', params, body).body end end end end end end has_privileges.rb000066400000000000000000000015321361161326000352550ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Remove a role from the native realm # # @option arguments [String] :user Username # @option arguments [String] :body The privileges to test (*Required*) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-has-privileges.html # def has_privileges(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_GET path = Elasticsearch::API::Utils.__pathify "_xpack/security/user", arguments[:user], "_has_privileges" perform_request(method, path, {}, arguments[:body]).body end end end end end end invalidate_api_key.rb000066400000000000000000000030731361161326000360740ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/security# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. module Elasticsearch module XPack module API module Security module Actions # Creates an API key for access without requiring basic authentication. # # @option arguments [Hash] :body The api key request to invalidate API key(s). (*Required*) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-api-key.html # def invalidate_api_key(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_DELETE path = "_security/api_key" params = {} perform_request(method, path, params, arguments[:body]).body end end end end end end invalidate_token.rb000066400000000000000000000014461361161326000355750ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Delete a token for OAuth 2.0 auhentication # # @option arguments [Hash] :body The token to invalidate (*Required*) # # @see https://www.elastic.co/guide/en/x-pack/master/security-api-tokens.html#security-api-invalidate-token # def invalidate_token(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/security/oauth2/token" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_privileges.rb000066400000000000000000000020251361161326000353100ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Add a privilege # # @option arguments [Hash] :body The privilege(s) to add (*Required*) # @option arguments [Boolean] :refresh If `true` (the default) then refresh the affected 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` then do nothing with refreshes. # def put_privileges(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :refresh ] method = Elasticsearch::API::HTTP_PUT path = "_xpack/security/privilege" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_role.rb000066400000000000000000000022311361161326000340770ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Update or create a role for the native shield realm # # @option arguments [String] :name Role name (*Required*) # @option arguments [Hash] :body The role to add (*Required*) # @option arguments [Boolean] :refresh Refresh the index after performing the operation # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-roles.html#security-api-put-role # def put_role(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :refresh ] method = Elasticsearch::API::HTTP_PUT path = "_xpack/security/role/#{arguments[:name]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_role_mapping.rb000066400000000000000000000027331361161326000356210ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Add a mapping for a role # # @option arguments [String] :name Role-mapping name (*Required*) # @option arguments [Hash] :body The role to add (*Required*) # @option arguments [String] :refresh If `true` (the default) then refresh the affected 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` then do nothing with refreshes. (options: true, false, wait_for) # # @see https://www.elastic.co/guide/en/x-pack/master/security-api-role-mapping.html#security-api-put-role-mapping # def put_role_mapping(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :name, :refresh ] arguments = arguments.clone name = arguments.delete(:name) method = Elasticsearch::API::HTTP_PUT path = "_xpack/security/role_mapping/#{name}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end put_user.rb000066400000000000000000000024431361161326000341210ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/securitymodule Elasticsearch module XPack module API module Security module Actions # Update or create a user for the native realm # # @option arguments [String] :username The username of the User (*Required*) # @option arguments [Hash] :body The user to add (*Required*) # @option arguments [Boolean] :refresh Refresh the index after performing the operation # # @see https://www.elastic.co/guide/en/x-pack/current/security-api-users.html#security-api-put-user # def put_user(arguments={}) raise ArgumentError, "Required argument 'username' missing" unless arguments[:username] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :refresh ] arguments = arguments.clone username = arguments.delete(:username) method = Elasticsearch::API::HTTP_PUT path = Elasticsearch::API::Utils.__pathify "_xpack/security/user", username params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/sql/000077500000000000000000000000001361161326000307325ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/sql/clear_cursor.rb000066400000000000000000000013201361161326000337360ustar00rootroot00000000000000module Elasticsearch module XPack module API module SQL module Actions # TODO: Description # # @option arguments [Hash] :body Specify the cursor value in the `cursor` element to clean the cursor. (*Required*) # # @see Clear SQL cursor # def clear_cursor(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/sql/close" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/sql/query.rb000066400000000000000000000016671361161326000324360ustar00rootroot00000000000000module Elasticsearch module XPack module API module SQL module Actions # TODO: Description # # @option arguments [Hash] :body Use the `query` element to start a query. Use the `cursor` element to continue a query. (*Required*) # @option arguments [String] :format a short version of the Accept header, e.g. json, yaml # # @see Execute SQL # def query(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :format ] method = Elasticsearch::API::HTTP_POST path = "_xpack/sql" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/sql/translate.rb000066400000000000000000000013151361161326000332540ustar00rootroot00000000000000module Elasticsearch module XPack module API module SQL module Actions # TODO: Description # # @option arguments [Hash] :body Specify the query in the `query` element. (*Required*) # # @see Translate SQL into Elasticsearch queries # def translate(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = Elasticsearch::API::HTTP_POST path = "_xpack/sql/translate" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/ssl/000077500000000000000000000000001361161326000307345ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/ssl/certificates.rb000066400000000000000000000006131361161326000337260ustar00rootroot00000000000000module Elasticsearch module XPack module API module SSL module Actions def certificates(arguments={}) method = Elasticsearch::API::HTTP_GET path = "_xpack/ssl/certificates" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/usage.rb000066400000000000000000000012001361161326000315550ustar00rootroot00000000000000module Elasticsearch module XPack module API module Actions # Retrieve information about X-Pack features usage # # @option arguments [Duration] :master_timeout Specify timeout for watch write operation # # def usage(arguments={}) valid_params = [ :master_timeout ] method = Elasticsearch::API::HTTP_GET path = "_xpack/usage" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watcher/000077500000000000000000000000001361161326000315705ustar00rootroot00000000000000ack_watch.rb000066400000000000000000000024571361161326000337720ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Acknowledge watch actions to throttle their executions # # @option arguments [String] :watch_id Watch ID (*Required*) # @option arguments [List] :action_id A comma-separated list of the action ids to be acked (default: all) # @option arguments [Duration] :master_timeout Specify timeout for watch write operation # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-ack-watch.html # def ack_watch(arguments={}) raise ArgumentError, "Required argument 'watch_id' missing" unless arguments[:watch_id] valid_params = [ :master_timeout ] arguments = arguments.clone watch_id = arguments.delete(:watch_id) action_id = arguments.delete(:action_id) method = Elasticsearch::API::HTTP_PUT path = "_xpack/watcher/watch/#{watch_id}/_ack" path << "/#{action_id}" if action_id params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end activate_watch.rb000066400000000000000000000020771361161326000350320ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Activate a currently inactive watch # # @option arguments [String] :watch_id Watch ID (*Required*) # @option arguments [Duration] :master_timeout Specify timeout for watch write operation # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-activate-watch.html # def activate_watch(arguments={}) raise ArgumentError, "Required argument 'watch_id' missing" unless arguments[:watch_id] valid_params = [ :master_timeout ] arguments = arguments.clone watch_id = arguments.delete(:watch_id) method = Elasticsearch::API::HTTP_PUT path = "_xpack/watcher/watch/#{watch_id}/_activate" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end deactivate_watch.rb000066400000000000000000000021051361161326000353330ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Deactivate a currently active watch # # @option arguments [String] :watch_id Watch ID (*Required*) # @option arguments [Duration] :master_timeout Specify timeout for watch write operation # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-deactivate-watch.html # def deactivate_watch(arguments={}) raise ArgumentError, "Required argument 'watch_id' missing" unless arguments[:watch_id] valid_params = [ :master_timeout ] arguments = arguments.clone watch_id = arguments.delete(:watch_id) method = Elasticsearch::API::HTTP_PUT path = "_xpack/watcher/watch/#{watch_id}/_deactivate" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end delete_watch.rb000066400000000000000000000024221361161326000344660ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Remove a watch # # @option arguments [String] :id Watch ID (*Required*) # @option arguments [Duration] :master_timeout Specify timeout for watch write operation # @option arguments [Boolean] :force Specify if this request should be forced and ignore locks # # @see http://www.elastic.co/guide/en/x-pack/current/appendix-api-delete-watch.html # def delete_watch(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ :master_timeout, :force ] method = Elasticsearch::API::HTTP_DELETE path = "_xpack/watcher/watch/#{arguments[:id]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil if Array(arguments[:ignore]).include?(404) Elasticsearch::API::Utils.__rescue_from_not_found { perform_request(method, path, params, body).body } else perform_request(method, path, params, body).body end end end end end end end execute_watch.rb000066400000000000000000000017431361161326000346730ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Force the execution of a stored watch # # @option arguments [String] :id Watch ID # @option arguments [Hash] :body Execution control # @option arguments [Boolean] :debug indicates whether the watch should execute in debug mode # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-execute-watch.html # def execute_watch(arguments={}) valid_params = [ :debug ] method = Elasticsearch::API::HTTP_PUT path = Elasticsearch::API::Utils.__pathify "_xpack/watcher/watch", arguments.delete(:id), "_execute" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end get_watch.rb000066400000000000000000000013211361161326000340000ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Retrieve a watch # # @option arguments [String] :id Watch ID (*Required*) # # @see https://www.elastic.co/guide/en/x-pack/current/watcher-api-get-watch.html # def get_watch(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = Elasticsearch::API::HTTP_GET path = "_xpack/watcher/watch/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end end put_watch.rb000066400000000000000000000025251361161326000340400ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watchermodule Elasticsearch module XPack module API module Watcher module Actions # Register a new watch in or update an existing one # # @option arguments [String] :id Watch ID (*Required*) # @option arguments [Hash] :body The watch (*Required*) # @option arguments [Duration] :master_timeout Specify timeout for watch write operation # @option arguments [Boolean] :active Specify whether the watch is in/active by default # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-put-watch.html # def put_watch(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :master_timeout, :active, :version, :if_seq_no, :if_primary_term ] method = Elasticsearch::API::HTTP_PUT path = "_xpack/watcher/watch/#{arguments[:id]}" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watcher/restart.rb000066400000000000000000000010521361161326000335770ustar00rootroot00000000000000module Elasticsearch module XPack module API module Watcher module Actions # Start and stop the Watcher service # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-restart.html # def restart(arguments={}) method = Elasticsearch::API::HTTP_POST path = "_xpack/watcher/_restart" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watcher/start.rb000066400000000000000000000010471361161326000332540ustar00rootroot00000000000000module Elasticsearch module XPack module API module Watcher module Actions # Start the Watcher service # # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-start.html # def start(arguments={}) method = Elasticsearch::API::HTTP_POST path = "_xpack/watcher/_start" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watcher/stats.rb000066400000000000000000000015661361161326000332630ustar00rootroot00000000000000module Elasticsearch module XPack module API module Watcher module Actions # Return the current Watcher metrics # # @option arguments [String] :metric Additional metrics to be included in the response # (options: _all, queued_watches, pending_watches) # # @see https://www.elastic.co/guide/en/x-pack/current/watcher-api-stats.html # def stats(arguments={}) valid_params = [ :metric, :emit_stacktraces ] method = Elasticsearch::API::HTTP_GET path = "_xpack/watcher/stats" params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/actions/watcher/stop.rb000066400000000000000000000010431361161326000331000ustar00rootroot00000000000000module Elasticsearch module XPack module API module Watcher module Actions # Stop the Watcher service # # # @see http://www.elastic.co/guide/en/x-pack/current/watcher-api-stop.html # def stop(arguments={}) method = Elasticsearch::API::HTTP_POST path = "_xpack/watcher/_stop" params = {} body = nil perform_request(method, path, params, body).body end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/000077500000000000000000000000001361161326000304275ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/graph.rb000066400000000000000000000005371361161326000320620ustar00rootroot00000000000000module Elasticsearch module XPack module API module Graph module Actions; end class GraphClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Graph::Actions end def graph @graph ||= GraphClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/license.rb000066400000000000000000000005531361161326000324010ustar00rootroot00000000000000module Elasticsearch module XPack module API module License module Actions; end class LicenseClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, License::Actions end def license @license ||= LicenseClient.new(self) end end end end end machine_learning.rb000066400000000000000000000007021361161326000341570ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespacemodule Elasticsearch module XPack module API module MachineLearning module Actions; end class MachineLearningClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, MachineLearning::Actions end def machine_learning @machine_learning ||= MachineLearningClient.new(self) end alias :ml :machine_learning end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/migration.rb000066400000000000000000000005671361161326000327550ustar00rootroot00000000000000module Elasticsearch module XPack module API module Migration module Actions; end class MigrationClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Migration::Actions end def migration @migration ||= MigrationClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/monitoring.rb000066400000000000000000000005751361161326000331500ustar00rootroot00000000000000module Elasticsearch module XPack module API module Monitoring module Actions; end class MonitoringClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Monitoring::Actions end def monitoring @monitoring ||= MonitoringClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/rollup.rb000066400000000000000000000005451361161326000322750ustar00rootroot00000000000000module Elasticsearch module XPack module API module Rollup module Actions; end class RollupClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Rollup::Actions end def rollup @rollup ||= RollupClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/security.rb000066400000000000000000000005611361161326000326250ustar00rootroot00000000000000module Elasticsearch module XPack module API module Security module Actions; end class SecurityClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Security::Actions end def security @security ||= SecurityClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/sql.rb000066400000000000000000000005231361161326000315530ustar00rootroot00000000000000module Elasticsearch module XPack module API module SQL module Actions; end class SQLClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, SQL::Actions end def sql @sql ||= SQLClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/ssl.rb000066400000000000000000000005231361161326000315550ustar00rootroot00000000000000module Elasticsearch module XPack module API module SSL module Actions; end class SSLClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, SSL::Actions end def ssl @ssl ||= SSLClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/api/namespace/watcher.rb000066400000000000000000000005531361161326000324140ustar00rootroot00000000000000module Elasticsearch module XPack module API module Watcher module Actions; end class WatcherClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Watcher::Actions end def watcher @watcher ||= WatcherClient.new(self) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/lib/elasticsearch/xpack/version.rb000066400000000000000000000001041361161326000277270ustar00rootroot00000000000000module Elasticsearch module XPack VERSION = '6.8.1' end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/pkg/000077500000000000000000000000001361161326000220155ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/pkg/elasticsearch-xpack-0.1.0.gem000066400000000000000000000260001361161326000270550ustar00rootroot00000000000000metadata.gz0000444000000000000000000000175112741366132013447 0ustar00wheelwheel00000000000000ZWZQ4~ϯ0rOI'B= !δ1Mb3v3v[^)j7盙|_MT|Dr(]EڠT+%)%Xl:%-:1 75e?!Ͳy6KLn-$лZ-T|x: ^O&ɕ>%li:,,f"dGTh C3~rһk^] q{ȤuWn6s4&ş/B7lyGܳy6=nk8klB r QO&3)/y? Fk?<.M}T ǐ"}fSGYMvqyvtmo"?\ǧMVuʡ3=Lq[뾩 s,B&O\Z0|Z@i96(LB+IN\1T(|XiFc=ȍ8<ho[Pߛ;oA;X6hÆɾIPReR{ʩu /BͶm|ޔw#W/_-ǰMl5(Q|d,hϝ98i3u7tkdB0L\nxTY iR:_X{Rn\FyX*߃TJ5V|AG{\Nv"EXb{hdTGG㢾Cޔ85Wj,{͹p?ґP?\P- w<0l L4ݪp `cP{AbxZh`v"yAe&uǎ}^ o*xa+.TuTeӔ 't5;E1H'^A\q]ANtS/GIt M{2ӥZmJ'P4K\(愌@*JJ@Jwd^C9X#X=7XC.l +DWZw:H# zK5< y_H%`vV}'D=j|f@/e{=CwYH5XeF(dur clPW4Oh&{ ERGXO0y2 Zcj"]cukZysO{Urأ\L#:6Bdbh5P:i7w&gQ$kmOfy@V'i'?ӣ,UoIh7qzx|~8@A& ` i,PjH:wFl}s47[FjN"g筳fR?vP*<#OpCkXTvܷ?r6]8;RǵINj,WsGXGX^ ;4XiYedѮgIhco5O lNdD iS&3=I]zhAt_^wr굣z~=_ޭk{30i'ޥvAգJ{zȡLu^y*\em i8H;V:ph dZHG‘q@:`P(eD2w?_e u$T tJR/df,ąLXKߙ]ŀ#kM4gH/`@*հLJ/dF/=/ءtZ"K+Y_A\޾%%r'9_Im*aF F{C9H2“f2Dzl<W{at*z+3p:ZC>?< ,. 3Ҋ7ۀT?`Z 6WgoB R*9n+)Q-1MY&^;_9;Y7]r,k /5 m6v7]BL+ nϹI(xJ@B۝n 5|ARwÀ ] kyHAH&`pӵ=EEJW^!/2bTmֱ=bҘ]SwTЦ( 0Hr#>'gai q8Wv9D=H͈jγr)htySouA'w _dNdîa .klcW>MF.% `:,t+pRW7V:NU2hVy~ЋJitKQsQZQ'zJr:K_,Ki⿪U܏ <_TL2W q$Y;: $S赘:Oܣk.".}j-9 sO7όzK tO,OV<3);Dt O^ Hэ+/=c$͒:hؓ)pd..c0䀘pU#ɠu?m636@q'qSLf6eoI??BmY` >2X=Ƭ*Vд<cF ԙdKCİf$P+51.e&$)/,I2'F[<))kpOMb. s\}V6;xUTW7]:"¸1c%&Zs|<(XٜS-ꛘEYPJ8'Wd&}o~Oվ1@9bZsX!;\hC:_,#>O:14Ϡh>v`>"9>.fF{`$ؔ@I`&lX,-Q1:M#\P VtvUauӣ)oTL{ĉT@RCk4̪9#MN ]7n$b:Ցr؁|Uo춫>}{?g~XAfކtj#4>}7gOAM7@UʑrR)JZP*Yڄ?r>^Z2ۖ!6LGQl\xn>ӵkOhB9mC#EtۯwPUܰsg^m~u/3ovwΛIp8F 4<Ѷ01r0 Nޙyv `/0ܧ9ٹ,IuoBSD4X[t>[vKfA>lG@U@ӼELPVpe2y7yj6EM>oEGQݕ?Ʊ!a/)2VPc<;Z3)Ԟ`"X}[Lx6M/Q\hUQ.Hu)β@64,U1HbH\A`EKRh 71]nb@[SulޜWڗw=~a@8! e^ jqaZאe@CʶasZp@ ߀>vpl&JZne8uvmᔌ <@vg^wʯ0.lei21,E |$ opڙhScf:(nymdzq!<5 /T"^@"쿶۵ ^QlW'y.(~8  $M5u8זŅUJ9/yzm눀-% CU'LJ+1/8 矖;?;۴oSgp_qPleb8TCYyVi3mb3\GـhB2-쮊u5=1r+ߏ/W*ϲt6=kpnwLS%#YG1#ER+X^_e :-CysJK'YE.BtjK9@gѣKErP˕Wzo)qB⿕b/_%߃̳k%އ0w1Ўx`Y 2UWSP ;_ 1Lơ_,[EAQA9-:k) AT/}iLʞ VbGd"́|9O:4efznq7Y㇓vۻvgj8HVYgU"c9R`rߤ 3( /kY lJuOXZBsk;1⿻s,l?iMyxwShe 1Z!/wz̙i%bT[[{y_R/:b3p>?f3Xk6`a m[؀,$>H|ؒ{asO~IEw`tEMc `!(9tFQ@Y|}ooȶWȭzm*_@$o|ݽQ@L>øIS[>Ra {.'[rq/UJ_?x""+4ւiECFFT鈮g C>g{@SJG Y5@Ilc`ű.<jR`@ܷa$PyJlϭvE0̃ ~W]+-7\ fk+Rtwt _#@69p|Q;]Η5KQ:,H#Tm,aX^5?%K?@T, 6 WlWS7 uL"7qgh8i{R|I5~x.& b9ʐX3ϻ򁛐,r+\zPXkv?}u6x1jm\=oKy˒s;AHJxh xX.3»7yU.WGPE߲퍏 TҾJ]= > 䉼|zn3F4((I/Vэ>rf#liB9tH֛ )> ǃ@O+.֣c@= kpnch`AJҼ(Jad Wj<~EA2 1Ksxj4u|D6/r5@ǰw/Əb[ci }8]U.pdܣb%xBphdCjʷz2U V)rժ2aY5!mI5EsUO OpB6]_ޕ/CXG,J -`DX= 1M0Ϋ_w- lbK{ѫ>od<0hLJ߫]o>D'lV/ǮG5q|^;;9E3y?/}[ThHLthDyIr'˱Dqd5XҸp↠L°}lR#s 7\0{#qٵfP -E 6l+`;"oWJ:R*4x#mZߦKtz5-)?ru?kݳ坡[DꋢpA\C972Ozt9knMKxTKxV x xv$4J};@Kms⁆pZ *í}@c+Njȼ^4^ݍxto#T,=42飣z踨sq v,=D&h/HP=n<0l L2Ԃݒ3@aHYxW8ި%k3sRM Y= oTI]'8^sK/{Tt/۶$m1ər5~8I?x#?ԁT q8:5Y̲,*aOIc5up’sXT{de]q{BwߩQI!data.tar.gz0000444000000000000000000002246012747412462013371 0ustar00wheelwheel000000000000002W]k{Fg~E/>@9$c33^$b5!o?Uխ+؎/՗z uWͿyRT67+YֶۛV 7\SUm rĹ$ݪƽOMLYVmgx\1L'nCumuiō!u&_IJ]~I9MzKqmBwz# N̞_gq3XՔȜhnB'F L .XUV_%eֱ׶)?XSYnY..w2 5$D9Lnjq:wjG`3}Ԕq{ @bcuc`nLtUC尼 g2G@h\52 ]Țk},roL5{lc]ր٩N :Ɩ>95k2=7tgTdEO]M"lᆑP`R[( >ue9xrd-ѝ`jP%<]F5]aXشej:if289p1[t7 $Uà^-96VLdj0x3CuivumXv E[c):;ǿwlw^yiu찓i0CgC`UEeAW|(#Dh 2?;@g9+E'd7 wzé27W%rjc˺+e䎍BQJOh{Nμ'gykam8<\qtײbGi@-+. $!UQc򟩅9SBeQG9uC!E>HD!wVUʬT'e ?P(_5(R@pX |IW;"YB. ƨD=3UWP Wm**rґREO& II3 OsP/tR`()$\`â?XTN`Z#6z 44۝n[RbU%픃6ݨ%!<؛\] k6!1EaQͩ x5!߷P~*㏌R弻'<o;wBiXR(};l"#s SKI'Z}F P35#p C:#Ř{*XI9R zy" c: <8vz ܒ:KyMFY2p@/&+5!a9`'ݽ~H/UpdHH A#谳9Mxwnحv4濬Ç![亟ǭܩ2tr\d\fLp Q+2m٘"GQ= ՘½nyêl&-̚ )xMò%XVA>SYl9Ds֘"+_)UkB8,ɪ~mu*/ EhĨv듃 :LS>k٧b`j߬OV(+` QRAWSʍVF%wl L(CY!_7۸AÝ27rQW}_7I(0Q_Luz&h05?v?~92quZo ft" X> THEZz4 ̯*^u@Oވ_YDL t1oa$,#`xr03ןV`;np4}EVDT:6Oc+ )lHmA_o DJPMy\jS$~>G㼻{@&COmR(NUla Wadym& I^ % _@t7כp{zIRȄ8Xô\}s>?W'9eX; ?S-,g<2SwptdO|FgLKDt<5 O±+Z`Ŏ1Gϣ6r -I )h~#,+p5pJ~gbqUS [6Ph!W\ 4aeByV #ƌKUԮP!`AQ:ƹpxA(9c|i=_pÚQ^td,ߟ(:$[<)+H= 'C% yyVܙNׇC0oD Ǻ]+qIlє(3p (YUV&J}%nk%ˉ[L^R+I_hlF=OvLo?Upʯpe|0LR,QШטs Xld6XKBKBRr5XnRPIܙ”K1ȁ2A5 y^"Z.iQqRpguGD,=(`6P ¡X+|^p0oE#`g%VQ?w( 8"ed(Q3AԙE(S(Ȉ\*%DHYRb}><s" a̅Nt"15yӇ{Z(ֈ["`M^P}DGS蒟.3F p{./XC&G[9l(^ _%0f`-g&7DGhNv 8Q ?_ߎ716n0I&lOײ3AD6,Uk) H_6"(i%iEM'PGCn+?N7lb[}a"NB>">".3%WLmq?fs GwEP/08 zI,k3d}S)ȣ)}; <Ĕhq6"آjqS|Nd͌$U Ttf9n9+|@;Ilf.$G]ӓHuFYN)y6j.@=!uU9_lBO mZ'WϹ=7殊R1WEINv)3K U+%%3 r.#h*Njɱ_jW!QHeb{&\.tcr_ s Q 44YUϣ\%lD:f%_͍ ysS^kyM;N!F+g?C0D0QBEIHa xT?W -)UFz>rp!7CAZ& E—79%y?hrRޑ9[z½{XL$$1wF*F֓8PBۛ38synF-!q0\iz!׾u\`N|I'h&.@i&:ek`-hC~*:<72ՊBpA2 q _ӺTn_JC pTFaV@ff*O>*J0B$M]纫(hIz5mL̷-F[ϩ$_E |Vۛ*Rm;X1L (^G.?̀wa@}2(:\Pdg`^hZyAIN*NLꋋS >/t&A<͝7DMRI{wMcp܂%>>syyk᜿[խѵ2-,P"gOOG Pȣ m0)\_jMRs3bZO` ;GmH4>^XGbx^9&շ[Iqc@*oC Pz=2znNUWUr7?h6ׇ2&jW%7xl MV Qx@}&Jn,p{=z~= }s7eahAa ~,d07hpͰ2z==i{KAy=΍Z =wQ>hw8/Т Ld: K=PZ'K%Z ;hǏՒ'M sR%h~!R 7T8|==[=I"CFhI޻ R5RQcm%dg䢤\$Y̓n>ýHGO쎞SDj$[%Х]wd$qn6jq_K'U?έ{i~:].VO@ 2}?PKU0&8Ip׳!?Wmo+ /VmV8&,pX`It mLQBz=⁧_UZeO[T;71YI_7he  O״_\G7x;Ds>YC^W+qȦl7T^M̍DNp! CٖtLn3~WqCǓr>[`k:,D4D:kށi$8]5u>v1#Q8%$~yx¥fhͣt=< =-I-4%w+{>7^Mr/NZ_N5A*_6jQqIJ"쟵T+9ShVzMW5~?JWh?>ϟH]?`d Π)x* |N*9fU3Qˣ> q@wYSCeJ~|g!DxЈP"+*谦_#6Gk_k?l4w$q_q;`[k[Frck%>H=/_q,@rʒ;xѐǶcܓ{ǭUVT>O?[d2lH$O}x"{_,z?&=OqcnVs?Qutۀwi زT UM@x9dUww{ 򞭓Qz%}[ίF~,7&R n'ݏz gMJ+@_7i+.d剸_֖/cMޗ#dzm x(pωmu\ʨ(ULlڇ.WzWz~@6checksums.yaml.gz0000444000000000000000000000041512747412462014615 0ustar00wheelwheel000000000000002We9N@ E">tt㱩hP*Nϐ:OnW_zĎG||߯"{L\`aQ2Ų æ/ǝTҁ "ڋڋp-`%6FF5}tT|5"aU8:Žx(" ? #n$a9(,` 3q:: 1!F-Y㜱ehɒix=Pt+'ivtx/&~٫{ٶ%iC$d^ ʍw$Mm <рV'$/4A{L/Ѩ |uFĒ:ҫְ#+{':\'tK .t!data.tar.gz0000444000000000000000000002245613010161324013354 0ustar00wheelwheel00000000000000 X]k[Fg^}lgm'$a3 6$FXm[;d.TU6DJR_/UVuuK>0-dWZlnl|SWRm}S]Tz ߭oXg&@ՐscAe{%WY˙rښ˔?Q_7bXϙrW܆=ӊyletGrz(7#u#2Ts0n0{rq/G c%VSJ=s d 6#&0!7lVdUZQ6SOZRWb_oS˱&vuN\F)\(=e2k]߰HsԸӹqCu\p KcY2 gL9e^AZe+3縎}j}M<(d2C{VaWmnOL#qtdÆ7l`˵"ۜ3zC"s-7lm2X9`*AMHWP$֘8VOW<dMWu>TX˻@z#sd TU#" yؕl2 zDCdž>e dЉ-@:ldi SƓ CwEXąޤ,b;ʖn(&5 cPWvw(' UrʣYeTy;ouMYcF&C^ GmkZ EwQ!=.; ccDC+7S?6Yo;&kuQ^sew:;[d?3H98g;ϣvaL~ Z'{;8܂ 2PjvOG:y:>2;ivOw}tiB{PA}ji~j+P+c_|Ǫ2;'@}cG[>{M oQ;OEiCrB) &Ա>6ַmYV:"i:!ۇNqH@(EFN/5w,)>#W7jX3|dvX,...z,aƯ]Pr(puuHs@Yz!"u*Ȭ#PٙE@٠N" * (Pl gb=JA6}&&:.A&T iS2zΥ|N=pN=9@ ,]!QBrE6_ 5N.0cY&.T+,2 k'H]2i, y3H3,3fu-[9zxqH~_!>t@slfjccB1cLt[Tbj!7FFf`0R ZHϩΙ_9Ɋ~Y ~&#[g]Ml! rYJ sbX@r*DEݺٷhf/&e᫢(Es՝w Ly#ǩNSiQ@k9 8Hy U0Kt wµ8ys'baYEMgx@ +dDc!dH` 3XDžʾDxM7e2tGF!(~D[=ޓ`_h 8k7 p|6 *vP1~B낃A24 O{+UHeVS*֓ /# )gU8Ѕ=>I ݤfOXT,FB~TڣŪ++6Fe9eN)"ˉ BRzH6+4d W6Xl>D %^ '*njJk`VA'jpIuȯAu:d؛\]` L#ZxZ֞ϡ@Eb=PDw:*1q G=_LonI%Ɋ,pd5ʐP<&W jNHu8O $V L̑5vtti~ Zwf&U^~[Wv͟|BYn Sj ҝ8Tn|*0*ÿdh` 0Dz` ZEN-iv锋J|0O@AZbF3A{vmosV2z҉-`z'R!aud6(0xq=y+Fg1 G|Ϝߧo\FVXl1DQPڸ>y|7= }1EO+ ](B5qNsIL>.fP$Xu]?l7>Oj?J(0%n@;$veI]}4 qiA56n?4s>?]Nrưv&+#r+@HQeZ//y.oZY4zFA4헾πP5.J|<v߷n!^h21w&z,C~ =e>j4:җ$' wQ_BHǿYvΔze~_NˤN! /i6 =!RN1/W8K;W+| nQYp]9[ Ǯh;F|< 5:_{;ױ $\qוlA9)ѿc}eBɵ@[)8b PEA `1rfo\lj8,Ј%71:~ JKȲI13,>w2$Qrm27hU{~ɝ8q}h?$JLpݕM9Ckbhj Uej'Q±}}&?t+BUz|z5σvLo=UdʯqM&0LR,QШטsHɬeXSBBRr5XnPPIܙ”K12A5{^"Z-iyVPqRpcuG*=(`6P ¡غWP`38'͋CduJͭ*~P*pD(`@"9f23EPNMUKR5rKiR6x||vZbd0ϕjc41:)D`HMMh X!VBvn5LyBOD"TmrMs: ?+~Tۗ,!Z0 o쳡xQ.|7Ƴy hEH7vj;<.,p~mobb,MخeϦzcXSl _D8f%A+`KҊ L!VT(ll[=a"NB>"> .3#WLmv ?s GwE8/08 zI,vk3d}S)ȣ)}; <Ĕhq6"آjqC|N`$U Ttfn9+|@;Ilv&4G]PuihN)y6j.@]!uU9_lBO m[Z'W/=7⮊R1WEiNv3K U+%%3 r. hڗ*Njɱ_jG!QHŋr)?"sbhEMCU#ǡe(!G5I'u-B^POrQ?i?A0LKڳAc"K&Q´A$x.$wcCueРR}FZaТ02pK7a^dOYN_g̢' ܹ %P.&>{y~b_Lu"DKgM@xg?^5֠)]_`gL|23I­tIķ\rMӝf3㏥w{S\3WDm^7L!T=r’?,Ns{|2>~󷷂myN5;[ERpDF+ ?%"e5qRxV@`\-+P(V¹ mk( _L,bV5] yG[Koݛ1b3Е?h &߇EYOo7B =ndϠ3̊~\x<R?3Eз Ľp>0 p\{"qQ\:ƮGh&:#|W傱EdI\T+ 4o$@OF1|ULJ=Ew7+բekZ~CQi%?(iZ&ao]EAK֫Yo#H `":|MF, Sr[oUo$;`Ow@%̱6bP5P潎c 6C!99h]dQVCuz+$lѴӜTg"}_ɸMx;o~"2fmDžF0F*!`J"|=. 39W7qz-=Y㿣koeZ YdDΞnΏ),ϑGA#`R09h?lQEgĎ 5-7vZRh:- ]rM:(׫zwƦT݅4Vtdu1ܜ..;n~Mm6e8L 0Jn4v2=/a1AF LX;{Hǧٕл) F8 hŘdЯs>VOWd!biž@ h_=`)(o|XK28az}. j{ g%Z`${]Ub#Ub'Hkw DKaZrX`!ڣxN-?D _vjS Ѿ;NlH+n+ڂ͂xY@mqO4bT2?hGۋ<4o?:BHz%uO,& #ȼ5aY1hag Κ׸)̵y -h gz2W2)Lݾ"f,4QG4d#4ٸ^m_gQW/wlN#`(4O&'(2IWǑpRW7Dxz48FbԂ"uaʁ`P.\~ڠ|;Lܩ"}Jh]f.0%SP:a xO/q,?֪[7hY%hn^HfNF.YB^Y`Y`4p2RMvdsGNib_5.Z$)e9 *6\uL(?l&R^_ {zOz*ߜGpSx)~<^:ߒ֝=c,zTހ(8n9 ^@:2pU?͵zeZWeoCNā/C<8HxqJk7e)(ڴ Īz?I:bb,Vf=BTpe*L3k}2m(|G<]̜ @Ytq;QB+Z ScUBܘז'WHRk#eB5"ժwÑ`wbJk:ldi(D[9XdYo(`919FGw$b,=OBcx_oA\uDnjJG/4"7`3lDciGt՟aNMlм-P A1$Ek8|x1| ^S+)x*\t].^L_ȹ!wU^_-LIAeFr,F "z 4]f~toύ0Ebz=v՛T,{z'wiw<9$Μ[,>[!KrQds[*?S:V6wg_9NR${SJ>/ш1qRghh=\݄= vF#lѧDAO' n!T,&BT9ǑEeJSJ*b &؃`zoL|)z7ޓWk?&JTR->ԏEI uHT@}.{6=̉ IJ׻KHXݨO~[d!x}q`:|ƧE~V cy`Lpy@@ACk +u]8/OQ]%l77.q Π2U|qO)_;>"ؐ/HTIb\v^EO>DxuY!xcFeYDxiYkZnoMLݮ#cgKϋ$z֍T 6뵸Sf?9}O vA uT_p8s#->:JHQnR"T߫]Oܪ_PxHD>3s`eG_t:dN7 _MWTs+Uk}VRO"r/OHIlCݰfx$guus^~XIkjsz*ߞ?%|(7SH/:>"2œϸ ,X%ѳL׶:^nK|z^2 XO0%Sv^-!gOm_tk+)NF}[ӟ dz5oOm~L3S=^z>̴IiE?mߥ)`2bf3T5Q2EW}E){NFjcF\|a}3v>莣+̟Ӈ$}n{q/^uUhUThJ`Ӓp{ͫ;G_i4TH2Ql6_~f]ֽ;ݿ/?G l0Jj{)e qU\yrݏ[lW:IF>i|\mIj1,Sx"3 .<#I*nZdT II#;-9|\D7'ۓāF7`f o2 +K&]J߲_]GCruP0jkWvx̩LhoIf<դҍՒ}vGve+!5Sa&vܝ]W<~~w[:իoqd C{ :)& ZruCcx I[-FqaL,{sFQ^(t; q+AJ Ж p]hĪ\:c7ߪ!,x&OφYd<,"u*#¬+-yoH᪺k& ^R3%2عbyv˂3]E䉥8X6 T%1K\.ƆL>6 爉sDGBG'.~- 2гcTs>#Slzogq Z9!`p,u'apM`р8>Ts*% ;;"9 )ǡ(7%7S͌{ A +L!r "8i&non mF(ͽ7d5W8jIo /@ wuw7Ӂ)&էQ@g v)0? {OAy fPaPsZف¥_ʔEbnԵ2 /RnN/,qaO3@?B#+8+P|Ĥöm/揃UPzXyPty`=C-.MS&^_a+}w]G6T~׼SkUiF,data.tar.gz0000444000000000000000000003240013127722143013355 0ustar00wheelwheel00000000000000c_Y}k{Fp>+qelLw=9'<^F#$Vxn]H`6ifVZe;]ZMU\ɿZ}Zݯk; (hj߰7kƮ;Дri{%WE[]WrNwv'W{5|U17XV<}ÿw*َ­7Urߨu\7 Nw{ qN7397f2k5m7w{چdMC&o+߰Vj{ _%iJHj{u\=v:7r RrW~!bݍu[]nu 9`]\w:! 2U2} $75\_-m)r1mw^7;s.;Cu bwǻ%s8gvu%L؈;.|`_{aV5堤70n(eCx ԍ[a}Ȱ\A|*rIw+vkx{1ctF Vw k؅`;Klhw_NMX@cFsiLk:*Mzr\|r;n7v,7]jxlӴok#TנQ_Z6n14pV+w@Vqz@"3t%AۋZ}8;up/ߎ/~9x[vwG%LJ9;=pr܂gO>߽?| +^2P:n#w_K3v>]~<98c>}8=oAGgPK]3n/''XU# O?~v/ӓ<-;%N+w?Srbu_Z;^n8"V〼=;}Wp{PpYlFSuqmVTzo6\&R$e,m_}դ:un1VbŽ@s9yG9.ϤFVQ\Q}#"n-gCK2I;L#nJJ'#I=Ds5P4@4Pb}k Ck" W|TkP42hOh# Τױπw><7JuL:E]3k&X~?pZ?0u0=<lR3:(tB 8u`aR4E+&CWr.|BǞ=؁wL SRO4 ?9OLV#+bs97I;o1B!qP H[ خz@ԄmX=7cavSӴAO'B("k-8.-:-OHEy c_eeYw(;/N @L@S<;mfs٣pS J̴Ϣ&xcu!J@WH(mt('F+J1:YI|({Q]^VK;aum bS>Qt,La\ó;Qu8Q ~K `PSgﱍ5Bej[{t#! ? 'V~WʬU'_ /CIgW80>E dVGhT%J}W^|XDMc*r܊4ⓏN QI 3#hRֶߢA]&pfKdP@H5pRb?JB:nIm1jqKCXKɻb95G,oqH~_'Իɮ)Mc?U;Rݝݤu\"eXg۞~vA^WxX{/$ 9\a||OQ. Iy _@s3*U?ma{ xT*~[ME|%>smyzJvNjЂ*`F]sà|_><}Q_~Zo4APx"Z X1ʝ>4seqXPU$B C#D ho!SoƖVx BqR$?MX3 D:%,HB5iWMuZ.<|O~٨ /aLVFFVeDuNZq ^`Fκ? oo?dcWkԯ4uF]'vQ/rFۆ"E6&k:i!H_ K?ay.mI@qb5H 7,?eI|PxE{#} P?baW~A> 3Ҕg,chΓLpފIX&npc^. fvԄ~Ԑ®|0:BL,L~拚)TWӆdZ;@"8bHBeɥ5aG8F@'ܸ] o%6a CyX׻vpѿQޱ4K,Q@u>gho񿁏‚93YϠT[˲瀬`4[gpwsetbe L%qO#.ҥuMґHunVEvww&?(俵rF.\ {F +t`[Z] 5ށ4r[-6BW(]Jz\Cu>D$)L\=7K&Zͅ |D '*:+ ; Xx.j;B߀aX>o8!`]Dݭi~R "bI_JrGN0i0EK،:eR7PS6;p,&Oꖈ1FEYvJX: =sJ-`M1[>\[<5BgӠ|:H80FZܠYvh!0XpI> _^e-H< ﵑ|ECt:];n;a__[elDsFifPB>ahGګ0htI@U; 9vGt UͲ/(d%SL}u7ds-vMp.adN2`.pj1h$ )#)[ -Ąq>IlQ)Nd;՝l4T14Paq׸ ^aV Tζ'. U, twPzcgoi pbNjPE[EVU! 0B'5s<ӑR@)h,!b}C{jU?ܒJHc@@. #7*΍ˮVu !z.X $}>U 6?ڂ{؜P}E( <ѱׄ:"8lLtT~,:ր$L OH/L& wG=W\wsq¡ Gd%t>B͟8 R31@Uom[.كcjv(!> )}Q)B`PrP˂dX4 W"? "wǦnSHig*MB{LoqlwT_4+SL3k{߆7;kw1G=#ù1 J,ߐGA#`0_k:9|tNXb,IcH z~XCwad㣻@(QvOJ{ksaZM[ͩRZe>a۸՝ BjHVC{8-JXPI>r':P.m\f#C˄Vi-m_yQ 6.gd A;}\CZo0aΐFC[ϵ0~ƵjKX8Qz=qpoP@, 6꤬܋U-t/K%t5z#ݡB&FߣxO51ŀ]S[7OSGс9Nlql+nl}AfFW|U4E{crtNIk/;EJZ7̎O3!Ә, #5! |8B^g/)Ե{aRvL'6do15h4C4K$uߠWqW8.oh-#m`6:Z-vIG$BFn]ľ@QpZ '}3L#ġf/UXTzPbm1m9qDC,L xF)`X{.i`Ѿ$dKLDma[JS$_uPtL*]]+!~A UOvJ{ ߄GnQ7|Gk+{"5^sdIąvq*[ɶAvCbةp&Þ0V! ȴ U3M:neH49݀?)`Ɔ,ey?{T"Ws?͈~sY-{w.xdzu?ًJO)cz-;!4) W߯ՔL&!7@H9-K@ODe%3f`[&V`ґɩ#`s,7`~ 9؇?,;~ _FPhj=I/E'%~{NKs~1)*6ZmZP)8ҿxA_*!Y)WV$! 8Aq2ETO#i٫5+YQJ >\1!"t_̪;.ݲ8ͶAqVVS_ `sl$!Lf!bQ&`W6NGgd G{f%rJ*1N6SMHgZRC@%: 0K_hˮmy͟ć.7ES@'͏>IGώ"m6;%BvO(<4E~9.W/._ߟ?qt&RfV&YF>5X\{߰z[ < -k+#H‘28c]S-!E-'qR"(J4Sɱ).㦖7 TFd7ifwI='5cu9s S`yŭ%tԦtE8CU8{ت|5Ī=@/wgbޮ*okA-~y'rk x\*%?#1^yu' =!Qk$Uoo\Q;;Dc} p!1@c-(H5 LK5L@O .̵Z~nPqC&ay78;8:5S<2ͫON6Z'SH,!QߙPg_?c–L~ kQ26/57JF8O_ɠOyUODu{{]:.'T |zq+{j)oa.O1pv׾H:9-ϱEf>d:F :\G[Â$lYH],L?n 2NtxUZ.2=x2!!V7<@%w5ha܃r*nkS,A"8|ȺbN]G륞֧?/ S0nD~|aЅȱ;`+0R1 ]Uk"͝0P9٥0< &ỜNґOa,,s;IŢ;Il[̌riP{^uO2?") B9wNĮG G\)/dATg4(WؖgX@Tq&\&>ܩ@ÒتPB1eoU2{EҤ{ ZI`Xj3^Gs{{ +o \NLQ4飯êyeM*#TUpJ:I]/GʲJ񟍉j _%T)ap*â̬7*tX BO/?{ ~QAKݶ}Y?Du/8g j0~"ȱjx5NP(Pd>gVTV=+*Lۙt[cgJϨ~c6,ڙ`/%Rݚ);#3;6Tg)l4-&)uwVߨOjk#?\7(\װ݈pBǁZge6hөz@孮1,@ -ˑb!w&pSw.t ]x;9qR(&Ry݉0,ة>_oGȔϻRvn,Fv=_\?GD"<$g.œG&*ZD&$,N2iEqֺ]K3 )/%xS^XOeGcn[֔%&mߙMi:-5=7](Ȅ$0 Qb+U1m`<,mw?iB;k#wA,7<ȧ_c=Jcw,Ⱥlf9ͮD؂N egI.46-Rɔյr ]]Nz>mOͣ~k5A=P/C:FjxOѠSb7߂>c9WauyL$1FauP T9 /EoGvA-7XGW*%$ H16/m3ӫk%=ns ,2@Ǝ@ǕCe JK%*N3+X >epC it|h1kOy&,DYHcme$O"284"<i\Z9zS+Wye1K_dTu.e}cB3\ <_PآV٭)\ߖgI.q f`,p[vRAGL‡J֥L/8{S#C3{ Ygp!6sclE!Q"\$e6NZ'$=iѷl_5.a{SLj. ngۈZm={lu<=F-u|WqC}4J ۩h_q2?O:O36e!E = ^w _=c.x=ֵ1(!3M},1,G;LJ1,fʳWDB)y)|DNsTh>(CfT wڧϴe_G4[]//_o4&=y|)`U(H%//lCJP3Ӽ jn|__WL0q `m8Q]I_I5P~ܯȱ_ǩk&k{; ?#Q>$@h fr f*= f|T(mr{N1[ -i|tk/iԠG$I4$3P[Ǣp&犀~OܦK;*obmd3v>[ɻ}.ɳ\aTy<_@0Q |㣹6K*ZP&%#.c^Pd[}L7:+Ie)< П™j_(E5L9#{J^!z\ s i:aݭ)y_3f;PiYIfbr(z> mP7qWU]|1 תIo? OLP1"\6 JX Եz_{ 88!L~v~B"w`. ZD>fڝ2 }4m|Qq}bD&:i3-I u~J_dRMUy-Qe}tlK nؖfv>nc2X1.%@Q&2ʲ:qU Zi=C15 jDW?j [d4sezI_ZvT#ㆯUT_6 4A.6;Cu RL%jYzarhދ52JyR0\ۊ,v}'XF3ɀ4_F:uԈu=ŸK¬m4K w)@;?XCJa:'ܹrVVWM"i _S7Q\n*ʹG푒? ww` )H 3GwDB=2TzhR2O:H@uAN`4اunܽ|rF OZ]j2}7rv#tvrދ Y.elasticsearch-ruby-6.8.1/elasticsearch-xpack/pkg/elasticsearch-xpack-6.0.0.gem000066400000000000000000000500001361161326000270570ustar00rootroot00000000000000metadata.gz0000444000000000000000000000247213224361270013443 0ustar00wheelwheel00000000000000QZZQo6~ׯ'INf+`C ÆAŚ"9rboߑ ҈T#x;*kjhMi@݀,Zn`yuЏdO4vTJ.eؓ~~Ks Z>1@30Jj{S0⻰!<Ne[0ȏb-6QոeY0G[D:g@⏫idkQ),nG%mQyGt}q5Vzw85%BSw}ZӤ+S@Gtl%vh .oqIONe@;KOGi[M*]KZXB|,[ b-3/?p뛋֑/_] HkhJIXڀ.@kEXٲ8`(z XN!8UM׊pcb%^3BQY[RL@6L@B &@V.#8V5dP3|aS2u.>b4ep5V&5;8qQl~EcSWHf{K8s3PT5)Ɇw6S8 1a^SR0` ѴcfvW7$Lƀ8mXCpWfC$b耇5ᭉfBHUKI gG3Ίp1hۆi7B#sVn@bč m퀁ı^wΐa|^e[79D`3@@BMæ0>rRwg$GLDSP1|Ja YW-(t/eXLYkfnSَf_ʧM_*FgI L#hkx4NVsghƐ6>>y0m~ eA .oN/vA"M>Y5{̵f޲1r5XJAJw8V߽r qicuu cnLFt5Crؖ Uϟ/THkFXS؍l<ƤuP }sjL'Yd#rjxreΰz:f}5qᡃ7؎e3Fr@ImkGicPWvOn(' ErgAQO0y2 ֵ̞-rZv:EiM0GUr$qaPnj$2]]3jX^e(6;;6;:cNO~>:l엣N>3HqWv+"ki쌝}8>jóȾޟ!C' Y0wӃv_c?}a)Y?lJik?/Cv1?9 oC?nQGpmr9a2Q;Om|ΏNc3NޟmZyz}YOΰC~8=yWaw' |-rf$xeǐ 3<ߐ봽]Oo4 kV@|)h].`X=0 _\9xs]2=^fK JwbۀRJm&;2P}6roް#aszr*9i<Tj/~6 +hŘR* Bkf8 fZ0TORD^XGDEP4@nj5)̨B2NӊL^|F=\!1nP H&Ƥ׵zϐw?erpʌ{%S^|zdk87>7]$h,B:4]3Xb(ЯlFc!0EV#2aP?ĵF@~]Hp˴kM7+j!%D}ڈ;C~Idq.<\ >y@&aې$ simYTvh9nժcYٷ@7vF/?r\s' +'!=vG%u$-{ЧY

Sî|ƖsV4]^-pY r6#`v υ( tP넾3R]/5/h̆o4{܇?uirX^qPʂcPV@WHX4U? arUjU~2Бv*Bh-HqVq22eD(R3Wj2h5\iTalTESTZ|2D#= |t U5T%ͅj UAw5Eo(_ @5 k`ώΊKDdΫco"iafg*CS`j p , o|| 3ݴѹpJ?@~T\"ST;(U hx_.P/»,OR^Ds:j} -toe?a{~0/(Ms|M% 3nWLɷW,TZH h I?+Ƽ@G*Lt FdR _nI%򯠗ͥ ;oprbH{B.#o_~]v@WcoN [GeyL*J=,Bdدօ|EwUAR۶lLߩ*5c #-{}2"X qZ*.H'%XEymCۧ'w )LU(KTooөf KPǃY C:?#izA?[٧b`d߁4JD$6)n]rJ{ jm/Wġ|UQ) E CTljzc7w"{t+꪿TýntRT(&mtC Qɻw fyէs}\X *4W3SYU MV:4AtNE`wVy;hb` @$4ua DU){<ǶzsИHnߜoaߜZ -zdFT2Ik>?;?:|?;g aogVhɕ'*)#>Վ5(@*\=mg8s2jV GrXߨ#nw-\o/%P#2}vƚ;*n+GNg;C`p?'3$͕ktkH+;?Qu&5haB'A1{͓KhFhdz#D\iBDR[Kvh-W&/3e2S涼;B.ONIO]-X|e1{hk]c=L iF_ -YqmUS戉HWT )eߖ&ĚFU|rnE+ ?ծ^CƸ R?:=4%Qarp887̟z =wjMM@e:3P+@NRbAv,f%{_ҖZ5mG9!lYd ?Gh_0@|Qo;;y_k÷PŅ+w {h~yI{KQvkXZTR/1fZ@ P]{•'ՀeԚ ";BARu3/|eE}ngu&7P)GRB7tb[:K; INбL,@ :t₇PK-vEc 1:]kxu|=U1Gzh6Q;It\s:A5=ErS}+i({+1'CvW˽X=?WLܜ 0?ݛШ'%x?;Q.ۿww_/i_q4JY%4,<>9bG_ W!GL%9BQ')8s*C@ \x5BƚN#! yErv"~Ju OJ Dw/hFZ1Hhz;vKFSOJ $TOz :#:Yέ|↑F ݣwHNԪT JUDžV_6]F@e`ٜ|`o8>7ZLpn@!=gٴn[/Zѓco`} %ZZؾCˤ< Ʈt\FxL*Qˈ:WÇξZ|UC 3* ְ$A"Ewogh^9' !Mnٿ[mH}1hI X-A$z:싂TL1 Խ/qGy2jG pr䇬EﳙY7WA YC7d|CJ j ٴLJN =QC-c < oq[(5lב)R$ŀ:W-CH#7V EUeeyxW^cqw!G `}1cD?;G$cr}]H=/sb#Z؊.m$$Px:[Ko |7bRWʺJؕG_ȌE;J;pNE 5޴fpR-rn2ɵ Mp~ spu}_QN޽;y<8Cݺ"ѹR|-dߎ劻.@\وst!OZwa@_>9{ m{^ HCq{mEꩲ%I;3hdSo4H6(S ް =VkԘ@e`&z{r5R wKi@jKK%jBhi%5 מ{԰D?5y܅}:a||4vodjlbUu+ϗK#ڂ휦(U4E[cp\ =W4guGݒ̰D7ЦώRKss:>l ]#t ؙBTg/ GW70F/'v1QZj19pHE(˘q\ŵ|zX {.ja޾h9;rAlKt{:(k*[۴b䴄խ˕DC~A Vv!Mzk񈶂op:xg&az:ֿ,]L@d AYJ:E,*e\m`"K"I}(<(BetT -G4C$TĚ{ +6AfX#F4,{0ui OwC+pM6caNI#A֣фG_*%5MiV#,t,?[Ӂ{YdyER^g bD$L")_9),GFE3fvz$n}C)Mj㤀?j?&!P8֜1z&zOq7syuxHD_>rUϰ+2|qy2@(d =0Όr__cGo[Ee?7Y'{{3#2x@i} |TO$Š#_}m]O.(ղO~:Me& @\]C. -j@ ; W;p"3dW x<7:*â@,7w^H)RZ:STe[I.Lg= Q q$U]}c iNA?jGdl*խ'p%N%w @_hMnFjFCw#v7<aꑈI%P2n?aNEw>qFr&n3 0wPt\~4ABO\hW#ik $3θ늳Ut(]m`[E_"1i2OhSg},AKwz CUXWEpPɸl!+2fSH4U<\zVF_Dz ?,H1x^4v͓,$-f8OZmd>ջ"kBѴPF0#Hu9:-$i-'ԉwd ~H&_, %@L~UƘY (r= Swoˏwl#i\qVvbz]w;L"@ 7F=X"$(gl%}=VPbhh ŝڄ'D"Mci^|pC:h Ŵ\4],]QrC8Qɣ8 e4PM-TL *N*'&L7p Hc#t^R_ԤG*m Zm<y|ɕ.Θ<áHaMuc:Ots@&Iq&Hw`K$] ^D1Y"6Z[aM[`=B$|\\yv8c`%CH: '23{eq*@lj=F?(p%⥭2V)I%%gu T$ҝ_ <>ґᔁHk^ O0j(7J^x' БB@`@?Ţz''PVՠ$f| Gg8/sτ^¸0Xmk3=6GVݙ k}}|h29`4+'^DKԧ52sqa\$ݥػe^ eG`3 6gniݘxqwz1 lr}G^-][G7*eH>a #[ |%WR8*D~i:qC\N.!_ϗFSꁡih%| |\?˛vjP=Í=abq{QI .x_%p\` lCx ?D^:eM~_h/ܿ@9V.|ޛ˰S+g_dWmx wۘP+_E [22^LH%&F ë$#j4v?W2 ׮0.]8~K.GV)pꊴs"08gxȍܝئ#â=?-0kz&5=)P~̈́١m8ܧ*l}?&,0&&0OouVnMH|_ǝTL꣣g+g]s$q?՛d1(F34H @_ãC0#6\ԩ$ryָ#I2<&qБULme5zj/x}*J8cMԁ~H)܋N Q T2J)NX0\=]1b\3EnEhD9;efi÷m-ȸ"B9BC6I1GX?Rm*Grav$tmKXjء5[kgLъA(8C CtKUY^t2ȣ/ CȜrB4wY#3CE:$]Z?Lg,%\Lԧ!P8!cR(E$IinBNc1 Sq;zpx2ͯu~5w/lA>*zEaa`(3q|Zbzg.<r9vk/`f57)OwN |y=VãĖբ$y|(Pmr*%0Z0N NT߭W?w \f[$`抷/Yez}\UT5Q_#Dف #}gzz,"TB~96tIc9? 6v4 h{ntwo$ZW~->(+G~v%ϑ&:4`5n_ [C)uRE7% z2jGme?AhnXP[ɷ0ҔE?%P3; s%^Hܙp`Hc-GN%Wb{f件&EP99)Iy=h:{jtΣ)Ŭ|1Ift]tuxni5H#v<ܓ@ٔPB2'ߔ@'^` g[bK%_$pbGj_m&!l)@v k*g|o0.3%O 㖺k 3^\poS}ѽOJψ8;e ɘ;Zs#r@L4#Y*YdnlY96K.`?m'׊/#`}'1z^?nS`d _Wc1UkfEPе2|^oBI{53 xn!AcXFOYܗtwmJ٭g_ [yM.l^ַ2]/{T:bϽZ#+J=\! *Yٵ"l:hol.v;ͨN=ׄ+Hwn" \YOe]ƄO6/ҹ__K(c:Xu p F;n:]#t;_\6~7rBHQ#'d[ ^<`FqvĞ daiˠř<( Zi [RFu>%POG#zWk[̱F\rjG%Jf1cGOx={|uH+9"qGH~(r0ĂӈFKX _`s겸 *]`k_ۺ6(*q *Ev+񘽎rM̝tQLxNHr_YiޣaaOڵPw_{+lIJeOpzx)d*x=4[ZȮנKM'E6kY > IKBB-Y3|@vL/`]:ru QbFqcZJ"dveXr{d3</ż0~5c}(2s.xhJQ$[IB2uBYS>\h#pd:Ч(qvn20ܽs/@ Txr7C;f|juZ]0P6Pzu喘0n;E[n1ౡ|"[.G=x[,G1J) , ̼ ^eslS{3ؔmFB <Yl'5$j"E#p(wabVЕ[4 YIIlX VPG!"p B}ꣲtl62hcְ^LE-ѯmB*[@ 9f~mL;ߔwu/ߙtGy[$ُ3|)A+@XthLbcjzQ ]O2<XvoIF}݌o? !~hHl稗!Q;nv0X`vip/cm _Agd@=<*y;#~.zt4K}U/ӫbF%_ YF"]OպC`pQ]q_Zm4 ) @UkNBb<)_h5Z8)wOXZ EI $9r$n\pBsjyn ;/JIg+ N.rw[js;3й :OK>֓hq n6'X9ZGῤ!~IbIG}ɵ'ۢK6=]ѣn5 _mZs_?IDtNj_F0gY7gUNH{M"ϊLf9HØ RLi>EDŁV(ܤ֦EG.L?(ЂtjJ8VX}fs~ 2^-?-.Ovb1 %zD\hh rRQSeB`P@*_u'o/%f[v͇$yJdIe5RJ#;,kE?hU?6J_iav1sZ߻{(kMc1Փۓ9;&IkGw݄ۏ 4_ ?w7SG%u9fROwOfR?+St2= 9$vd?t @z4_@rj:qFDDd^2m٥릷F S_o@Ǔp=r}f߯Hb/VHf!'O[ϐy㘘1h \Ӗ3Թ{x0Q0hǕr83m~qW!- ]/_k4{@T[!`+%QN!fI'E4#A՛ƔE$@0}L{TWTR!&0 ̖y_mܡK4Sg-/6-t?֍{.ٳ04Cr]6_@y,b;zOԏ2H_rQ;agrZġtL7W3$ْ>-FlDDɍDrΓ-ļ 1e5٨D1f2GVA_L3zũo͝*ҁYĠz5CJ! {;f~$$YIE谤NTAVfF/&fcУCOd@tf2d3) 68K6ߍš|/OȢ˽}9Ckbp֚=&0~v)Mh10hK?ח!FqCJim+o.5@l)m@\W̽}\BטZK lh{Zk[FrnS X q^NH7C d)Q|j:qy?&|/`Sjz7OO>z\bDԛ+җmb1&EjZo re b(as«>Oo"{FFjr?t"]ݪ 4OzD0qg0+tN bͽ`e{戕nꝠq_u'3Zr\kLP%?g@LԑeUv_'F#;aS LH+eϮug*c?$. u/: ܍/=zhjIJACB/?qG3"~;=acO %a I;[(#WjΫ4WWe2uײS#ۨ72z2R1Uq$,`M D\ WG-f^-1?Μ}U\D[pI=;:yLj++}checksums.yaml.gz0000444000000000000000000000041413224361270014603 0ustar00wheelwheel00000000000000QZe9R0 E"#ْ-LEä(vy{z=~]IBsѭd&-/_ "Wj4dgtVXKs3q#8'PXs.Ȩygʜ?gn4RV926U0!Ml)c",> #:ԄHj{X}{ٗ*|elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/000077500000000000000000000000001361161326000221665ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/spec_helper.rb000066400000000000000000000166551361161326000250210ustar00rootroot00000000000000require 'pry-nav' require 'yaml' require 'elasticsearch' require 'elasticsearch/xpack' require 'logger' require 'support/test_file' require 'openssl' RSpec.configure do |config| config.formatter = 'documentation' config.color = true end PROJECT_PATH = File.join(File.dirname(__FILE__), '..', '..') TRANSPORT_OPTIONS = {} TEST_SUITE = ENV['TEST_SUITE'].freeze if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] split_hosts = hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end TEST_HOST, TEST_PORT = split_hosts.first.split(':') else TEST_HOST, TEST_PORT = 'localhost', 9200 end raw_certificate = File.read(File.join(PROJECT_PATH, '/.ci/certs/testnode.crt')) certificate = OpenSSL::X509::Certificate.new(raw_certificate) raw_key = File.read(File.join(PROJECT_PATH, '/.ci/certs/testnode.key')) key = OpenSSL::PKey::RSA.new(raw_key) if defined?(TEST_HOST) && defined?(TEST_PORT) if TEST_SUITE == 'security' TRANSPORT_OPTIONS.merge!(:ssl => { verify: false, client_cert: certificate, client_key: key, ca_file: '.ci/certs/ca.crt'}) password = ENV['ELASTIC_PASSWORD'] URL = "https://elastic:#{password}@#{TEST_HOST}:#{TEST_PORT}" else URL = "http://#{TEST_HOST}:#{TEST_PORT}" end ADMIN_CLIENT = Elasticsearch::Client.new(host: URL, transport_options: TRANSPORT_OPTIONS) if ENV['QUIET'] == 'true' DEFAULT_CLIENT = Elasticsearch::Client.new(host: URL, transport_options: TRANSPORT_OPTIONS) else DEFAULT_CLIENT = Elasticsearch::Client.new(host: URL, transport_options: TRANSPORT_OPTIONS, tracer: Logger.new($stdout)) end end YAML_FILES_DIRECTORY = "#{File.expand_path(File.dirname('..'), '..')}" + "/tmp/elasticsearch/x-pack/plugin/src/test/resources/rest-api-spec/test" SINGLE_TEST = if ENV['SINGLE_TEST'] && !ENV['SINGLE_TEST'].empty? ["#{File.expand_path(File.dirname('..'), '..')}" + "/tmp/elasticsearch/x-pack/plugin/src/test/resources/rest-api-spec/test/#{ENV['SINGLE_TEST']}"] end SKIPPED_TESTS = [] # Response from Elasticsearch includes the ca.crt, so length doesn't match. SKIPPED_TESTS << { file: 'ssl/10_basic.yml', description: 'Test get SSL certificates' } # Searching the monitoring index returns no results. SKIPPED_TESTS << { file: 'monitoring/bulk/20_privileges.yml', description: 'Monitoring Bulk API' } # Searching the monitoring index returns no results. SKIPPED_TESTS << { file: 'monitoring/bulk/10_basic.yml', description: 'Bulk indexing of monitoring data on closed indices should throw an export exception' } # The test inserts an invalid license, which makes all subsequent tests fail. SKIPPED_TESTS << { file: 'xpack/15_basic.yml', description: '*' } # The test inserts an invalid license, which makes all subsequent tests fail. SKIPPED_TESTS << { file: 'license/20_put_license.yml', description: '*' } # The test inserts an invalid license, which makes all subsequent tests fail. SKIPPED_TESTS << { file: 'token/10_basic.yml', description: "Test invalidate user's tokens" } # The test inserts an invalid license, which makes all subsequent tests fail. SKIPPED_TESTS << { file: 'token/10_basic.yml', description: "Test invalidate realm's tokens" } # The number of shards when a snapshot is successfully created is more than 1. Maybe because of the security index? SKIPPED_TESTS << { file: 'snapshot/10_basic.yml', description: 'Create a source only snapshot and then restore it' } # ArgumentError for empty body SKIPPED_TESTS << { file: 'watcher/put_watch/10_basic.yml', description: 'Test empty body is rejected by put watch' } # Operation times out "failed_node_exception" SKIPPED_TESTS << { file: 'ml/set_upgrade_mode.yml', description: 'Setting upgrade_mode to enabled' } # Operation times out "failed_node_exception" SKIPPED_TESTS << { file: 'ml/set_upgrade_mode.yml', description: 'Setting upgrade_mode to disabled' } # Operation times out "failed_node_exception" SKIPPED_TESTS << { file: 'ml/set_upgrade_mode.yml', description: 'Setting upgrade mode to disabled from enabled' } # Operation times out "failed_node_exception" SKIPPED_TESTS << { file: 'ml/set_upgrade_mode.yml', description: 'Attempt to open job when upgrade_mode is enabled' } # Expecting "missing" error and getting 409 Conflict SKIPPED_TESTS << { file: 'ml/post_data.yml', description: 'Test POST data with invalid parameters' } # Expecting "missing" error and getting 409 Conflict SKIPPED_TESTS << { file: 'ml/post_data.yml', description: 'Test Flush data with invalid parameters' } # Expecting "missing" error and getting 409 Conflict SKIPPED_TESTS << { file: 'ml/forecast.yml', description: 'Test forecast unknown job' } # Non-zero length node_settings field SKIPPED_TESTS << { file: 'deprecation/10_basic.yml', description: 'Test Deprecations' } # The directory of rest api YAML files. REST_API_YAML_FILES = SINGLE_TEST || Dir.glob("#{YAML_FILES_DIRECTORY}/**/*.yml") # The features to skip REST_API_YAML_SKIP_FEATURES = ['warnings'].freeze # Given a list of keys, find the value in a recursively nested document. # # @param [ Array ] chain The list of nested document keys. # @param [ Hash ] document The document to find the value in. # # @return [ Object ] The value at the nested key. # # @since 6.2.0 def find_value_in_document(chain, document) return document[chain[0]] unless chain.size > 1 find_value_in_document(chain[1..-1], document[chain[0]]) if document[chain[0]] end # Given a string representing a nested document key using dot notation, # split it, keeping escaped dots as part of a key name and replacing # numerics with a Ruby Integer. # # For example: # "joe.metadata.2.key2" => ['joe', 'metadata', 2, 'key2'] # "jobs.0.node.attributes.ml\\.enabled" => ["jobs", 0, "node", "attributes", "ml\\.enabled"] # # @param [ String ] chain The list of nested document keys. # @param [ Hash ] document The document to find the value in. # # @return [ Array ] A list of the nested keys. # # @since 6.2.0 def split_and_parse_key(key) key.split(/(? ] features_to_skip The names of features to skip. # # @since 6.1.0 def initialize(file_name, features_to_skip = []) @name = file_name documents = YAML.load_stream(File.new(file_name)) @test_definitions = documents.reject { |doc| doc['setup'] || doc['teardown'] } @setup = documents.find { |doc| doc['setup'] } @teardown = documents.find { |doc| doc['teardown'] } @features_to_skip = REST_API_YAML_SKIP_FEATURES + features_to_skip end # Get a list of tests in the test file. # # @example Get the list of tests # test_file.tests # # @return [ Array ] A list of Test objects. # # @since 6.2.0 def tests @test_definitions.collect do |test_definition| Test.new(self, test_definition) end end # Run the setup tasks defined for a single test file. # # @example Run the setup tasks. # test_file.setup(client) # # @param [ Elasticsearch::Client ] client The client to use to perform the setup tasks. # # @return [ self ] # # @since 6.2.0 def setup(client) return unless @setup actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) } actions.each do |action| action.execute(client) end self end # Run the teardown tasks defined for a single test file. # # @example Run the teardown tasks. # test_file.teardown(client) # # @param [ Elasticsearch::Client ] client The client to use to perform the teardown tasks. # # @return [ self ] # # @since 6.2.0 def teardown(client) return unless @teardown actions = @teardown['teardown'].select { |action| action['do'] }.map { |action| Action.new(action['do']) } actions.each { |action| action.execute(client) } self end class << self # Prepare Elasticsearch for a single test file. # This method deletes indices, roles, datafeeds, etc. # # @since 6.2.0 def prepare(client) clear_indices(client) clear_roles(client) clear_users(client) clear_privileges(client) clear_datafeeds(client) clear_ml_jobs(client) clear_rollup_jobs(client) clear_tasks(client) clear_machine_learning_indices(client) create_x_pack_rest_user(client) end private def create_x_pack_rest_user(client) client.xpack.security.put_user(username: 'x_pack_rest_user', body: { password: 'x-pack-test-password', roles: ['superuser'] }) end def clear_roles(client) client.xpack.security.get_role.each do |role, _| begin; client.xpack.security.delete_role(name: role); rescue; end end end def clear_users(client) client.xpack.security.get_user.each do |user, _| begin; client.xpack.security.delete_user(username: user); rescue; end end end def clear_privileges(client) client.xpack.security.get_privileges.each do |privilege, _| begin; client.xpack.security.delete_privileges(name: privilege); rescue; end end end def clear_datafeeds(client) client.xpack.ml.stop_datafeed(datafeed_id: '_all', force: true) client.xpack.ml.get_datafeeds['datafeeds'].each do |d| client.xpack.ml.delete_datafeed(datafeed_id: d['datafeed_id']) end end def clear_ml_jobs(client) client.xpack.ml.close_job(job_id: '_all', force: true) client.xpack.ml.get_jobs['jobs'].each do |d| client.xpack.ml.delete_job(job_id: d['job_id']) end end def clear_rollup_jobs(client) client.xpack.rollup.get_jobs(id: '_all')['jobs'].each do |d| client.xpack.rollup.stop_job(id: d['config']['id']) client.xpack.rollup.delete_job(id: d['config']['id']) end end def clear_tasks(client) tasks = client.tasks.get['nodes'].values.first['tasks'].values.select do |d| d['cancellable'] end.map do |d| "#{d['node']}:#{d['id']}" end tasks.each { |t| client.tasks.cancel task_id: t } end def clear_machine_learning_indices(client) client.indices.delete(index: '.ml-*', ignore: 404) end def clear_indices(client) indices = client.indices.get(index: '_all').keys.reject do |i| i.start_with?('.security') || i.start_with?('.watches') end client.indices.delete(index: indices, ignore: 404) unless indices.empty? end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/support/test_file/000077500000000000000000000000001361161326000256605ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/support/test_file/action.rb000066400000000000000000000067101361161326000274660ustar00rootroot00000000000000module Elasticsearch module RestAPIYAMLTests # Class representing a single action. An action is one of the following: # # 1. Applying header settings on a client. # 2. Sending some request to Elasticsearch. # 3. Sending some request to Elasticsearch, expecting an exception. # # @since 6.2.0 class Action attr_reader :response # Initialize an Action object. # # @example Create an action object: # Action.new("xpack.watcher.get_watch" => { "id" => "my_watch" }) # # @param [ Hash ] definition The action definition. # # @since 6.2.0 def initialize(definition) @definition = definition end # Execute the action. The method returns the client, in case the action created a new client # with header settings. # # @example Execute the action. # action.execute(client, test) # # @param [ Elasticsearch::Client ] client The client to use to execute the action. # @param [ Test ] test The test containing this action. Necessary for caching variables. # # @return [ Elasticsearch::Client ] The client. It will be a new one than the one passed in, # if the action is to set headers. # # @since 6.2.0 def execute(client, test = nil) @definition.each.inject(client) do |client, (method_chain, args)| chain = method_chain.split('.') if chain.size > 1 client = chain[0...-1].inject(client) do |_client, _method| _client.send(_method) end end _method = chain[-1] case _method when 'headers' if ENV['QUIET'] == 'true' # todo: create a method on Elasticsearch::Client that can clone the client with new options Elasticsearch::Client.new(host: URL, transport_options: TRANSPORT_OPTIONS.merge( headers: prepare_arguments(args, test))) else Elasticsearch::Client.new(host: URL, tracer: Logger.new($stdout), transport_options: TRANSPORT_OPTIONS.merge( headers: prepare_arguments(args, test))) end when 'catch' client else raise "#{client.class} does not respond to method: #{_method}" unless client.respond_to?(_method) @response = client.send(_method, prepare_arguments(args, test)) client end end end private def prepare_arguments(args, test) symbolize_keys(args).tap do |args| if test args.each do |key, value| case value when Hash args[key] = prepare_arguments(value, test) when String # Find the cached values where the variable name is contained in the arguments. if cached_value = test.cached_values.find { |k, v| value =~ /\$\{?#{k}\}?/ } # The arguments may contain the variable in the form ${variable} or $variable args[key] = value.gsub(/\$\{?#{cached_value[0]}\}?/, cached_value[1].to_s) end end end end end end def symbolize_keys(object) if object.is_a? Hash object.reduce({}) { |memo,(k,v)| memo[k.to_sym] = symbolize_keys(v); memo } else object end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/support/test_file/task_group.rb000066400000000000000000000241501361161326000303650ustar00rootroot00000000000000module Elasticsearch module RestAPIYAMLTests class TestFile class Test # Representation of a block of actions consisting of some 'do' actions and their verifications. # # For example, this is a task group: # # - do: # xpack.security.get_role: # name: "admin_role" # - match: { admin_role.cluster.0: "all" } # - match: { admin_role.metadata.key1: "val1" } # - match: { admin_role.metadata.key2: "val2" } # # @since 6.2.0 class TaskGroup attr_reader :exception attr_reader :response attr_reader :test # Initialize a TaskGroup object. # # @example Create a TaskGroup # TaskGroup.new(test) # # @param [ Test ] test The test this task group is part of. # # @since 6.2.0 def initialize(test) @actions = [] @exception = nil @response = nil @variables = {} @test = test end # Add an action to the task group definition. # # @example Add an action # task_group.add_action(action) # # @param [ Hash ] action The hash representation of an action. # # @return [ self ] # # @since 6.2.0 def add_action(action) @actions << action if ACTIONS.any? { |a| action[a] } self end # Run the actions in the task group. # # @example Run the actions # task_group.run(client) # # @param [ Elasticsearch::Client ] client The client to use to run the actions. # # @return [ self ] # # @since 6.2.0 def run(client) # Allow the actions to be execute only once. return if @executed @executed = true do_actions.inject(client) do |_client, action| action.execute(_client, test) # Cache the result of the action, if a set action is defined. set_variable(action) transform_and_set_variable(action) _client end self rescue => ex raise ex unless catch_exception? # Cache the exception raised as a result of the operation, if the task group has a 'catch' defined. @exception = ex end # Consider the response from the last action the response of interest. # # @return [ Hash ] The response from the last action. # # @since 6.2.0 def response do_actions[-1].response end # Does this task group expect to raise an exception for an action? # # @return [ true, false ] If the task group contains an action expected to raise an exception. # # @since 6.2.0 def catch_exception? !!expected_exception_message end # Does this task group have match clauses. # # @return [ true, false ] If the task group has match clauses. # # @since 6.2.0 def has_match_clauses? !!match_clauses end # Does this task group have match clauses on field value length. # # @return [ true, false ] If the task group has match clauses on field value length. # # @since 6.2.0 def has_length_match_clauses? !!length_match_clauses end # Does this task group have match clauses on a field value being true. # # @return [ true, false ] If the task group has match clauses on a field value being true. # # @since 6.2.0 def has_true_clauses? !!true_clauses end # Does this task group have match clauses on a field value being false. # # @return [ true, false ] If the task group has match clauses on a field value being false. # # @since 6.2.0 def has_false_clauses? !!false_clauses end # Does this task group have clauses on a field value being gte. # # @return [ true, false ] If the task group has clauses on a field value being gte. # # @since 6.2.0 def has_gte_clauses? !!gte_clauses end # Does this task group have clauses on a field value being gt. # # @return [ true, false ] If the task group has clauses on a field value being gt. # # @since 6.2.0 def has_gt_clauses? !!gt_clauses end # Does this task group have clauses on a field value being lte. # # @return [ true, false ] If the task group has clauses on a field value being lte. # # @since 6.2.0 def has_lte_clauses? !!lte_clauses end # Does this task group have clauses on a field value being lt. # # @return [ true, false ] If the task group has clauses on a field value being lt. # # @since 6.2.0 def has_lt_clauses? !!lt_clauses end # The expected exception message. # # @return [ String ] The expected exception message. # # @since 6.2.0 def expected_exception_message @expected_exception_message ||= begin if do_definitions = @actions.group_by { |a| a.keys.first }['do'] if catch_exception = do_definitions.find { |a| a['do']['catch'] } catch_exception['do']['catch'] end end end end # The match clauses. # # @return [ Array ] The match clauses. # # @since 6.2.0 def match_clauses @match_actions ||= @actions.group_by { |a| a.keys.first }['match'] end # The true match clauses. # # @return [ Array ] The true match clauses. # # @since 6.2.0 def true_clauses @true_clauses ||= @actions.group_by { |a| a.keys.first }['is_true'] end # The false match clauses. # # @return [ Array ] The false match clauses. # # @since 6.2.0 def false_clauses @false_clauses ||= @actions.group_by { |a| a.keys.first }['is_false'] end # The gte clauses. # # @return [ Array ] The gte clauses. # # @since 6.2.0 def gte_clauses @gte_clauses ||= @actions.group_by { |a| a.keys.first }['gte'] end # The gt clauses. # # @return [ Array ] The gt clauses. # # @since 6.2.0 def gt_clauses @gt_clauses ||= @actions.group_by { |a| a.keys.first }['gt'] end # The lte clauses. # # @return [ Array ] The lte clauses. # # @since 6.2.0 def lte_clauses @lte_clauses ||= @actions.group_by { |a| a.keys.first }['lte'] end # The lt clauses. # # @return [ Array ] The lt clauses. # # @since 6.2.0 def lt_clauses @lt_clauses ||= @actions.group_by { |a| a.keys.first }['lt'] end # The field length match clauses. # # @return [ Array ] The field length match clauses. # # @since 6.2.0 def length_match_clauses @match_length ||= @actions.group_by { |a| a.keys.first }['length'] end private ACTIONS = [ 'do', 'match', 'length', 'set', 'transform_and_set', 'is_true', 'is_false', 'gte', 'gt', 'lte', 'lt' ].freeze def do_actions @do_actions ||= @actions.group_by { |a| a.keys.first }['do'].map { |definition| Action.new(definition['do']) } end def variables_to_set @actions.group_by { |a| a.keys.first }['set'] || [] end def variables_to_transform_and_set @actions.group_by { |a| a.keys.first }['transform_and_set'] || [] end def transform_and_set_variable(action) variables_to_transform_and_set.each do |set_definition| set_definition['transform_and_set'].each do |response_key, transform_description| match_base_64_transform = /(\#base64EncodeCredentials\()(\S*)\)/ matches = match_base_64_transform.match(transform_description) fields = matches[2].split(',') if matches.length > 0 values_to_encode = action.response.select do |key| fields.include?(key) end.values if fields to_set = Base64.encode64(values_to_encode.join(':')) @test.cache_value(response_key, to_set) end end end def set_variable(action) variables_to_set.each do |set_definition| set_definition['set'].each do |response_key, variable_name| nested_key_chain = response_key.split('.').map do |key| (key =~ /\A[-+]?[0-9]+\z/) ? key.to_i: key end if to_set = find_value(nested_key_chain, action.response) @test.cache_value(variable_name, to_set) end end end end def find_value(chain, document) return document[chain[0]] unless chain.size > 1 find_value(chain[1..-1], document[chain[0]]) if document[chain[0]] end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/support/test_file/test.rb000066400000000000000000000152111361161326000271640ustar00rootroot00000000000000module Elasticsearch module RestAPIYAMLTests class TestFile # Represents a single test in a test file. A single test can have many operations and validations. # # @since 6.2.0 class Test attr_reader :description attr_reader :test_file attr_reader :cached_values attr_reader :file_basename # Actions that if followed by a 'do' action, indicate that they complete their task group. # For example, consider this sequence of actions: # do, do, match, match, do, match # The second match indicates that the task group is complete and can be run as a unit. # That sequence becomes two task groups: # do, do, match, match # do, match # # @since 6.2.0 GROUP_TERMINATORS = [ 'length', 'gt', 'set', 'transform_and_set', 'match', 'is_false', 'is_true' ].freeze # The maximum Elasticsearch version this client version can successfully run tests against. # # @since 6.2.0 MAX_REQUIRED_VERSION = nil # The minimum Elasticsearch version this client version can successfully run tests against. # # @since 6.2.0 MIN_REQUIRED_VERSION = nil # Initialize the Test object. # # @example Create a test object # Test.new(file, definition) # # @param [ String ] test_file The name of the test file. # @param [ Hash ] test_definition A hash corresponding to the parsed YAML containing the test definition. # # @since 6.2.0 def initialize(test_file, test_definition) @test_file = test_file @file_basename = test_file.name.gsub("#{YAML_FILES_DIRECTORY}/", '') @description = test_definition.keys.first @definition = test_definition[description].select { |doc| !doc.key?('skip') } @definition.delete_if { |doc| doc['skip'] } @cached_values = {} skip_definitions = test_definition[description].select { |doc| doc['skip'] }.compact @skip = skip_definitions unless skip_definitions.empty? end # Get the list of task groups in this test. # # @example # test.task_groups # # @return [ Array ] The list of task groups. # # @since 6.2.0 def task_groups @task_groups ||= begin @definition.each_with_index.inject([]) do |task_groups, (action, i)| # the action has a catch, it's a singular task group if action['do'] && action['do']['catch'] task_groups << TaskGroup.new(self) elsif action['do'] && i > 0 && is_a_validation?(@definition[i-1]) task_groups << TaskGroup.new(self) elsif i == 0 task_groups << TaskGroup.new(self) end task_groups[-1].add_action(action) && task_groups end end end # Cache a value on this test object. # # @example # test.cache_value(cache_key, value) # # @param [ String ] cache_key The cache key for the value. # @param [ Object ] value The value to cache. # # @return [ Hash ] The cached values. # # @since 6.2.0 def cache_value(cache_key, value) @cached_values["#{cache_key}"] = value @cached_values end # Get a cached value. # # @example # test.get_cached_value('$watch_count_active') # # @param [ String ] key The key of the cached value. # # @return [ Hash ] The cached value at the key or the key if it's not found. # # @since 6.2.0 def get_cached_value(key) return key unless key.is_a?(String) @cached_values.fetch(key.gsub(/[\$\{\}]/, ''), key) end # Run all the tasks in this test. # # @example # test.run(client) # # @param [ Elasticsearch::Client ] client The client to use when executing operations. # # @return [ self ] # # @since 6.2.0 def run(client) task_groups.each { |task_group| task_group.run(client) } self end # Determine whether this test should be skipped, given a list of unsupported features. # # @example # test.skip_test?(['warnings']) # # @param [ Array ] features_to_skip A list of the features to skip. # # @return [ true, false ] Whether this test should be skipped, given a list of unsupported features. # # @since 6.2.0 def skip_test?(client, features_to_skip = test_file.features_to_skip) return true if pre_defined_skip? if @skip @skip.collect { |s| s['skip'] }.any? do |skip| contains_features_to_skip?(features_to_skip, skip) || skip_version?(client, skip) end end end private def contains_features_to_skip?(features_to_skip, skip_defintion) !(features_to_skip & ([skip_defintion['features']].flatten || [])).empty? end def pre_defined_skip? SKIPPED_TESTS.find do |t| file_basename == t[:file] && (description == t[:description] || t[:description] == '*') end end def skip_version?(client, skip_definition) return true if skip_definition['version'] == 'all' range_partition = /\s*-\s*/ if versions = skip_definition['version'] && skip_definition['version'].partition(range_partition) low, high = __parse_versions(versions) range = low..high begin server_version = client.info['version']['number'] rescue warn('Could not determine Elasticsearch version when checking if test should be skipped.') end range.cover?(server_version) end end def is_a_validation?(action) GROUP_TERMINATORS.any? { |validation| action[validation] } || expects_exception?(action) end def expects_exception?(action) action['do'] && action['do']['catch'] end def __parse_versions(versions) low = versions[0] high = (['', nil, '-'].include? versions[2]) ? low : versions[2] [low, high] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/000077500000000000000000000000001361161326000232745ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/machine_learning/000077500000000000000000000000001361161326000265575ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/machine_learning/set_upgrade_mode_spec.rb000066400000000000000000000026031361161326000334250ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. require 'spec_helper' describe 'client#set_upgrade_mode' do let(:expected_args) do [ 'POST', '_ml/set_upgrade_mode', {}, nil, nil ] end it 'performs the request' do expect(client_double.ml.set_upgrade_mode).to eq({}) end context 'when params are specified' do let(:expected_args) do [ 'POST', '_ml/set_upgrade_mode', { enabled: true, timeout: '10m' }, nil, nil ] end it 'performs the request' do expect(client_double.ml.set_upgrade_mode(enabled: true, timeout: '10m')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/rest_api_yaml_spec.rb000066400000000000000000000303031361161326000274620ustar00rootroot00000000000000require 'spec_helper' RSpec::Matchers.define :match_response_field_length do |expected_pairs| match do |response| expected_pairs.all? do |expected_key, expected_value| # ssl test returns results at '$body' key. See ssl/10_basic.yml expected_pairs = expected_pairs['$body'] if expected_pairs['$body'] split_key = split_and_parse_key(expected_key) actual_value = split_key.inject(response) do |_response, key| # If the key is an index, indicating element of a list if _response.empty? && key == '$body' _response else _response[key] end end actual_value.size == expected_value end end end RSpec::Matchers.define :match_true_field do |field| match do |response| # Handle is_true: '' return response == true if field == '' !!find_value_in_document(split_and_parse_key(field) , response) end end RSpec::Matchers.define :match_false_field do |field| match do |response| # Handle is_false: '' return response == false if field == '' !find_value_in_document(split_and_parse_key(field) , response) end end RSpec::Matchers.define :match_gte_field do |expected_pairs| match do |response| expected_pairs.all? do |expected_key, expected_value| split_key = split_and_parse_key(expected_key) actual_value = split_key.inject(response) do |_response, key| # If the key is an index, indicating element of a list if _response.empty? && key == '$body' _response else _response[key] end end actual_value >= expected_value end end end RSpec::Matchers.define :match_gt_field do |expected_pairs, test| match do |response| expected_pairs.all? do |expected_key, expected_value| split_key = split_and_parse_key(expected_key) actual_value = split_key.inject(response) do |_response, key| # If the key is an index, indicating element of a list if _response.empty? && key == '$body' _response else _response[key] end end actual_value > test.get_cached_value(expected_value) end end end RSpec::Matchers.define :match_lte_field do |expected_pairs| match do |response| expected_pairs.all? do |expected_key, expected_value| split_key = split_and_parse_key(expected_key) actual_value = split_key.inject(response) do |_response, key| # If the key is an index, indicating element of a list if _response.empty? && key == '$body' _response else _response[key] end end actual_value <= expected_value end end end RSpec::Matchers.define :match_lt_field do |expected_pairs| match do |response| expected_pairs.all? do |expected_key, expected_value| split_key = split_and_parse_key(expected_key) actual_value = split_key.inject(response) do |_response, key| # If the key is an index, indicating element of a list if _response.empty? && key == '$body' _response else _response[key] end end puts "actual: #{actual} and exected: #{expected_value}" actual_value < expected_value end end end RSpec::Matchers.define :match_response do |test, expected_pairs| match do |response| # sql test returns results at '$body' key. See sql/translate.yml expected_pairs = expected_pairs['$body'] if expected_pairs['$body'] # sql test has a String response. See sql/sql.yml if expected_pairs.is_a?(String) return compare_string_response(response, expected_pairs) end expected_pairs.all? do |expected_key, expected_value| # See test xpack/10_basic.yml # The master node id must be injected in the keys of match clauses expected_key = inject_master_node_id(expected_key, test) split_key = split_and_parse_key(expected_key) actual_value = find_value_in_document(split_key, response) # Sometimes the expected value is a cached value from a previous request. # See test api_key/10_basic.yml expected_value = test.get_cached_value(expected_value) # When you must match a regex. For example: # match: {task: '/.+:\d+/'} if expected_value.is_a?(String) && expected_value[0] == "/" && expected_value[-1] == "/" /#{expected_value.tr("/", "")}/ =~ actual_value else actual_value == expected_value end end end def inject_master_node_id(expected_key, test) # Replace the $master key in the nested document with the cached master node's id # See test xpack/10_basic.yml if test.cached_values['master'] expected_key.gsub(/\$master/, test.cached_values['master']) else expected_key end end def compare_string_response(response, expected_string) regexp = Regexp.new(expected_string.strip[1..-2], Regexp::EXTENDED|Regexp::MULTILINE) regexp =~ response end end RSpec::Matchers.define :match_error do |expected_error| match do |actual_error| # Remove surrounding '/' in string representing Regex expected_error = expected_error.tr("/", "") message = actual_error.message.tr("\\","") case expected_error when 'request_timeout' message =~ /\[408\]/ when 'missing' message =~ /\[404\]/ when 'conflict' message =~ /\[409\]/ when 'request' message =~ /\[500\]/ when 'bad_request' message =~ /\[400\]/ when 'param' message =~ /\[400\]/ || actual_error.is_a?(ArgumentError) when 'unauthorized' actual_error.is_a?(Elasticsearch::Transport::Transport::Errors::Unauthorized) when 'forbidden' actual_error.is_a?(Elasticsearch::Transport::Transport::Errors::Forbidden) else message =~ /#{expected_error}/ end end end describe 'XPack Rest API YAML tests' do REST_API_YAML_FILES.each do |file| test_file = Elasticsearch::RestAPIYAMLTests::TestFile.new(file, REST_API_YAML_SKIP_FEATURES) context "#{file.gsub("#{YAML_FILES_DIRECTORY}/", '')}" do before(:all) do # Runs once before all tests in a test file Elasticsearch::RestAPIYAMLTests::TestFile.prepare(ADMIN_CLIENT) end test_file.tests.each do |test| context "#{test.description}" do if test.skip_test?(ADMIN_CLIENT) skip 'Test contains feature(s) not yet support or version is not satisfied' else let(:client) do DEFAULT_CLIENT end # Runs once before each test in a test file before(:all) do begin # watcher/get_watch/30_with_chain_input.yml needs to have a teardown deleting my_watch. ADMIN_CLIENT.xpack.watcher.delete_watch(id: "my_watch") rescue Elasticsearch::Transport::Transport::Errors::NotFound end # todo: remove these two lines when Dimitris' PR is merged ADMIN_CLIENT.cluster.put_settings(body: { transient: { "xpack.ml.max_model_memory_limit" => nil } }) ADMIN_CLIENT.cluster.put_settings(body: { persistent: { "xpack.ml.max_model_memory_limit" => nil } }) Elasticsearch::RestAPIYAMLTests::TestFile.send(:clear_datafeeds, ADMIN_CLIENT) Elasticsearch::RestAPIYAMLTests::TestFile.send(:clear_ml_jobs, ADMIN_CLIENT) Elasticsearch::RestAPIYAMLTests::TestFile.send(:clear_tasks, ADMIN_CLIENT) Elasticsearch::RestAPIYAMLTests::TestFile.send(:clear_rollup_jobs, ADMIN_CLIENT) Elasticsearch::RestAPIYAMLTests::TestFile.send(:clear_machine_learning_indices, ADMIN_CLIENT) Elasticsearch::RestAPIYAMLTests::TestFile.send(:clear_indices, ADMIN_CLIENT) test_file.setup(ADMIN_CLIENT) end after(:all) do test_file.teardown(ADMIN_CLIENT) end test.task_groups.each do |task_group| before do task_group.run(client) end # 'catch' is in the task group definition if task_group.catch_exception? it 'sends the request and throws the expected error' do expect(task_group.exception).to match_error(task_group.expected_exception_message) end # 'match' on error description is in the task group definition if task_group.has_match_clauses? task_group.match_clauses.each do |match| it 'contains the expected error in the request response' do expect(task_group.exception.message).to match(Regexp.new(Regexp.escape(match['match'].values.first.to_s))) end end end else # 'match' is in the task group definition if task_group.has_match_clauses? task_group.match_clauses.each do |match| it "has the expected value (#{match['match'].values.join(',')}) in the response field (#{match['match'].keys.join(',')})" do expect(task_group.response).to match_response(test, match['match']) end end end # 'length' is in the task group definition if task_group.has_length_match_clauses? task_group.length_match_clauses.each do |match| it "the '#{match['length'].keys.join(',')}' field have the expected length" do expect(task_group.response).to match_response_field_length(match['length']) end end end # 'is_true' is in the task group definition if task_group.has_true_clauses? task_group.true_clauses.each do |match| it 'sends the request and the response fields have the expected fields set to true' do expect(task_group.response).to match_true_field(match['is_true']) end end end # 'is_false' is in the task group definition if task_group.has_false_clauses? task_group.false_clauses.each do |match| it 'sends the request and the response fields have the expected fields set to false' do expect(task_group.response).to match_false_field(match['is_false']) end end end # 'gte' is in the task group definition if task_group.has_gte_clauses? task_group.gte_clauses.each do |match| it 'sends the request and the response fields have values greater than or equal to the expected values' do expect(task_group.response).to match_gte_field(match['gte']) end end end # 'gt' is in the task group definition if task_group.has_gt_clauses? task_group.gt_clauses.each do |match| it 'sends the request and the response fields have values greater than to the expected values' do expect(task_group.response).to match_gt_field(match['gt'], test) end end end # 'lte' is in the task group definition if task_group.has_lte_clauses? task_group.lte_clauses.each do |match| it 'sends the request and the response fields have values less than or equal to the expected values' do expect(task_group.response).to match_lte_field(match['lte']) end end end # 'lt' is in the task group definition if task_group.has_lt_clauses? task_group.lt_clauses.each do |match| it 'sends the request and the response fields have values less than to the expected values' do expect(task_group.response).to match_lt_field(match['lt']) end end end end end end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/security/000077500000000000000000000000001361161326000251435ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/security/create_api_key_spec.rb000066400000000000000000000040401361161326000314440ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. require 'spec_helper' describe 'client#security#create_api_key' do let(:expected_args) do [ 'PUT', '_security/api_key', {}, body, nil ] end let(:body) do { "name": "my-api-key", "expiration": "1d", "role_descriptors": { "role-a": { "cluster": ["all"], "index": [ { "names": ["index-a"], "privileges": ["read"] } ] }, "role-b": { "cluster": ["manage"], "index": [ { "names": ["index-b"], "privileges": ["all"] } ] } } } end it 'performs the request' do expect(client_double.security.create_api_key(body: body)).to eq({}) end context 'when params are specified' do let(:expected_args) do [ 'PUT', '_security/api_key', { refresh: 'wait_for' }, body, nil ] end it 'performs the request' do expect(client_double.security.create_api_key(body: body, refresh: 'wait_for')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/security/get_api_key_spec.rb000066400000000000000000000031021361161326000307560ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. require 'spec_helper' describe 'client#security#get_api_key' do let(:expected_args) do [ 'GET', '_security/api_key', params, nil, nil ] end let(:params) do {} end it 'performs the request' do expect(client_double.security.get_api_key).to eq({}) end context 'when params are specified' do let(:params) do { id: '1', username: 'user', name: 'my-api-key', realm_name: '_es_api_key' } end it 'performs the request' do expect(client_double.security.get_api_key(id: '1', username: 'user', name: 'my-api-key', realm_name: '_es_api_key')).to eq({}) end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/spec/xpack/security/invalidate_api_key_spec.rb000066400000000000000000000021461361161326000323260ustar00rootroot00000000000000# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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. require 'spec_helper' describe 'client#security#create_api_key' do let(:expected_args) do [ 'DELETE', '_security/api_key', {}, body, nil ] end let(:body) do { id: 1 } end it 'performs the request' do expect(client_double.security.invalidate_api_key(body: body)).to eq({}) end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/000077500000000000000000000000001361161326000222135ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/integration/000077500000000000000000000000001361161326000245365ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/integration/yaml_test_runner.rb000066400000000000000000000521331361161326000304610ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) require 'pathname' require 'logger' require 'yaml' require 'active_support/inflector' require 'ansi' require 'elasticsearch' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/extensions/test/profiling' unless JRUBY require 'test_helper' # Skip features skip_features = 'stash_in_path,requires_replica,warnings' SKIP_FEATURES = ENV.fetch('TEST_SKIP_FEATURES', skip_features) # Skip files where a pattern matches default_skip_patterns = [ '/xpack/10_basic.yml', # Test fails, doesn't counts with more plugins installed, like `ingest-geoip` '/xpack/15_basic', # Test inserts invalid license, making all subsequent tests fail '/license/20_put_license', # Test inserts invalid license, making all subsequent tests fail '/token/', # Tokens require full SSL setup (TODO) '/ssl/10_basic', # (?) Test relies on some external setup '/ml/jobs_crud.yml', # (?) Test expects settings? '/ml/ml_info.yml' # Test doesn't reset itself in teardown ].join('|') SKIP_PATTERNS = Regexp.new( [default_skip_patterns, ENV['TEST_SKIP_PATTERNS'] ].compact.join('|') ) class String # Reset the `ansi` method on CI def ansi(*args) self end end if ENV['CI'] module CapturedLogger def self.included base base.class_eval do %w[ info error warn fatal debug ].each do |m| alias_method "#{m}_without_capture", m define_method m do |*args| @logdev.__send__ :puts, *(args.join("\n") + "\n") self.__send__ "#{m}_without_capture", *args end end end end end Logger.__send__ :include, CapturedLogger if ENV['CI'] $logger = Logger.new($stderr) $logger.progname = 'elasticsearch' $logger.formatter = proc do |severity, datetime, progname, msg| color = case severity when /INFO/ then :green when /ERROR|WARN|FATAL/ then :red when /DEBUG/ then :cyan else :white end "#{severity[0]} ".ansi(color, :faint) + msg.ansi(:white, :faint) + "\n" end $tracer = Logger.new($stdout) $tracer.progname = 'elasticsearch.tracer' $tracer.formatter = proc { |severity, datetime, progname, msg| "#{msg}\n" } if ENV['ELASTIC_PASSWORD'] password = ENV['ELASTIC_PASSWORD'] else password = begin puts "The ELASTIC_PASSWORD environment variable is not set, getting password by running `bin/elasticsearch-setup-passwords`...".ansi(:faint) out = `docker exec -it elasticsearch-xpack bin/elasticsearch-setup-passwords auto --batch` matches = out.match(/PASSWORD elastic = (\S+)/) if matches && matches.captures.first matches.captures.first else puts "\nCannot get password from Docker:".ansi(:bold, :red) puts out.to_s.ansi(:faint) exit(1) end end puts "Password succesfully generated, export it in your shell for subsequent runs:".ansi(:faint), "export ELASTIC_PASSWORD=#{password}" end $url = ENV.fetch('TEST_CLUSTER_URL', "http://elastic:#{password}@localhost:#{ENV['TEST_CLUSTER_PORT'] || 9260}") puts '-'*80, "Connecting to <#{$url}>".ansi(:bold, :faint) $client ||= Elasticsearch::Client.new url: $url $helper_client ||= Elasticsearch::Client.new url: $url es_version_info = $helper_client.info['version'] xpack_info = $helper_client.xpack.info plugins = $helper_client.cat.plugins(format: 'json') $es_version = es_version_info['number'] puts '-'*80, "Elasticsearch #{$es_version.ansi(:bold)} [#{es_version_info['build_hash'].to_s[0...7]}]", "Plugins: " + plugins.map { |d| "#{d['component'].ansi(:bold)}:#{d['version']}"}.join(', '), "X-Pack #{xpack_info['license']['type']} license is #{xpack_info['license']['status'].ansi(:bold)} and expires at #{Time.at(xpack_info['license']['expiry_date_in_millis']/1000)}", '-'*80 $client.transport.logger = $logger unless ENV['QUIET'] || ENV['CI'] $original_client = $client.clone module Minitest module Reporters class SpecReporter def record_print_status(test) test_name = test.name.gsub(/^test_: (.+) should (.+)/, '[\1] \2') print pad_test(test_name) print_colored_status(test) print(" (%.2fs)" % test.time) unless test.time.nil? puts end end end end module Elasticsearch module YamlTestSuite $last_response = '' $results = {} $stash = {} module Utils def titleize(word) word.to_s.gsub(/[^\w]+/, ' ').gsub(/\b('?[a-z])/) { $1.capitalize }.tr('_', ' ') end def symbolize_keys(object) if object.is_a? Hash object.reduce({}) { |memo,(k,v)| memo[k.to_sym] = symbolize_keys(v); memo } else object end end extend self end module Runner def perform_api_call(test, api, arguments=nil) namespace = api.split('.') replacer = lambda do |value| case value when Array value.map { |v| replacer.call(v) } when Hash Hash[ value.map { |v| replacer.call(v) } ] else fetch_or_return value end end timefixer = lambda do |value| if value.is_a?(Time) value.iso8601 else value end end arguments = Hash[ arguments.map do |key, value| replacement = replacer.call(value) replacement = timefixer.call(replacement) [key, replacement] end ] $stderr.puts "[#{api}] ARGUMENTS: #{arguments.inspect}" if ENV['DEBUG'] $last_response = namespace.reduce($client) do |memo, current| unless current == namespace.last memo = memo.send(current) else arguments ? memo = memo.send(current, arguments) : memo = memo.send(current) end memo end $results[test.hash] = $last_response end def evaluate(test, property, response=nil) response ||= $results[test.hash] property.gsub(/\\\./, '_____').split('.').reduce(response) do |memo, attr| if memo if attr attr = attr.gsub(/_____/, '.') attr = $stash[attr] if attr.start_with? '$' end case when memo.is_a?(Hash) && attr memo = memo[attr] when memo.is_a?(Array) && attr && attr =~ /^\d+$/ memo = memo[attr.to_i] else memo = memo end end memo end end def in_context(name, &block) klass = Class.new(YamlTestCase) Object::const_set "%sTest" % name.split(/\s/).reject { |d| d.match(/^\d+/) }.map { |d| d.capitalize }.join('').gsub(/[^\w]+/, ''), klass klass.context name, &block end def fetch_or_return(var) if var.is_a?(String) && var =~ /^\$(.+)/ $stash[var] else var end end def set(var, val) $stash["$#{var}"] = val end def skip?(actions) skip = actions.select { |a| a['skip'] }.first # Skip version if skip && skip['skip']['version'] $stderr.puts "SKIP: #{skip.inspect}" if ENV['DEBUG'] return skip['skip']['reason'] ? skip['skip']['reason'] : true if skip['skip']['version'] == 'all' min, max = skip['skip']['version'].split('-').map(&:strip) min_normalized = sprintf "%03d-%03d-%03d", *min.split('.') .map(&:to_i) .fill(0, min.split('.').length, 3-min.split('.').length) max_normalized = sprintf "%03d-%03d-%03d", *max.split('.') .map(&:to_i) .map(&:to_i) .fill(0, max.split('.').length, 3-max.split('.').length) es_normalized = sprintf "%03d-%03d-%03d", *$es_version.split('.').map(&:to_i) if ( min.empty? || min_normalized <= es_normalized ) && ( max.empty? || max_normalized >= es_normalized ) return skip['skip']['reason'] ? skip['skip']['reason'] : true end # Skip features elsif skip && skip['skip']['features'] skip_features = skip['skip']['features'].respond_to?(:split) ? skip['skip']['features'].split(',') : skip['skip']['features'] if ( skip_features & SKIP_FEATURES.split(',') ).size > 0 return skip['skip']['features'] end end return false end extend self end class YamlTestCase < Minitest::Test; end end end include Elasticsearch::YamlTestSuite rest_api_test_source = '../../../../tmp/elasticsearch/x-pack/plugin/src/test/resources/rest-api-spec/test' PATH = Pathname(ENV.fetch('TEST_REST_API_SPEC', File.expand_path(rest_api_test_source, __FILE__))) raise Errno::ENOENT, "#{PATH}" unless PATH.exist? suites = Dir.glob(PATH.join('*')).map { |d| Pathname(d) } suites = suites.select { |s| s.to_s =~ Regexp.new(ENV['FILTER']) } if ENV['FILTER'] $stderr.puts "TEST SUITES: " + suites.map { |d| d.basename }.join(', ') if ENV['DEBUG'] suites.each do |suite| name = Elasticsearch::YamlTestSuite::Utils.titleize(suite.basename) Elasticsearch::YamlTestSuite::Runner.in_context name do # --- Register context setup ------------------------------------------- # setup do # Prevent deleting the `.security*` index indices = $helper_client.indices.get(index: '_all').keys.reject { |i| i.start_with?('.security') } $helper_client.indices.delete index: indices, ignore: 404 unless indices.empty? $results = {} $stash = {} # Cleanup for roles $helper_client.xpack.security.get_role.each do |role, _| begin $helper_client.xpack.security.delete_role name: role rescue end end # Cleanup for privileges $helper_client.xpack.security.get_privileges.each do |privilege, _| begin $helper_client.xpack.security.delete_privileges name: privilege rescue end end # Cleanup for users $helper_client.xpack.security.get_user.each do |user, _| begin $helper_client.xpack.security.delete_user username: user rescue end end # Setup machine learning user $helper_client.xpack.security.put_user username: 'x_pack_rest_user', body: { password: 'x-pack-test-password', roles: ['superuser'] } # Cleanup for machine learning $helper_client.xpack.ml.stop_datafeed datafeed_id: '_all', force: true $helper_client.xpack.ml.get_datafeeds['datafeeds'].each do |d| $helper_client.xpack.ml.delete_datafeed datafeed_id: d['datafeed_id'] end $helper_client.xpack.ml.close_job job_id: '_all', force: true $helper_client.xpack.ml.get_jobs['jobs'].each do |d| $helper_client.xpack.ml.delete_job job_id: d['job_id'] end # $helper_client.cat.tasks(format: 'json') tasks = $helper_client.tasks.get['nodes'].values.first['tasks'].values.select { |d| d['cancellable'] }.map { |d| "#{d['node']}:#{d['id']}" } tasks.each { |t| $helper_client.tasks.cancel task_id: t } $helper_client.indices.delete index: '.ml-*', ignore: 404 end # --- Register context teardown ---------------------------------------- # teardown do $helper_client.xpack.ml.stop_datafeed datafeed_id: '_all', force: true $helper_client.xpack.ml.get_datafeeds['datafeeds'].each do |d| $helper_client.xpack.ml.delete_datafeed datafeed_id: d['datafeed_id'] end $helper_client.xpack.ml.close_job job_id: '_all', force: true $helper_client.xpack.ml.get_jobs['jobs'].each do |d| $helper_client.xpack.ml.delete_job job_id: d['job_id'] end $helper_client.indices.delete index: '_all', ignore: 404 if ENV['CLEANUP'] end # --- Parse tests ------------------------------------------------------ # Dir[suite.join('*.{yml,yaml}')].each do |file| if file =~ SKIP_PATTERNS $stderr.puts "#{'SKIP FILE'.ansi(:yellow)} #{file.gsub(PATH.to_s, '')}" next end tests = YAML.load_stream File.new(file) # Extract setup and teardown actions setup_actions = tests.select { |t| t['setup'] }.first['setup'] rescue [] teardown_actions = tests.select { |t| t['teardown'] }.first['teardown'] rescue [] # Skip all the tests when `skip` is part of the `setup` part if features = Runner.skip?(setup_actions) $stdout.puts "#{'SKIP TEST'.ansi(:yellow)} [#{name}] #{file.gsub(PATH.to_s, '').ansi(:bold)} (Feature not implemented: #{features})" next end # Remove setup/teardown actions from tests tests = tests.reject { |t| t['setup'] || t['teardown'] } # Add setup/teardown actions to each individual test tests.each { |t| t[t.keys.first] << { 'setup' => setup_actions } } tests.each { |t| t[t.keys.first] << { 'teardown' => teardown_actions } } tests.each do |test| context '' do test_name = test.keys.first.to_s.gsub(/test/i, '').strip.capitalize.ansi(:bold) + " | #{file.gsub(PATH.to_s, '')}" actions = test.values.first if reason = Runner.skip?(actions) $stdout.puts "#{'SKIP TEST'.ansi(:yellow)} [#{name}] #{test_name} (Reason: #{reason})" next end # --- Register test setup ------------------------------------------- setup do actions.find { |a| a['setup'] }['setup'].each do |action| if action['do'] if headers = action['do'] && action['do'].delete('headers') puts "HEADERS: " + headers.inspect if ENV['DEBUG'] $client = Elasticsearch::Client.new url: $url, transport_options: { headers: headers } $client.transport.logger = $logger unless ENV['QUIET'] || ENV['CI'] else $client = $original_client end api, arguments = action['do'].to_a.first arguments = Utils.symbolize_keys(arguments) Runner.perform_api_call((test.to_s + '___setup'), api, arguments) end if action['set'] stash = action['set'] property, variable = stash.to_a.first result = Runner.evaluate(test, property, $last_response) $stderr.puts "STASH: '$#{variable}' => #{result.inspect}" if ENV['DEBUG'] Runner.set variable, result end end end # --- Register test teardown ------------------------------------------- teardown do $client = $helper_client actions.select { |a| a['teardown'] }.first['teardown'].each do |action| if action['do'] api, arguments = action['do'].to_a.first arguments = Utils.symbolize_keys(arguments) Runner.perform_api_call((test.to_s + '___teardown'), api, arguments) end if action['set'] stash = action['set'] property, variable = stash.to_a.first result = Runner.evaluate(test, property, $last_response) $stderr.puts "STASH: '$#{variable}' => #{result.inspect}" if ENV['DEBUG'] Runner.set variable, result end end unless teardown_actions.empty? end # --- Register test method ------------------------------------------ should test_name do actions.each do |action| $stderr.puts "ACTION: #{action.inspect}" if ENV['DEBUG'] if headers = action['do'] && action['do'].delete('headers') puts "HEADERS: " + headers.inspect if ENV['DEBUG'] $client = Elasticsearch::Client.new url: $url, transport_options: { headers: headers } $client.transport.logger = $logger unless ENV['QUIET'] || ENV['CI'] else $client = $original_client end case # --- Perform action ------------------------------------------ # when action['do'] catch_exception = action['do'].delete('catch') if action['do'] api, arguments = action['do'].to_a.first arguments = Utils.symbolize_keys(arguments) begin $results[test.hash] = Runner.perform_api_call(test, api, arguments) rescue Exception => e begin $results[test.hash] = MultiJson.load(e.message.match(/{.+}/, 1).to_s) rescue MultiJson::ParseError $stderr.puts "RESPONSE: Cannot parse JSON from error message: '#{e.message}'" if ENV['DEBUG'] end if catch_exception $stderr.puts "CATCH: '#{catch_exception}': #{e.inspect}" if ENV['DEBUG'] case e when 'missing' assert_match /\[404\]/, e.message when 'conflict' assert_match /\[409\]/, e.message when 'request' assert_match /\[500\]/, e.message when 'param' raise ArgumentError, "NOT IMPLEMENTED" when /\/.+\// assert_match Regexp.new(catch_exception.tr('/', '')), e.message end else raise e end end # --- Evaluate predicates ------------------------------------- # when property = action['is_true'] result = Runner.evaluate(test, property) $stderr.puts "CHECK: Expected '#{property}' to be true, is: #{result.inspect}" if ENV['DEBUG'] assert(result, "Property '#{property}' should be true, is: #{result.inspect}") when property = action['is_false'] result = Runner.evaluate(test, property) $stderr.puts "CHECK: Expected '#{property}' to be nil, false, 0 or empty string, is: #{result.inspect}" if ENV['DEBUG'] assert "Property '#{property}' should be nil, false, 0 or empty string, but is: #{result.inspect}" do result.nil? || result == false || result == 0 || result == '' end when a = action['match'] property, value = a.to_a.first if value.is_a?(String) && value =~ %r{\s*^/\s*.*\s*/$\s*}mx # Begins and ends with / pattern = Regexp.new(value.strip[1..-2], Regexp::EXTENDED|Regexp::MULTILINE) else value = Runner.fetch_or_return(value) end if property == '$body' result = $results[test.hash] else result = Runner.evaluate(test, property) end if pattern $stderr.puts "CHECK: Expected '#{property}' to match #{pattern}, is: #{result.inspect}" if ENV['DEBUG'] assert_match(pattern, result) else value = value.reduce({}) { |memo, (k,v)| memo[k] = Runner.fetch_or_return(v); memo } if value.is_a? Hash $stderr.puts "CHECK: Expected '#{property}' to be '#{value}', is: #{result.inspect}" if ENV['DEBUG'] assert_equal(value, result) end when a = action['length'] property, value = a.to_a.first result = Runner.evaluate(test, property) length = result.size $stderr.puts "CHECK: Expected '#{property}' to be #{value}, is: #{length.inspect}" if ENV['DEBUG'] assert_equal(value, length) when a = action['lt'] || action['gt'] || action['lte'] || action['gte'] property, value = a.to_a.first operator = case when action['lt'] '<' when action['gt'] '>' when action['lte'] '<=' when action['gte'] '>=' end result = Runner.evaluate(test, property) message = "Expected '#{property}' to be #{operator} #{value}, is: #{result.inspect}" $stderr.puts "CHECK: #{message}" if ENV['DEBUG'] assert_operator result, operator.to_sym, value.to_i when stash = action['set'] property, variable = stash.to_a.first result = Runner.evaluate(test, property) $stderr.puts "STASH: '$#{variable}' => #{result.inspect}" if ENV['DEBUG'] Runner.set variable, result end end end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/test_helper.rb000066400000000000000000000022541361161326000250610ustar00rootroot00000000000000$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pathname' require 'minitest/autorun' require 'minitest/reporters' require 'shoulda/context' require 'mocha/minitest' require 'ansi' require 'elasticsearch/xpack' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new module Minitest class Test def assert_nothing_raised(*args) begin line = __LINE__ yield rescue Exception => e raise MiniTest::Assertion, "Exception raised:\n<#{e.class}>", e.backtrace end true end end end module Elasticsearch module Test class FakeClient def xpack @xpack_client ||= Elasticsearch::XPack::API::Client.new(self) end def perform_request(method, path, params, body) puts "PERFORMING REQUEST:", "--> #{method.to_s.upcase} #{path} #{params} #{body}" FakeResponse.new(200, 'FAKE', {}) end end FakeResponse = Struct.new(:status, :body, :headers) do def status values[0] || 200 end def body values[1] || '{}' end def headers values[2] || {} end end class NotFound < StandardError; end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/000077500000000000000000000000001361161326000231725ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/graph/000077500000000000000000000000001361161326000242735ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/graph/explore_test.rb000066400000000000000000000011361361161326000273360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class GraphExploreTest < Minitest::Test context "Graph: Explore" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/_graph/_explore', url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.graph.explore end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/info_test.rb000066400000000000000000000010721361161326000255110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackInfoTest < Minitest::Test context "XPack: Info" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.info end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/license/000077500000000000000000000000001361161326000246145ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/license/delete_test.rb000066400000000000000000000011341361161326000274410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackLicenseDeleteTest < Minitest::Test context "License: Delete" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/license', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.license.delete end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/license/get_test.rb000066400000000000000000000011201361161326000267510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackLicenseGetTest < Minitest::Test context "License: Get" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/license', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.license.get end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/license/post_test.rb000066400000000000000000000011401361161326000271610ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackLicensePostTest < Minitest::Test context "License: Post" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/license', url assert_equal Hash.new, params assert_equal [], body true end.returns(FakeResponse.new) subject.xpack.license.post body: [] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/000077500000000000000000000000001361161326000264555ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/close_job_test.rb000066400000000000000000000012171361161326000320010ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlCloseJobTest < Minitest::Test context "XPack MachineLearning: Close job" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/_close", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.close_job :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/delete_datafeed_test.rb000066400000000000000000000012311361161326000331150ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlDeleteDatafeedTest < Minitest::Test context "XPack MachineLearning: Delete datafeed" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/ml/datafeeds/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.delete_datafeed :datafeed_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/delete_expired_data_test.rb000066400000000000000000000012251361161326000340140ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlDeleteExpiredDataTest < Minitest::Test context "XPack MachineLearning: Delete expired data" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/ml/_delete_expired_data", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.delete_expired_data end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/delete_filter_test.rb000066400000000000000000000012171361161326000326510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlDeleteFilterTest < Minitest::Test context "XPack MachineLearning: Delete filter" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/ml/filters/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.delete_filter :filter_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/delete_forecast_test.rb000066400000000000000000000012471361161326000331750ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlDeleteForecastTest < Minitest::Test context "XPack MachineLearning: Delete forecast" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/ml/anomaly_detectors/foo/_forecast/", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.delete_forecast :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/delete_job_test.rb000066400000000000000000000012151361161326000321340ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlDeleteJobTest < Minitest::Test context "XPack MachineLearning: Delete job" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/ml/anomaly_detectors/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.delete_job :job_id => 'foo' end end end end end delete_model_snapshot_test.rb000066400000000000000000000013301361161326000343200ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learningrequire 'test_helper' module Elasticsearch module Test class XPackMlDeleteModelSnapshotTest < Minitest::Test context "XPack MachineLearning: Delete model snapshot" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/ml/anomaly_detectors/foo/model_snapshots/bar", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.delete_model_snapshot :job_id => 'foo', :snapshot_id => 'bar' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/find_file_structure_test.rb000066400000000000000000000012301361161326000340740ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class FindFileStructuretest < Minitest::Test context "XPack MachineLearning: Find file structure" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/find_file_structure", url assert_equal Hash.new, params assert_equal "", body true end.returns(FakeResponse.new) subject.xpack.ml.find_file_structure body: [] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/flush_job_test.rb000066400000000000000000000012241361161326000320130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlFlushJobTest < Minitest::Test context "XPack MachineLearning: Flush job" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/_flush", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.flush_job :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/forecast_test.rb000066400000000000000000000012201361161326000316420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlForecastTest < Minitest::Test context "XPack MachineLearning: Forecast" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_xpack/ml/anomaly_detectors/foo/_forecast', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.forecast :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_buckets_test.rb000066400000000000000000000012421361161326000323370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetBucketsTest < Minitest::Test context "XPack MachineLearning: Get buckets" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo/results/buckets", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.get_buckets :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_categories_test.rb000066400000000000000000000012561361161326000330310ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetCategoriesTest < Minitest::Test context "XPack MachineLearning: Get categories" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo/results/categories", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.get_categories :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_datafeed_stats_test.rb000066400000000000000000000012131361161326000336500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetDatafeedStatsTest < Minitest::Test context "XPack MachineLearning: Get datafeed stats" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/datafeeds/_stats", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.get_datafeed_stats end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_datafeeds_test.rb000066400000000000000000000012201361161326000326130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetDatafeedsTest < Minitest::Test context "XPack MachineLearning: Get datafeeds" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/datafeeds/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.get_datafeeds :datafeed_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_filters_test.rb000066400000000000000000000012061361161326000323470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetFiltersTest < Minitest::Test context "XPack MachineLearning: Get filters" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/filters/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.get_filters :filter_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_influencers_test.rb000066400000000000000000000012621361161326000332160ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetInfluencersTest < Minitest::Test context "XPack MachineLearning: Get influencers" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo/results/influencers", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.get_influencers :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_job_stats_test.rb000066400000000000000000000012311361161326000326650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetJobStatsTest < Minitest::Test context "XPack MachineLearning: Get job stats" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo/_stats", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.get_job_stats :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_jobs_test.rb000066400000000000000000000012041361161326000316320ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetJobsTest < Minitest::Test context "XPack MachineLearning: Get jobs" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.get_jobs :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_model_snapshots_test.rb000066400000000000000000000013241361161326000341020ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetModelSnapshotsTest < Minitest::Test context "XPack MachineLearning: Get model snapshots" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo/model_snapshots/bar", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.get_model_snapshots :job_id => 'foo', :snapshot_id => 'bar' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_overall_buckets_test.rb000066400000000000000000000013011361161326000340570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetOverallBucketsTest < Minitest::Test context "XPack MachineLearning: Get overall buckets" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/ml/anomaly_detectors/foo/results/overall_buckets', url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.get_overall_buckets :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/get_records_test.rb000066400000000000000000000012421361161326000323400ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetRecordsTest < Minitest::Test context "XPack MachineLearning: Get records" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/anomaly_detectors/foo/results/records", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.get_records :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/open_job_test.rb000066400000000000000000000012131361161326000316310ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlOpenJobTest < Minitest::Test context "XPack MachineLearning: Open job" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/_open", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.open_job :job_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/post_data_test.rb000066400000000000000000000012451361161326000320210ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlPostDataTest < Minitest::Test context "XPack MachineLearning: Post data" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/_data", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.post_data :job_id => 'foo', :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/preview_datafeed_test.rb000066400000000000000000000012421361161326000333360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlPreviewDatafeedTest < Minitest::Test context "XPack MachineLearning: Preview datafeed" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/ml/datafeeds/foo/_preview", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.preview_datafeed :datafeed_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/put_datafeed_test.rb000066400000000000000000000012411361161326000324640ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlPutDatafeedTest < Minitest::Test context "XPack MachineLearning: Put datafeed" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal "_xpack/ml/datafeeds/foo", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.put_datafeed :datafeed_id => 'foo', body: {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/put_filter_test.rb000066400000000000000000000012321361161326000322140ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlPutFilterTest < Minitest::Test context "XPack MachineLearning: Put filter" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal "_xpack/ml/filters/foo", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.put_filter :filter_id => 'foo', :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/put_job_test.rb000066400000000000000000000012301361161326000314770ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlPutJobTest < Minitest::Test context "XPack MachineLearning: Put job" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal "_xpack/ml/anomaly_detectors/foo", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.put_job :job_id => 'foo', :body => {} end end end end end revert_model_snapshot_test.rb000066400000000000000000000013431361161326000343710ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learningrequire 'test_helper' module Elasticsearch module Test class XPackMlRevertModelSnapshotTest < Minitest::Test context "XPack MachineLearning: Revert model snapshot" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/model_snapshots/bar/_revert", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.revert_model_snapshot :job_id => 'foo', :snapshot_id => 'bar' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/start_datafeed_test.rb000066400000000000000000000012401361161326000330100ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlStartDatafeedTest < Minitest::Test context "XPack MachineLearning: Start datafeed" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/datafeeds/foo/_start", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.ml.start_datafeed :datafeed_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/stop_datafeed_test.rb000066400000000000000000000012271361161326000326450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlStopDatafeedTest < Minitest::Test context "XPack MachineLearning: Stop datafeed" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/datafeeds/foo/_stop", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ml.stop_datafeed :datafeed_id => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/update_datafeed_test.rb000066400000000000000000000012661361161326000331450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlUpdateDatafeedTest < Minitest::Test context "XPack MachineLearning: Update datafeed" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/datafeeds/foo/_update", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.update_datafeed :datafeed_id => 'foo', :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/update_filter_test.rb000066400000000000000000000012541361161326000326720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlUpdateFilterTest < Minitest::Test context "XPack MachineLearning: Update filter" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/filters/foo/_update", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.update_filter :filter_id => 'foo', :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/update_job_test.rb000066400000000000000000000012521361161326000321550ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlUpdateJobTest < Minitest::Test context "XPack MachineLearning: Update job" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/_update", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.update_job :job_id => 'foo', :body => {} end end end end end update_model_snapshot_test.rb000066400000000000000000000013651361161326000343500ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learningrequire 'test_helper' module Elasticsearch module Test class XPackMlUpdateModelSnapshotTest < Minitest::Test context "XPack MachineLearning: Update model snapshot" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/foo/model_snapshots/bar/_update", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.update_model_snapshot :job_id => 'foo', :snapshot_id => 'bar', :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/validate_detector_test.rb000066400000000000000000000012641361161326000335260ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlValidateDetectorTest < Minitest::Test context "XPack MachineLearning: Validate detector" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/_validate/detector", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.validate_detector :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/machine_learning/validate_test.rb000066400000000000000000000012211361161326000316260ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlValidateTest < Minitest::Test context "XPack MachineLearning: Validate" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/ml/anomaly_detectors/_validate", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.ml.validate :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/migration/000077500000000000000000000000001361161326000251635ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/migration/deprecations_test.rb000066400000000000000000000012051361161326000312250ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMigrationDeprecationsTest < Minitest::Test context "XPack Migration: Deprecations" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/migration/deprecations', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.migration.deprecations end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/migration/get_assistance_test.rb000066400000000000000000000012111361161326000315360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMigrationGetAssistanceTest < Minitest::Test context "XPack Migration: Get assistance" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/migration/assistance', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.migration.get_assistance end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/migration/upgrade_test.rb000066400000000000000000000012071361161326000301760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMigrationUpgradeTest < Minitest::Test context "XPack Migration: Upgrade" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_xpack/migration/upgrade/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.migration.upgrade :index => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/monitoring/000077500000000000000000000000001361161326000253575ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/monitoring/bulk_test.rb000066400000000000000000000011711361161326000277000ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMonitoringBulkTest < Minitest::Test context "XPack Monitoring: Bulk" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_xpack/monitoring/_bulk', url assert_equal Hash.new, params assert_equal "", body true end.returns(FakeResponse.new) subject.xpack.monitoring.bulk body: [] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/rollup/000077500000000000000000000000001361161326000245075ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/rollup/get_rollup_index_caps_test.rb000066400000000000000000000012301361161326000324400ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackMlGetRollupIndexCapsTest < Minitest::Test context "XPack Rollup: Get index caps" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "foo/_xpack/rollup/data", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.rollup.get_rollup_index_caps :index => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/000077500000000000000000000000001361161326000250415ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/authenticate_test.rb000066400000000000000000000012031361161326000310770ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityAuthenticateTest < Minitest::Test context "XPack Security: Authenticate" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/_authenticate', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.authenticate end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/change_password_test.rb000066400000000000000000000023001361161326000315670ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityChangePasswordTest < Minitest::Test context "XPack Security: Change password" do subject { FakeClient.new } should "perform correct request for a specific user" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/security/user/foo/_password', url assert_equal Hash.new, params assert_equal 'bar', body[:password] true end.returns(FakeResponse.new) subject.xpack.security.change_password username: 'foo', body: { password: 'bar' } end should "perform correct request for current user" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/security/user/_password', url assert_equal Hash.new, params assert_equal 'bar', body[:password] true end.returns(FakeResponse.new) subject.xpack.security.change_password body: { password: 'bar' } end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/clear_cached_realms_test.rb000066400000000000000000000012761361161326000323530ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityClearCachedRealmsTest < Minitest::Test context "XPack Security: Clear cached realms" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/security/realm/foo,bar/_clear_cache", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.clear_cached_realms :realms => ['foo', 'bar'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/clear_cached_roles_test.rb000066400000000000000000000012521361161326000322060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityClearCachedRolesTest < Minitest::Test context "XPack Security: Clear cached roles" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/security/role/foo/_clear_cache', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.clear_cached_roles :name => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/delete_privileges_test.rb000066400000000000000000000012731361161326000321230ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityDeletePrivilegesTest < Minitest::Test context "XPack Security: Delete privileges" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/security/privilege/foo/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.delete_privileges :application => 'foo', name: 'bar' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/delete_role_mapping_test.rb000066400000000000000000000012531361161326000324240ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityDeleteRoleMappingTest < Minitest::Test context "XPack Security: Delete role mapping" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/security/role_mapping/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.delete_role_mapping :name => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/delete_role_test.rb000066400000000000000000000012141361161326000307060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityDeleteRoleTest < Minitest::Test context "XPack Security: Delete role" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/security/role/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.delete_role :name => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/delete_user_test.rb000066400000000000000000000012201361161326000307200ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityDeleteUserTest < Minitest::Test context "XPack Security: Delete user" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/security/user/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.delete_user :username => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/disable_user_test.rb000066400000000000000000000012311361161326000310630ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityDisableUserTest < Minitest::Test context "XPack Security: Disable user" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal "_xpack/security/user/foo/_disable", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.disable_user :username => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/enable_user_test.rb000066400000000000000000000012251361161326000307110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityEnableUserTest < Minitest::Test context "XPack Security: Enable user" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal "_xpack/security/user/foo/_enable", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.enable_user :username => 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/get_privileges_test.rb000066400000000000000000000040651361161326000314420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityGetPrivilegesTest < Minitest::Test context "XPack Security: Get privileges" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/privilege', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_privileges end should "perform correct request for an application but no name" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/privilege/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_privileges application: 'foo' end should "perform correct request for an application and a single name" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/privilege/foo/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_privileges application: 'foo', name: 'bar' end should "perform correct request for an application and multiple names" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/privilege/foo/bar,baz', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_privileges application: 'foo', name: ['bar', 'baz'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/get_role_mapping_test.rb000066400000000000000000000021361361161326000317420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityGetRoleMappingTest < Minitest::Test context "XPack Security: Get role mapping" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/security/role_mapping/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_role_mapping :name => 'foo' end should "handle a list of roles" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/security/role_mapping/foo,bar", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_role_mapping :name => ['foo', 'bar'] end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/get_role_test.rb000066400000000000000000000024671361161326000302360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityGetRoleTest < Minitest::Test context "XPack Security: Get role" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/role', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_role end should "perform correct request for multiple roles" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/role/foo,bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_role name: ['foo', 'bar'] end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.xpack.security.get_role name: 'foo', ignore: 404 end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/get_token_test.rb000066400000000000000000000012171361161326000304050ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityGetTokenTest < Minitest::Test context "XPack Security: Get token" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal "_xpack/security/oauth2/token", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.security.get_token :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/get_user_privileges_test.rb000066400000000000000000000012361361161326000324750ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityGetUserPrivilegesTest < Minitest::Test context "XPack Security: Get user privileges" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal "_xpack/security/user/_privileges", url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.security.get_user_privileges end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/get_user_test.rb000066400000000000000000000024761361161326000302530ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityGetUserTest < Minitest::Test context "XPack Security: Get user" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/user', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_user end should "perform correct request for multiple roles" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/user/foo,bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.security.get_user username: ['foo', 'bar'] end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.xpack.security.get_user username: 'foo', ignore: 404 end end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/has_privileges_test.rb000066400000000000000000000024261361161326000314350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityHasPrivilegesTest < Minitest::Test context "XPack Security: Has Privileges" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/user/_has_privileges', url assert_equal Hash.new, params assert_equal({ cluster: [], index: [], application: [] }, body) true end.returns(FakeResponse.new) subject.xpack.security.has_privileges(body: { cluster: [], index: [], application: [] }) end should "check privileges for a specific user" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/security/user/foo/_has_privileges', url assert_equal Hash.new, params assert_equal({ cluster: [], index: [], application: [] }, body) true end.returns(FakeResponse.new) subject.xpack.security.has_privileges(user: 'foo', body: { cluster: [], index: [], application: [] }) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/invalidate_token_test.rb000066400000000000000000000012461361161326000317500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityInvalidateTokenTest < Minitest::Test context "XPack Security: Invalidate token" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal "_xpack/security/oauth2/token", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.security.invalidate_token :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/put_privileges_test.rb000066400000000000000000000013731361161326000314720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityPutPrivilegesTest < Minitest::Test context "XPack Security: Put role" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/security/privilege', url assert_equal Hash.new, params assert_equal({ "app-allow": { read: { actions: [ "data:read/*" ] } } }, body) true end.returns(FakeResponse.new) subject.xpack.security.put_privileges(body: { "app-allow": { read: { actions: [ "data:read/*" ] } } }) end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/put_role_mapping_test.rb000066400000000000000000000012661361161326000317760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityPutRoleMappingTest < Minitest::Test context "XPack Security: Put role mapping" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal "_xpack/security/role_mapping/foo", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.security.put_role_mapping :name => 'foo', :body => {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/put_role_test.rb000066400000000000000000000012241361161326000302550ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityPutRoleTest < Minitest::Test context "XPack Security: Put role" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/security/role/foo', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.security.put_role :name => 'foo', body: {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/security/put_user_test.rb000066400000000000000000000012251361161326000302730ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSecurityPutUserTest < Minitest::Test context "XPack Security: Put user" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/security/user/foo', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.security.put_user username: 'foo', body: {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/ssl/000077500000000000000000000000001361161326000237735ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/ssl/certificates_test.rb000066400000000000000000000011561361161326000300270ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackSslCertificatesTest < Minitest::Test context "XPack Ssl: Certificates" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/ssl/certificates', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.ssl.certificates end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/usage_test.rb000066400000000000000000000011031361161326000256550ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackUsageTest < Minitest::Test context "XPack: Usage" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/usage', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.usage end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/000077500000000000000000000000001361161326000246275ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/ack_watch_test.rb000066400000000000000000000021411361161326000301350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherAckWatchTest < Minitest::Test context "XPack Watcher: Ack watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/foo/_ack', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.ack_watch watch_id: 'foo' end should "perform correct request when action id is provided" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/foo/_ack/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.ack_watch watch_id: 'foo', action_id: 'bar' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/activate_watch_test.rb000066400000000000000000000012321361161326000311770ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherActivateWatchTest < Minitest::Test context "XPack Watcher: Activate watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/foo/_activate', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.activate_watch watch_id: 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/deactivate_watch_test.rb000066400000000000000000000012421361161326000315110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherDeactivateWatchTest < Minitest::Test context "XPack Watcher: Deactivate watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/foo/_deactivate', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.deactivate_watch watch_id: 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/delete_watch_test.rb000066400000000000000000000012071361161326000306430ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherDeleteWatchTest < Minitest::Test context "XPack Watcher: Delete watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_xpack/watcher/watch/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.delete_watch id: 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/execute_watch_test.rb000066400000000000000000000021151361161326000310420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherExecuteWatchTest < Minitest::Test context "XPack Watcher: Execute watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/foo/_execute', url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.watcher.execute_watch id: 'foo' end should "perform correct request with no id specified" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/_execute', url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.xpack.watcher.execute_watch end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/get_watch_test.rb000066400000000000000000000011731361161326000301620ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherGetWatchTest < Minitest::Test context "XPack Watcher: Get watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/watcher/watch/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.get_watch id: 'foo' end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/put_watch_test.rb000066400000000000000000000012171361161326000302120ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherPutWatchTest < Minitest::Test context "XPack Watcher: Put watch" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_xpack/watcher/watch/foo', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.xpack.watcher.put_watch id: 'foo', body: {} end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/restart_test.rb000066400000000000000000000011541361161326000277000ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherRestartTest < Minitest::Test context "XPack Watcher: Restart" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_xpack/watcher/_restart', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.restart end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/start_test.rb000066400000000000000000000011441361161326000273500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherStartTest < Minitest::Test context "XPack Watcher: Start" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_xpack/watcher/_start', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.start end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/stats_test.rb000066400000000000000000000011421361161326000273470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherStatsTest < Minitest::Test context "XPack Watcher: Stats" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_xpack/watcher/stats', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.stats end end end end end elasticsearch-ruby-6.8.1/elasticsearch-xpack/test/unit/watcher/stop_test.rb000066400000000000000000000011401361161326000271740ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class XPackWatcherStopTest < Minitest::Test context "XPack Watcher: Stop" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_xpack/watcher/_stop', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.xpack.watcher.stop end end end end end elasticsearch-ruby-6.8.1/elasticsearch/000077500000000000000000000000001361161326000201305ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch/.gitignore000066400000000000000000000002321361161326000221150ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp elasticsearch-ruby-6.8.1/elasticsearch/Gemfile000066400000000000000000000013471361161326000214300ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch.gemspec gemspec if File.exist? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-transport/elasticsearch-transport.gemspec", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => false end if File.exist? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => true end elasticsearch-ruby-6.8.1/elasticsearch/LICENSE.txt000066400000000000000000000011101361161326000217440ustar00rootroot00000000000000 Copyright 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch/README.md000066400000000000000000000072251361161326000214150ustar00rootroot00000000000000# Elasticsearch The `elasticsearch` library provides a Ruby client and API for [Elasticsearch](http://elasticsearch.org). Features overview: * Pluggable logging and tracing * Pluggable connection selection strategies (round-robin, random, custom) * Pluggable transport implementation, customizable and extendable * Pluggable serializer implementation * Request retries and dead connections handling * Node reloading (based on cluster state) on errors or on demand * Consistent API support for the whole Elasticsearch API * Extensive documentation and examples * Emphasis on modularity and extendability of both the client and API libraries (For integration with Ruby models and Rails applications, see the project.) ## Compatibility The Elasticsearch client for Ruby is compatible with Ruby 1.9 and higher. The client's API is compatible with Elasticsearch's API versions from 0.90 till current, just use a release matching major version of Elasticsearch. | Ruby | | Elasticsearch | |:-------------:|:-:| :-----------: | | 0.90 | → | 0.90 | | 1.x | → | 1.x | | 2.x | → | 2.x | | 5.x | → | 5.x | | 6.x | → | 6.x | | master | → | master | ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git' or install it from a source code checkout: git clone https://github.com/elasticsearch/elasticsearch-ruby.git cd elasticsearch-ruby/elasticsearch bundle install rake install ## Usage This library is a wrapper for two separate libraries: * [`elasticsearch-transport`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-transport), which provides a low-level Ruby client for connecting to an [Elasticsearch](http://elasticsearch.org) cluster * [`elasticsearch-api`](https://github.com/elasticsearch/elasticsearch-ruby/tree/master/elasticsearch-api), which provides a Ruby API for the Elasticsearch RESTful API Install the `elasticsearch` package and use the API directly: ```ruby require 'elasticsearch' client = Elasticsearch::Client.new log: true client.cluster.health client.transport.reload_connections! client.search q: 'test' # etc. ``` Please refer to the specific library documentation for details: * **Transport**: [[README]](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/README.md) [[Documentation]](http://rubydoc.info/gems/elasticsearch-transport/file/README.markdown) * **API**: [[README]](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-api/README.md) [[Documentation]](http://rubydoc.info/gems/elasticsearch-api/file/README.markdown) ## License This software is licensed under the Apache 2 license, quoted below. Copyright (c) 2013 Elasticsearch 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. elasticsearch-ruby-6.8.1/elasticsearch/Rakefile000066400000000000000000000020101361161326000215660ustar00rootroot00000000000000require "bundler/gem_tasks" desc "Run unit tests" task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' namespace :test do desc "Wait for Elasticsearch to be in a green state" task :wait_for_green do sh '../scripts/wait-cluster.sh' end Rake::TestTask.new(:unit) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] test.verbose = false test.warning = false end Rake::TestTask.new(:integration) do |test| test.deps = [ :wait_for_green ] test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/**/*_test.rb"] test.verbose = false test.warning = false end Rake::TestTask.new(:all) do |test| test.deps = [ :unit, :integration ] end end # ----- Documentation tasks --------------------------------------------------- require 'yard' YARD::Rake::YardocTask.new(:doc) do |t| t.options = %w| --embed-mixins --markup=markdown | end elasticsearch-ruby-6.8.1/elasticsearch/elasticsearch.gemspec000066400000000000000000000045601361161326000243140ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/version' Gem::Specification.new do |s| s.name = "elasticsearch" s.version = Elasticsearch::VERSION s.authors = ["Karel Minarik"] s.email = ["karel.minarik@elasticsearch.org"] s.summary = "Ruby integrations for Elasticsearch" s.homepage = "http://github.com/elasticsearch/elasticsearch-ruby" s.license = "Apache-2.0" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] s.extra_rdoc_files = [ "README.md", "LICENSE.txt" ] s.rdoc_options = [ "--charset=UTF-8" ] s.required_ruby_version = '>= 1.9' s.add_dependency "elasticsearch-transport", '6.8.1' s.add_dependency "elasticsearch-api", '6.8.1' s.add_development_dependency "bundler" if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "rake", "~> 11.1" else s.add_development_dependency "rake", "< 11.0" end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "elasticsearch-extensions" end s.add_development_dependency "ansi" s.add_development_dependency "shoulda-context" s.add_development_dependency "mocha" s.add_development_dependency "turn" s.add_development_dependency "yard" s.add_development_dependency "pry" # Prevent unit test failures on Ruby 1.8 if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_development_dependency "test-unit", '~> 2' s.add_development_dependency "json", '~> 1.8' end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "minitest", "~> 4.0" s.add_development_dependency "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) s.add_development_dependency "require-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) s.add_development_dependency "simplecov" s.add_development_dependency "simplecov-rcov" s.add_development_dependency "cane" end if defined?(RUBY_VERSION) && RUBY_VERSION > '2.2' s.add_development_dependency "test-unit", '~> 2' end s.description = <<-DESC.gsub(/^ /, '') Ruby integrations for Elasticsearch (client, API, etc.) DESC end elasticsearch-ruby-6.8.1/elasticsearch/lib/000077500000000000000000000000001361161326000206765ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch/lib/elasticsearch-ruby.rb000066400000000000000000000000301361161326000250050ustar00rootroot00000000000000require 'elasticsearch' elasticsearch-ruby-6.8.1/elasticsearch/lib/elasticsearch.rb000066400000000000000000000003141361161326000240330ustar00rootroot00000000000000require "elasticsearch/version" require 'elasticsearch/transport' require 'elasticsearch/api' module Elasticsearch module Transport class Client include Elasticsearch::API end end end elasticsearch-ruby-6.8.1/elasticsearch/lib/elasticsearch/000077500000000000000000000000001361161326000235105ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch/lib/elasticsearch/version.rb000066400000000000000000000000551361161326000255220ustar00rootroot00000000000000module Elasticsearch VERSION = '6.8.1' end elasticsearch-ruby-6.8.1/elasticsearch/test/000077500000000000000000000000001361161326000211075ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch/test/integration/000077500000000000000000000000001361161326000234325ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch/test/integration/client_integration_test.rb000066400000000000000000000037331361161326000307050ustar00rootroot00000000000000require 'test_helper' require 'logger' module Elasticsearch module Test class ClientIntegrationTest < Elasticsearch::Test::IntegrationTestCase startup do Elasticsearch::Extensions::Test::Cluster.start(number_of_nodes: 2) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 2) end shutdown do Elasticsearch::Extensions::Test::Cluster.stop(number_of_nodes: 2) if ENV['SERVER'] and Elasticsearch::Extensions::Test::Cluster.running?(number_of_nodes: 2) end context "Elasticsearch client" do setup do system "curl -X DELETE http://#{TEST_HOST}:#{TEST_PORT}/_all > /dev/null 2>&1" @logger = Logger.new(STDERR) @logger.formatter = proc do |severity, datetime, progname, msg| color = case severity when /INFO/ then :green when /ERROR|WARN|FATAL/ then :red when /DEBUG/ then :cyan else :white end ANSI.ansi(severity[0] + ' ', color, :faint) + ANSI.ansi(msg, :white, :faint) + "\n" end @client = Elasticsearch::Client.new host: "#{TEST_HOST}:#{TEST_PORT}", logger: (ENV['QUIET'] ? nil : @logger) end should "perform the API methods" do assert_nothing_raised do # Index a document # @client.index index: 'test-index', type: 'test-type', id: '1', body: { title: 'Test' } # Refresh the index # @client.indices.refresh index: 'test-index' # Search # response = @client.search index: 'test-index', body: { query: { match: { title: 'test' } } } assert_equal 1, response['hits']['total'] assert_equal 'Test', response['hits']['hits'][0]['_source']['title'] # Delete the index # @client.indices.delete index: 'test-index' end end end end end end elasticsearch-ruby-6.8.1/elasticsearch/test/test_helper.rb000066400000000000000000000046631361161326000237630ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) ELASTICSEARCH_HOSTS = if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end end.freeze TEST_HOST, TEST_PORT = ELASTICSEARCH_HOSTS.first.split(':') if ELASTICSEARCH_HOSTS if RUBY_1_8 and not ENV['BUNDLE_GEMFILE'] require 'rubygems' gem 'test-unit' end if ENV['COVERAGE'] && ENV['CI'].nil? && !RUBY_1_8 require 'simplecov' SimpleCov.start { add_filter "/test|test_/" } end if ENV['CI'] && !RUBY_1_8 require 'simplecov' require 'simplecov-rcov' SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start { add_filter "/test|test_" } end # Register `at_exit` handler for integration tests shutdown. # MUST be called before requiring `test/unit`. if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' at_exit { Elasticsearch::Test::IntegrationTestCase.__run_at_exit_hooks } end require 'test/unit' require 'shoulda-context' require 'mocha/setup' require 'turn' unless ENV["TM_FILEPATH"] || ENV["NOTURN"] || RUBY_1_8 require 'require-prof' if ENV["REQUIRE_PROF"] require 'elasticsearch' RequireProf.print_timing_infos if ENV["REQUIRE_PROF"] if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/extensions/test/profiling' unless JRUBY end module Elasticsearch module Test class IntegrationTestCase < ::Test::Unit::TestCase extend Elasticsearch::Extensions::Test::StartupShutdown shutdown { Elasticsearch::Extensions::Test::Cluster.stop if ENV['SERVER'] && started? && Elasticsearch::Extensions::Test::Cluster.running? } context "IntegrationTest" do; should "noop on Ruby 1.8" do; end; end if RUBY_1_8 end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' end module Test class ProfilingTest < ::Test::Unit::TestCase extend Elasticsearch::Extensions::Test::StartupShutdown extend Elasticsearch::Extensions::Test::Profiling shutdown { Elasticsearch::Extensions::Test::Cluster.stop if ENV['SERVER'] && started? && Elasticsearch::Extensions::Test::Cluster.running? } context "IntegrationTest" do; should "noop on Ruby 1.8" do; end; end if RUBY_1_8 end unless RUBY_1_8 || JRUBY end end elasticsearch-ruby-6.8.1/elasticsearch/test/unit/000077500000000000000000000000001361161326000220665ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/elasticsearch/test/unit/wrapper_gem_test.rb000066400000000000000000000010701361161326000257600ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WrapperGemTest < ::Test::Unit::TestCase context "Wrapper gem" do should "require all neccessary subgems" do assert defined? Elasticsearch::Client assert defined? Elasticsearch::API end should "mix the API into the client" do client = Elasticsearch::Client.new assert_respond_to client, :search assert_respond_to client, :cluster assert_respond_to client, :indices end end end end end elasticsearch-ruby-6.8.1/examples/000077500000000000000000000000001361161326000171345ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/examples/percolator/000077500000000000000000000000001361161326000213065ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/examples/percolator/percolator_alerts.rb000066400000000000000000000046321361161326000253640ustar00rootroot00000000000000# An example of using the percolator with Elasticsearch 5.x and higher # ==================================================================== # # See: # # * https://www.elastic.co/blog/elasticsearch-percolator-continues-to-evolve # * https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-percolate-query.html require 'ansi' require 'elasticsearch' client = Elasticsearch::Client.new log: true client.transport.logger.formatter = proc do |severity, datetime, progname, msg| "\e[2m#{msg}\e[0m\n" end # Delete the indices used for the example # client.indices.delete index: ['my-alerts','my-messages'], ignore: 404 # Set up the mapping for the index # # * Register the "percolate" type for the `query` field # * Set up the mapping for the `message` field # client.indices.create index: 'my-alerts', body: { mappings: { doc: { properties: { query: { type: 'percolator' }, message: { type: 'text' } } } } } # Store alert for messages containing "foo" # client.index index: 'my-alerts', type: 'doc', id: 'alert-1', body: { query: { match: { message: 'foo' } } } # Store alert for messages containing "bar" # client.index index: 'my-alerts', type: 'doc', id: 'alert-2', body: { query: { match: { message: 'bar' } } } # Store alert for messages containing "baz" # client.index index: 'my-alerts', type: 'doc', id: 'alert-3', body: { query: { match: { message: 'baz' } } } client.indices.refresh index: 'my-alerts' # Percolate a piece of text against the queries # results = client.search index: 'my-alerts', body: { query: { percolate: { field: 'query', document: { message: "Foo Bar" } } } } puts "Which alerts match the text 'Foo Bar'?".ansi(:bold), '> ' + results['hits']['hits'].map { |r| r['_id'] }.join(', ') client.index index: 'my-messages', type: 'doc', id: 123, body: { message: "Foo Bar Baz" } client.indices.refresh index: 'my-messages' results = client.search index: 'my-alerts', body: { query: { percolate: { field: 'query', index: 'my-messages', type: 'doc', id: 123 } } } puts "Which alerts match the document [my-messages/doc/123]?".ansi(:bold), '> ' + results['hits']['hits'].map { |r| r['_id'] }.join(', ') elasticsearch-ruby-6.8.1/examples/rabbitmq/000077500000000000000000000000001361161326000207355ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/examples/rabbitmq/Gemfile000066400000000000000000000001331361161326000222250ustar00rootroot00000000000000source 'https://rubygems.org' gem 'elasticsearch' gem 'bunny' gem 'multi_json' gem 'oj' elasticsearch-ruby-6.8.1/examples/rabbitmq/consumer-publisher.rb000066400000000000000000000021221361161326000251050ustar00rootroot00000000000000# Example of listening to a RabbitMQ queue and indexing the payload # # Usage: # # $ bundle install # $ bundle exec ruby consume-publish.rb # require 'multi_json' require 'oj' require 'elasticsearch' require 'bunny' connection = Bunny.new connection.start channel = connection.create_channel queue = channel.queue 'examples.elasticsearch', auto_delete: true exchange = channel.default_exchange elasticsearch = Elasticsearch::Client.new log:true elasticsearch.indices.delete index: 'rabbit' rescue nil queue.subscribe do |delivery_info, metadata, payload| hash = MultiJson.load(payload) elasticsearch.index index: 'rabbit', type: 'event', id: hash.delete(:id), body: hash end (1..10).each do |i| exchange.publish MultiJson.dump({id: i, title: "Test #{i}"}), routing_key: queue.name end sleep 1.0 puts "Enter some words to index (use Ctrl+C to exit):" [:INT, :TERM].each do |signal| trap(signal) { puts "\nExiting..."; exit } end while input = gets exchange.publish MultiJson.dump({title: input.chomp}), routing_key: queue.name unless input =~ /^\s*$/ end connection.close elasticsearch-ruby-6.8.1/rake_tasks/000077500000000000000000000000001361161326000174455ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/rake_tasks/elasticsearch_tasks.rake000066400000000000000000000163661361161326000243440ustar00rootroot00000000000000ELASTICSEARCH_PATH = "#{CURRENT_PATH}/tmp/elasticsearch" desc "Clone elasticsearch into the ./tmp directory" task :setup do unless File.exist?('./tmp/elasticsearch') sh "git clone https://github.com/elasticsearch/elasticsearch.git tmp/elasticsearch" end end namespace :elasticsearch do desc "Wait for elasticsearch cluster to be in green state" task :wait_for_green do require 'elasticsearch' ready = nil 5.times do |i| begin puts "Attempting to wait for green status: #{i + 1}" if admin_client.cluster.health(wait_for_status: 'green', timeout: '50s') ready = true puts 'Connected to Elasticsearch' break end rescue Elasticsearch::Transport::Transport::Errors::RequestTimeout => ex puts "Couldn't confirm green status.\n#{ex.inspect}." rescue Faraday::ConnectionFailed => ex puts "Couldn't connect to Elasticsearch.\n#{ex.inspect}." sleep(30) end end unless ready puts "Couldn't connect to Elasticsearch, aborting program." exit(1) end end desc "Update the submodule with Elasticsearch core repository" task :update => :setup do sh "git --git-dir=#{CURRENT_PATH.join('tmp/elasticsearch/.git')} --work-tree=#{CURRENT_PATH.join('tmp/elasticsearch')} fetch origin --quiet" begin %x[git --git-dir=#{CURRENT_PATH.join('tmp/elasticsearch/.git')} --work-tree=#{CURRENT_PATH.join('tmp/elasticsearch')} pull] rescue Exception => @exception @failed = true end if @failed || !$?.success? STDERR.puts "", "[!] Error while pulling -- #{@exception}" end puts "\n", "CHANGES:", '-'*80 sh "git --git-dir=#{CURRENT_PATH.join('tmp/elasticsearch/.git')} --work-tree=#{CURRENT_PATH.join('tmp/elasticsearch')} log --oneline ORIG_HEAD..HEAD | cat", :verbose => false end desc <<-DESC Build Elasticsearch for the specified branch ('origin/master' by default)" Build a specific branch: $ rake elasticsearch:build[origin/1.x] The task will execute `git fetch` to synchronize remote branches. DESC task :build, :branch do |task, args| Rake::Task['elasticsearch:status'].invoke puts '-'*80 gitref = args[:branch] || 'origin/master' es_version = gitref.gsub(/^v|origin\/(\d\.+)/, '\1').to_f current_branch = `git --git-dir=#{CURRENT_PATH.join('tmp/elasticsearch/.git')} --work-tree=#{CURRENT_PATH.join('tmp/elasticsearch')} branch --no-color`.split("\n").select { |b| b =~ /^\*/ }.first.gsub(/^\*\s*/, '') STDOUT.puts "Building version [#{es_version}] from [#{gitref}]:", "" case es_version when 0.0, 5..1000 path_to_build = CURRENT_PATH.join('tmp/elasticsearch/distribution/tar/build/distributions/elasticsearch-*.tar.gz') build_command = "cd #{CURRENT_PATH.join('tmp/elasticsearch/distribution/tar')} && gradle clean assemble;" extract_command = <<-CODE.gsub(/ /, '') build=`ls #{path_to_build} | xargs -0 basename | sed s/\.tar\.gz//` if [[ $build ]]; then rm -rf "#{CURRENT_PATH.join('tmp/builds')}/$build"; else echo "Cannot determine build, exiting..." exit 1 fi tar xvf #{path_to_build} -C #{CURRENT_PATH.join('tmp/builds')}; CODE when 1.8..4 path_to_build = CURRENT_PATH.join('tmp/elasticsearch/distribution/tar/target/releases/elasticsearch-*.tar.gz') build_command = "cd #{CURRENT_PATH.join('tmp/elasticsearch')} && MAVEN_OPTS=-Xmx1g mvn --projects core,distribution/tar clean package -DskipTests -Dskip.integ.tests;" extract_command = <<-CODE.gsub(/ /, '') build=`ls #{path_to_build} | xargs -0 basename | sed s/\.tar\.gz//` if [[ $build ]]; then rm -rf "#{CURRENT_PATH.join('tmp/builds')}/$build"; else echo "Cannot determine build, exiting..." exit 1 fi tar xvf #{path_to_build} -C #{CURRENT_PATH.join('tmp/builds')}; CODE when 0.1..1.7 path_to_build = CURRENT_PATH.join('tmp/elasticsearch/target/releases/elasticsearch-*.tar.gz') build_command = "cd #{CURRENT_PATH.join('tmp/elasticsearch')} && MAVEN_OPTS=-Xmx1g mvn clean package -DskipTests" extract_command = <<-CODE.gsub(/ /, '') build=`ls #{path_to_build} | xargs -0 basename | sed s/\.tar\.gz//` if [[ $build ]]; then rm -rf "#{CURRENT_PATH.join('tmp/builds')}/$build"; else echo "Cannot determine build, exiting..." exit 1 fi tar xvf #{path_to_build} -C #{CURRENT_PATH.join('tmp/builds')}; CODE else STDERR.puts "", "[!] Cannot determine a compatible version of the build (gitref: #{gitref}, es_version: #{es_version})" exit(1) end sh <<-CODE.gsub(/ /, '') mkdir -p #{CURRENT_PATH.join('tmp/builds')}; rm -rf '#{CURRENT_PATH.join('tmp/elasticsearch/distribution/tar/target/')}'; cd #{CURRENT_PATH.join('tmp/elasticsearch')} && git fetch origin --quiet; cd #{CURRENT_PATH.join('tmp/elasticsearch')} && git checkout #{gitref}; #{build_command} #{extract_command} echo; echo; echo "Built: $build" CODE puts "", '-'*80, "" Rake::Task['elasticsearch:builds'].invoke end desc "Display the info for all branches in the Elasticsearch submodule" task :status do sh "git --git-dir=#{CURRENT_PATH.join('tmp/elasticsearch/.git')} --work-tree=#{CURRENT_PATH.join('tmp/elasticsearch')} branch -v -v", :verbose => false end desc "Display the list of builds" task :builds do system "mkdir -p #{CURRENT_PATH.join('tmp/builds')};" puts "Builds:" Dir.entries(CURRENT_PATH.join('tmp/builds')).reject { |f| f =~ /^\./ }.each do |build| puts "* #{build}" end end desc "Display the history of the 'rest-api-spec' repo" task :changes do STDERR.puts "Log: #{CURRENT_PATH.join('tmp/elasticsearch')}/rest-api-spec", "" sh "git --git-dir=#{CURRENT_PATH.join('tmp/elasticsearch/.git')} --work-tree=#{CURRENT_PATH.join('tmp/elasticsearch')} log --pretty=format:'%C(yellow)%h%Creset %s \e[2m[%ar by %an]\e[0m' -- rest-api-spec", :verbose => false end desc "Checkout the build hash from the running Elasticsearch server" task :checkout_build do require 'elasticsearch' branches = `git --git-dir=#{ELASTICSEARCH_PATH}/.git --work-tree=#{ELASTICSEARCH_PATH} branch --no-color` current_branch = branches. split("\n"). select { |b| b =~ /^\*/ }. reject { |b| b =~ /no branch|detached/ }. map { |b| b.gsub(/^\*\s*/, '') }. first unless current_branch STDERR.puts "[!] Unable to determine current branch, defaulting to 'master'" current_branch = 'master' end es_version_info = admin_client.info['version'] unless build_hash = es_version_info['build_hash'] STDERR.puts "[!] Cannot determine checkout build hash -- server not running" exit(1) end name = ENV['CI'] ? build_hash : "[\e[1m#{build_hash}\e[0m]" STDERR.puts '-'*80, "YAML tests: Switching to #{name} from #{current_branch}", '-'*80 git_specs("checkout #{build_hash} --force --quiet") end end def git_specs(command, options={}) sh "git --git-dir=#{ELASTICSEARCH_PATH}/.git --work-tree=#{ELASTICSEARCH_PATH} #{command}", options end elasticsearch-ruby-6.8.1/rake_tasks/test_tasks.rake000066400000000000000000000044271361161326000225040ustar00rootroot00000000000000UNIT_TESTED_PROJECTS = [ 'elasticsearch', 'elasticsearch-transport', 'elasticsearch-dsl', 'elasticsearch-api', 'elasticsearch-extensions' ].freeze INTEGRATION_TESTED_PROJECTS = (UNIT_TESTED_PROJECTS - ['elasticsearch-api']).freeze namespace :test do task :bundle => 'bundle:install' desc "Run all tests in all subprojects" task :client => [ :unit, :integration ] desc "Run unit tests in all subprojects" task :unit do UNIT_TESTED_PROJECTS.each do |project| puts '-'*80 sh "cd #{CURRENT_PATH.join(project)} && unset BUNDLE_GEMFILE && unset BUNDLE_PATH && unset BUNDLE_BIN && bundle exec rake test:unit" puts "\n" end end desc "Run integration tests in all subprojects" task :integration do INTEGRATION_TESTED_PROJECTS.each do |project| puts '-'*80 sh "cd #{CURRENT_PATH.join(project)} && unset BUNDLE_GEMFILE && bundle exec rake test:integration" puts "\n" end end desc "Run rest api tests" task :rest_api => 'elasticsearch:update' do puts '-' * 80 sh "cd #{CURRENT_PATH.join('elasticsearch-api')} && unset BUNDLE_GEMFILE && bundle exec rake test:integration" puts "\n" end desc "Run security (Platinum) rest api yaml tests" task :security => 'elasticsearch:update' do Rake::Task['elasticsearch:wait_for_green'].invoke Rake::Task['elasticsearch:checkout_build'].invoke puts '-' * 80 sh "cd #{CURRENT_PATH.join('elasticsearch-xpack')} && unset BUNDLE_GEMFILE && bundle exec rake test:rest_api" puts "\n" end namespace :cluster do desc "Start Elasticsearch nodes for tests" task :start do require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.start end desc "Stop Elasticsearch nodes for tests" task :stop do require 'elasticsearch/extensions/test/cluster' Elasticsearch::Extensions::Test::Cluster.stop end task :status do require 'elasticsearch/extensions/test/cluster' (puts "\e[31m[!] Test cluster not running\e[0m"; exit(1)) unless Elasticsearch::Extensions::Test::Cluster.running? Elasticsearch::Extensions::Test::Cluster.__print_cluster_info(ENV['TEST_CLUSTER_PORT'] || 9250) end end endelasticsearch-ruby-6.8.1/scripts/000077500000000000000000000000001361161326000170055ustar00rootroot00000000000000elasticsearch-ruby-6.8.1/scripts/wait-cluster.sh000077500000000000000000000010231361161326000217630ustar00rootroot00000000000000#!/bin/bash TEST_ES_SERVER=${TEST_ES_SERVER:-"http://localhost:9200"} echo $TEST_ES_SERVER attempt_counter=0 max_attempts=5 url="${TEST_ES_SERVER}/_cluster/health?wait_for_status=green&timeout=50s" echo "Waiting for Elasticsearch..." while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' --max-time 55 "$url")" != "200" ]]; do if [ ${attempt_counter} -eq ${max_attempts} ];then echo "\nCouldn't connect to Elasticsearch" exit 1 fi printf '.' attempt_counter=$(($attempt_counter+1)) sleep 5 done echo "\nReady"