pax_global_header00006660000000000000000000000064125334125720014516gustar00rootroot0000000000000052 comment=242f09a3e5efc9d53c50fa88600778019d075a96 elasticsearch-ruby-1.0.12/000077500000000000000000000000001253341257200153705ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/.gitignore000066400000000000000000000000751253341257200173620ustar00rootroot00000000000000.config .yardoc _yardoc coverage doc/ rdoc/ tmp Gemfile.lock elasticsearch-ruby-1.0.12/.travis.yml000066400000000000000000000017771253341257200175150ustar00rootroot00000000000000# ------------------------------------------------------------------------------- # Configuration file for http://travis-ci.org/#!/elasticsearch/elasticsearch-ruby # ------------------------------------------------------------------------------- language: ruby branches: only: - master - travis rvm: - 1.8.7 - 1.9.3 - 2.1 - 2.2 jdk: - openjdk7 env: - TEST_SUITE=unit - TEST_SUITE=integration before_install: - gem update --system - gem --version install: - test $TEST_SUITE == 'integration' && curl -# https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.0.0.tar.gz | tar xz -C /tmp || true before_script: - rake setup - rake elasticsearch:update - rake bundle:clean - rake bundle:install script: - SERVER=start TEST_BUILD_REF=tags/v1.0.0 TEST_CLUSTER_COMMAND=/tmp/elasticsearch-1.0.0/bin/elasticsearch rake test:$TEST_SUITE matrix: exclude: - rvm: 1.8.7 jdk: openjdk7 env: TEST_SUITE=integration notifications: disable: true elasticsearch-ruby-1.0.12/CHANGELOG.md000066400000000000000000000164251253341257200172110ustar00rootroot00000000000000## 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-1.0.12/CONTRIBUTING.md000066400000000000000000000022531253341257200176230ustar00rootroot00000000000000The 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-1.0.12/Gemfile000066400000000000000000000017241253341257200166670ustar00rootroot00000000000000source 'https://rubygems.org' gem "bundler", "> 1" gem "rake" 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 "pry" gem "ansi" gem "shoulda-context" gem "mocha" gem "turn" gem "yard" gem "ci_reporter", "~> 1.9" 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-1.0.12/README.md000066400000000000000000000133631253341257200166550ustar00rootroot00000000000000# Elasticsearch This repository contains Ruby integrations for [Elasticsearch](http://elasticsearch.org): * 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 project. ## Compatibility The libraries are compatible with Ruby 1.8.7 and higher. The library is compatible with Elasticsearch 0.90 and 1.0 -- you have to install and use a matching version, though. The 1.x versions and the master branch are compatible with **Elasticsearch 1.x** API. To use the **Elasticsearch 0.90** API, install the **0.4.x** gem version or use the corresponding [`0.4`](https://github.com/elasticsearch/elasticsearch-ruby/tree/0.4) branch. ## 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](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 ```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). ### Transport * [README](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/README.md) * [Documentation](http://rubydoc.info/gems/elasticsearch-transport) * [Test Suite](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-transport/test) ### API * [README](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-api/README.md) * [Documentation](http://rubydoc.info/gems/elasticsearch-api/) * [Test Suite](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-api/test) ### Extensions * [README](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-extensions/README.md) * [Documentation](http://rubydoc.info/gems/elasticsearch-extensions/) * [Test Suite](https://github.com/elasticsearch/elasticsearch-ruby/blob/master/elasticsearch-extensions/test) ## 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): ``` 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-1.0.12/Rakefile000066400000000000000000000156461253341257200170510ustar00rootroot00000000000000require 'pathname' subprojects = %w| elasticsearch elasticsearch-transport elasticsearch-api elasticsearch-extensions | __current__ = Pathname( File.expand_path('..', __FILE__) ) # TODO: Figure out "bundle exec or not" # subprojects.each { |project| $LOAD_PATH.unshift __current__.join(project, "lib").to_s } 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__.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 "Setup the project" task :setup do unless File.exists?('./tmp/elasticsearch') sh "git clone https://github.com/elasticsearch/elasticsearch.git tmp/elasticsearch" end end desc "Alias for `bundle:install`" task :bundle => 'bundle:install' namespace :bundle do desc "Run `bundle install` in all subprojects" task :install do puts '-'*80 sh "bundle install --gemfile #{__current__}/Gemfile" puts subprojects.each do |project| puts '-'*80 sh "bundle install --gemfile #{__current__.join(project)}/Gemfile" puts end end desc "Remove Gemfile.lock in all subprojects" task :clean do sh "rm -f Gemfile.lock" subprojects.each do |project| sh "rm -f #{__current__.join(project)}/Gemfile.lock" end end end namespace :elasticsearch do desc "Update the submodule with Elasticsearch core repository" task :update do sh "git --git-dir=#{__current__.join('tmp/elasticsearch/.git')} --work-tree=#{__current__.join('tmp/elasticsearch')} fetch origin --verbose" begin puts %x[git --git-dir=#{__current__.join('tmp/elasticsearch/.git')} --work-tree=#{__current__.join('tmp/elasticsearch')} pull --verbose] 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__.join('tmp/elasticsearch/.git')} --work-tree=#{__current__.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 branch = args[:branch] || 'origin/master' current_branch = `git --git-dir=#{__current__.join('tmp/elasticsearch/.git')} --work-tree=#{__current__.join('tmp/elasticsearch')} branch --no-color`.split("\n").select { |b| b =~ /^\*/ }.first.gsub(/^\*\s*/, '') begin sh <<-CODE mkdir -p #{__current__.join('tmp/builds')}; rm -rf '#{__current__.join('tmp/elasticsearch/target')}'; cd #{__current__.join('tmp/elasticsearch')} && git fetch origin --quiet; cd #{__current__.join('tmp/elasticsearch')} && git checkout #{branch}; cd #{__current__.join('tmp/elasticsearch')} && mvn clean package -DskipTests; build=`ls #{__current__.join('tmp/elasticsearch/target/releases/elasticsearch-*.tar.gz')} | xargs -0 basename | sed s/\.tar\.gz//` && \ rm -rf "#{__current__.join('tmp/builds')}/$build"; tar xvf target/releases/elasticsearch-*.tar.gz -C #{__current__.join('tmp/builds')}; echo; echo; echo "Built: $build" CODE end 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__.join('tmp/elasticsearch/.git')} --work-tree=#{__current__.join('tmp/elasticsearch')} branch -v -v", :verbose => false end desc "Display the list of builds" task :builds do puts "Builds:" Dir.entries(__current__.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__.join('tmp/elasticsearch')}/rest-api-spec", "" sh "git --git-dir=#{__current__.join('tmp/elasticsearch/.git')} --work-tree=#{__current__.join('tmp/elasticsearch')} log --pretty=format:'%C(yellow)%h%Creset %s \e[2m[%ar by %an]\e[0m' -- rest-api-spec", :verbose => false end end namespace :test do task :bundle => 'bundle:install' desc "Run unit tests in all subprojects" task :unit do Rake::Task['test:ci_reporter'].invoke if ENV['CI'] subprojects.each do |project| puts '-'*80 sh "cd #{__current__.join(project)} && unset BUNDLE_GEMFILE && bundle exec rake test:unit" puts "\n" end end desc "Run integration tests in all subprojects" task :integration do Rake::Task['elasticsearch:update'].invoke Rake::Task['test:ci_reporter'].invoke if ENV['CI'] subprojects.each do |project| puts '-'*80 sh "cd #{__current__.join(project)} && unset BUNDLE_GEMFILE && bundle exec rake test:integration" puts "\n" end end desc "Run all tests in all subprojects" task :all do Rake::Task['test:ci_reporter'].invoke if ENV['CI'] subprojects.each do |project| puts '-'*80 sh "cd #{__current__.join(project)} && unset BUNDLE_GEMFILE && bundle exec rake test:all" puts "\n" end end task :ci_reporter do ENV['CI_REPORTS'] ||= 'tmp/reports' if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' require 'ci/reporter/rake/test_unit' Rake::Task['ci:setup:testunit'].invoke else require 'ci/reporter/rake/minitest' Rake::Task['ci:setup:minitest'].invoke end 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 end desc "Generate documentation for all subprojects" task :doc do subprojects.each do |project| sh "cd #{__current__.join(project)} && rake doc" puts '-'*80 end end desc "Release all subprojects to Rubygems" task :release do subprojects.each do |project| next if project == 'elasticsearch-extensions' sh "cd #{__current__.join(project)} && rake release" puts '-'*80 end end elasticsearch-ruby-1.0.12/elasticsearch-api/000077500000000000000000000000001253341257200207515ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/.gitignore000066400000000000000000000002321253341257200227360ustar00rootroot00000000000000*.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-1.0.12/elasticsearch-api/Gemfile000066400000000000000000000012761253341257200222520ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-api.gemspec gemspec if File.exists? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-transport", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => true end if File.exists? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end elasticsearch-ruby-1.0.12/elasticsearch-api/LICENSE.txt000066400000000000000000000010561253341257200225760ustar00rootroot00000000000000Copyright (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-1.0.12/elasticsearch-api/README.md000066400000000000000000000137631253341257200222420ustar00rootroot00000000000000# 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.8.7 or higher. The library is compatible with Elasticsearch 0.90 and 1.0 -- you have to install and use a matching version, though. The 1.x versions and the master branch are compatible with **Elasticsearch 1.x** API. To use the **Elasticsearch 0.90** API, install the **0.4.x** gem version or use the corresponding [`0.4`](https://github.com/elasticsearch/elasticsearch-ruby/tree/0.4) branch. ## 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' } }, facets: { tags: { terms: { field: 'tags' } } } } mash = Hashie::Mash.new response mash.hits.hits.first._source.title # => 'Test' mash.facets.tags.terms.first # => # ``` ## 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-1.0.12/elasticsearch-api/Rakefile000066400000000000000000000123161253341257200224210ustar00rootroot00000000000000require "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' namespace :test do desc "Update the repository with YAML tests" task :update do git_specs "fetch origin --verbose", :verbose => true end task :ci_reporter do ENV['CI_REPORTS'] ||= 'tmp/reports' if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' require 'ci/reporter/rake/test_unit' Rake::Task['ci:setup:testunit'].invoke else require 'ci/reporter/rake/minitest' Rake::Task['ci:setup:minitest'].invoke end end Rake::TestTask.new(:unit) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] # test.verbose = true # test.warning = true end desc "Run integration tests" task :integration 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| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/yaml_test_runner.rb", "test/integration/**/*_test.rb"] end # Check if a test cluster is running begin client = Elasticsearch::Client.new :host => "localhost:#{ENV['TEST_CLUSTER_PORT'] || 9250}" es_version_info = client.info['version'] build_hash = es_version_info['build_hash'] cluster_running = true rescue Faraday::Error::ConnectionFailed => e 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 # Path to the API specs ENV['TEST_REST_API_SPEC'] = __current__.join('../tmp/elasticsearch/rest-api-spec/test/').to_s # 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:ci_reporter'].invoke if ENV['CI'] 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-1.0.12/elasticsearch-api/elasticsearch-api.gemspec000066400000000000000000000051001253341257200256730ustar00rootroot00000000000000# 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" 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.add_dependency "multi_json" s.add_development_dependency "bundler", "> 1" s.add_development_dependency "rake" 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" s.add_development_dependency "ci_reporter", "~> 1.9" # 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" 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-1.0.12/elasticsearch-api/lib/000077500000000000000000000000001253341257200215175ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch-api.rb000066400000000000000000000000341253341257200254220ustar00rootroot00000000000000require 'elasticsearch/api' elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/000077500000000000000000000000001253341257200243315ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api.rb000066400000000000000000000034771253341257200254420ustar00rootroot00000000000000require "cgi" require "multi_json" require "elasticsearch/api/version" require "elasticsearch/api/namespace/common" require "elasticsearch/api/utils" 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 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 = [ :format, # Search, Cat, ... :pretty, # Pretty-print the response :human # Return numeric values in human readable format ] 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::Snapshot, Elasticsearch::API::Cat end module ClassMethods # Access the module settings # def settings @settings ||= {} end end extend ClassMethods end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/000077500000000000000000000000001253341257200251025ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/000077500000000000000000000000001253341257200265425ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/abort_benchmark.rb000066400000000000000000000012071253341257200322100ustar00rootroot00000000000000module 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/master/search-benchmark.html # def abort_benchmark(arguments={}) valid_params = [ ] method = HTTP_POST path = "_bench/abort/#{arguments[:name]}" params = {} body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/benchmark.rb000066400000000000000000000040231253341257200310200ustar00rootroot00000000000000module 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/master/search-benchmark.html # def benchmark(arguments={}) valid_params = [ :verbose ] method = HTTP_PUT path = "_bench" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/bulk.rb000066400000000000000000000067331253341257200300350ustar00rootroot00000000000000module Elasticsearch module API module Actions # Perform multiple index, delete or update operations in a single request. # # Pass the operations in the `:body` option as an array of hashes, following Elasticsearch conventions. # For operations which take data, pass them as the `:data` option in the operation hash. # # @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 [Array] :body An array of operations to perform, each operation is a Hash # @option arguments [String] :consistency Explicit write consistency setting for the operation # (options: one, quorum, all) # @option arguments [Boolean] :refresh Refresh the index after performing the operation # @option arguments [String] :replication Explicitly set the replication type (options: sync, async) # @option arguments [Time] :timeout Explicit operation timeout # # @return [Hash] Deserialized Elasticsearch response # # @see http://elasticsearch.org/guide/reference/api/bulk/ # def bulk(arguments={}) valid_params = [ :consistency, :refresh, :replication, :type, :timeout ] method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_bulk' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] if body.is_a? Array payload = Utils.__bulkify(body) else payload = body end perform_request(method, path, params, payload).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/000077500000000000000000000000001253341257200273115ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/aliases.rb000066400000000000000000000045551253341257200312700ustar00rootroot00000000000000module 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 information as Ruby objects # # client.cat.aliases format: 'json' # # @option arguments [List] :name A comma-separated list of alias names to return # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-aliases.html # def aliases(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] name = arguments.delete(:name) method = HTTP_GET path = Utils.__pathify '_cat/aliases', Utils.__listify(name) params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/allocation.rb000066400000000000000000000051051253341257200317640ustar00rootroot00000000000000module 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] :bytes The unit in which to display byte values (options: b, k, m, g) # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-allocation.html # def allocation(arguments={}) valid_params = [ :bytes, :local, :master_timeout, :h, :help, :v ] 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, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/count.rb000066400000000000000000000043441253341257200307730ustar00rootroot00000000000000module 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 [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-count.html # def count(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/count', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/fielddata.rb000066400000000000000000000034321253341257200315550ustar00rootroot00000000000000module 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 include in the output # @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 [Boolean] :help Return help information # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-fielddata.html # def fielddata(arguments={}) valid_params = [ :bytes, :local, :master_timeout, :h, :help, :v, :fields ] fields = arguments.delete(:fields) method = HTTP_GET path = Utils.__pathify "_cat/fielddata", Utils.__listify(fields) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/health.rb000066400000000000000000000035511253341257200311070ustar00rootroot00000000000000module 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 [Boolean] :ts Whether to display timestamp information # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-health.html # def health(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :ts, :v ] method = HTTP_GET path = "_cat/health" params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/help.rb000066400000000000000000000011771253341257200305740ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Help information for the Cat API # # @option arguments [Boolean] :help Return help information # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html # def help(arguments={}) valid_params = [ :help ] method = HTTP_GET path = "_cat" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/indices.rb000066400000000000000000000057141253341257200312630ustar00rootroot00000000000000module 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] :bytes The unit in which to display byte values (options: b, k, m, g) # @option arguments [Boolean] :pri Limit the returned information on primary shards only (default: false) # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-indices.html # def indices(arguments={}) valid_params = [ :bytes, :local, :master_timeout, :h, :help, :pri, :v ] index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/indices', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/master.rb000066400000000000000000000032051253341257200311310ustar00rootroot00000000000000module 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 [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-master.html # def master(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] method = HTTP_GET path = "_cat/master" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/nodes.rb000066400000000000000000000043041253341257200307470ustar00rootroot00000000000000module 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 [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-nodes.html # def nodes(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] method = HTTP_GET path = "_cat/nodes" params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/pending_tasks.rb000066400000000000000000000034321253341257200324710ustar00rootroot00000000000000module 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 [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-pending-tasks.html # def pending_tasks(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] method = HTTP_GET path = "_cat/pending_tasks" params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/plugins.rb000066400000000000000000000022441253341257200313210ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Return information about installed plugins # # @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 [Boolean] :v Verbose mode. Display column headers # # @see http://www.elastic.co/guide/en/elasticsearch/reference/master/cat-plugins.html # def plugins(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] method = 'GET' path = "/_cat/plugins" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/recovery.rb000066400000000000000000000053111253341257200314740ustar00rootroot00000000000000module 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] :bytes The unit in which to display byte values (options: b, k, m, g) # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-recovery.html # def recovery(arguments={}) valid_params = [ :bytes, :local, :master_timeout, :h, :help, :v ] index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/recovery', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/segments.rb000066400000000000000000000021321253341257200314610ustar00rootroot00000000000000module 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 [List] :h Comma-separated list of column names to display # @option arguments [Boolean] :help Return help information # @option arguments [Boolean] :v Verbose mode. Display column headers # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-segments.html # def segments(arguments={}) valid_params = [ :h, :help, :v ] method = 'GET' path = "_cat/segments" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/shards.rb000066400000000000000000000052571253341257200311330ustar00rootroot00000000000000module 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 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] :bytes The unit in which to display byte values (options: b, k, m, g) # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-shards.html # def shards(arguments={}) valid_params = [ :local, :master_timeout, :h, :help, :v ] index = arguments.delete(:index) method = HTTP_GET path = Utils.__pathify '_cat/shards', Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cat/thread_pool.rb000066400000000000000000000043431253341257200321420ustar00rootroot00000000000000module Elasticsearch module API module Cat module Actions # Display thread pool statistics across nodes (use the `help` parameter to display a list # of avaialable 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 [Boolean] :full_id Display the complete node ID # @option arguments [List] :h Comma-separated list of column names to display -- see the `help` argument # @option arguments [Boolean] :v Display column headers as part of the output # @option arguments [String] :format The output format. Options: 'text', 'json'; default: 'text' # @option arguments [Boolean] :help Return information about headers # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-thread-pool.html # def thread_pool(arguments={}) valid_params = [ :full_id, :local, :master_timeout, :h, :help, :v ] method = HTTP_GET path = "_cat/thread_pool" params = Utils.__validate_and_extract_params arguments, valid_params params[:h] = Utils.__listify(params[:h]) if params[:h] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/clear_scroll.rb000066400000000000000000000020101253341257200315240ustar00rootroot00000000000000module 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 # # @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] scroll_id = arguments[:body] || arguments.delete(:scroll_id) scroll_ids = case scroll_id when Array scroll_id.join(',') else scroll_id end method = HTTP_DELETE path = Utils.__pathify '_search/scroll' params = {} body = scroll_ids perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/000077500000000000000000000000001253341257200302235ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/get_settings.rb000066400000000000000000000015371253341257200332550ustar00rootroot00000000000000module 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) # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-update-settings/ # def get_settings(arguments={}) valid_params = [ :flat_settings ] method = HTTP_GET path = "_cluster/settings" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/health.rb000066400000000000000000000043631253341257200320230ustar00rootroot00000000000000module 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 [String] :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 [Number] :wait_for_active_shards Wait until the specified number of shards is active # @option arguments [Number] :wait_for_nodes Wait until the specified number of nodes is available # @option arguments [Number] :wait_for_relocating_shards Wait until the specified number of relocating # shards is finished # @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={}) valid_params = [ :level, :local, :master_timeout, :timeout, :wait_for_active_shards, :wait_for_nodes, :wait_for_relocating_shards, :wait_for_status ] method = HTTP_GET path = "_cluster/health" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/pending_tasks.rb000066400000000000000000000022371253341257200334050ustar00rootroot00000000000000module 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/master/cluster-pending.html # def pending_tasks(arguments={}) valid_params = [ :local, :master_timeout ] method = HTTP_GET path = "/_cluster/pending_tasks" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/put_settings.rb000066400000000000000000000017471253341257200333110ustar00rootroot00000000000000module 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). # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-update-settings/ # def put_settings(arguments={}) valid_params = [ :flat_settings ] method = HTTP_PUT path = "_cluster/settings" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] || {} perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/reroute.rb000066400000000000000000000040261253341257200322370ustar00rootroot00000000000000module 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 for why the commands can or cannot be executed # @option arguments [Boolean] :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 Specify timeout for connection to master # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-reroute/ # def reroute(arguments={}) valid_params = [ :dry_run, :explain, :metric, :master_timeout, :timeout ] method = HTTP_POST path = "_cluster/reroute" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] || {} perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/cluster/state.rb000066400000000000000000000050611253341257200316720ustar00rootroot00000000000000module 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 omit to # perform the operation on all indices # @option arguments [List] :metric Limit the information returned to the specified metrics # (options: _all, blocks, index_templates, metadata, nodes, routing_table, # master_node, version) # @option arguments [List] :index_templates A comma separated list to return specific index templates when # returning metadata # @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 [String] :expand_wildcards Whether to expand wildcard expression for inidices # (options: open, closed) # @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when # unavailable (missing, closed, etc) # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-state/ # def state(arguments={}) arguments = arguments.clone index = arguments.delete(:index) metric = arguments.delete(:metric) valid_params = [ :metric, :index_templates, :local, :master_timeout, :flat_settings, :expand_wildcards, :ignore_unavailable ] method = HTTP_GET path = "_cluster/state" path = Utils.__pathify '_cluster/state', Utils.__listify(metric), Utils.__listify(index) params = Utils.__validate_and_extract_params arguments, valid_params [: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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/count.rb000066400000000000000000000071401253341257200302210ustar00rootroot00000000000000module 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] :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://elasticsearch.org/guide/reference/api/count/ # def count(arguments={}) valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :min_score, :preference, :routing, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :lowercase_expanded_terms ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_count' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/count_percolate.rb000066400000000000000000000100131253341257200322500ustar00rootroot00000000000000module 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/master/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] valid_params = [ :routing, :preference, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_index, :percolate_type, :version, :version_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, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/create.rb000066400000000000000000000017401253341257200303340ustar00rootroot00000000000000module Elasticsearch module API module Actions # Create a document. # # Enforce the _create_ operation when indexing a document -- # the operation will return an error when the document already exists. # # @example Create a document # # client.create index: 'myindex', # type: 'mytype', # id: '1', # body: { # title: 'Test 1', # tags: ['y', 'z'], # published: true, # published_at: Time.now.utc.iso8601, # counter: 1 # } # # @option (see Actions#index) # # (The `:op_type` argument is ignored.) # # @see http://elasticsearch.org/guide/reference/api/index_/ # def create(arguments={}) index arguments.update :op_type => 'create' end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/delete.rb000066400000000000000000000051471253341257200303400ustar00rootroot00000000000000module 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 [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment # @option arguments [String] :index The name of the index (*Required*) # @option arguments [String] :type The type of the document (*Required*) # @option arguments [String] :consistency Specific write consistency setting for the operation # (options: one, quorum, all) # @option arguments [String] :parent ID of parent document # @option arguments [Boolean] :refresh Refresh the index after performing the operation # @option arguments [String] :replication Specific replication type (options: sync, async) # @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) # # @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] valid_params = [ :consistency, :parent, :refresh, :replication, :routing, :timeout, :version, :version_type ] 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, valid_params 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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/delete_by_query.rb000066400000000000000000000075161253341257200322610ustar00rootroot00000000000000module 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 indices to restrict the operation; # use `_all`to perform the operation on all indices (*Required*) # @option arguments [List] :type A comma-separated list of types to restrict the operation # @option arguments [Hash] :body A query to restrict the operation # @option arguments [String] :analyzer The analyzer to use for the query string # @option arguments [String] :consistency Specific write consistency setting for the operation # (options: one, quorum, all) # @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] :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 [String] :replication Specific replication type (options: sync, async) # @option arguments [String] :q Query in the Lucene query string syntax # @option arguments [String] :routing Specific routing value # @option arguments [String] :source The URL-encoded query definition (instead of using the request body) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/delete-by-query/ # def delete_by_query(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :analyzer, :consistency, :default_operator, :df, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :replication, :q, :routing, :source, :timeout ] method = HTTP_DELETE path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '/_query' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/delete_script.rb000066400000000000000000000022001253341257200317070ustar00rootroot00000000000000module Elasticsearch module API module Actions # Remove an indexed script from Elasticsearch # # @option arguments [String] :id Script ID (*Required*) # @option arguments [String] :lang Script language (*Required*) # @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/modules-scripting.html # def delete_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'lang' missing" unless arguments[:lang] valid_params = [ :version, :version_type ] method = HTTP_DELETE path = "_scripts/#{arguments.delete(:lang)}/#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/delete_template.rb000066400000000000000000000010321253341257200322200ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/exists.rb000066400000000000000000000037221253341257200304120ustar00rootroot00000000000000module 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 (default: `_all`) # @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 # # @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 valid_params = [ :parent, :preference, :realtime, :refresh, :routing ] 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, valid_params body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists?, :exists end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/explain.rb000066400000000000000000000101111253341257200305210ustar00rootroot00000000000000module 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 (*Required*) # @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] :fields A comma-separated list of 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 [Boolean] :lowercase_expanded_terms Specify whether query terms should be lowercased # @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 [String] :source The URL-encoded query definition (instead of using the request body) # @option arguments [String] :_source Specify whether the _source field should be returned, # or a list of fields to return # @option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field # @option arguments [String] :_source_include 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] valid_params = [ :analyze_wildcard, :analyzer, :default_operator, :df, :fields, :lenient, :lowercase_expanded_terms, :parent, :preference, :q, :routing, :source, :_source, :_source_include, :_source_exclude ] 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, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/field_stats.rb000066400000000000000000000031771253341257200314000ustar00rootroot00000000000000module 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={}) valid_params = [ :fields, :level, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = 'GET' path = "_field_stats" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/get.rb000066400000000000000000000065461253341257200276610ustar00rootroot00000000000000module 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 [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment # @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] :fields A comma-separated list of 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 [Number] :version Explicit version number for concurrency control # @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) # @option arguments [String] :_source Specify whether the _source field should be returned, # or a list of fields to return # @option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field # @option arguments [String] :_source_include A list of fields to extract and return from the _source field # @option arguments [Boolean] :_source_transform Retransform the source before returning it # # @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 valid_params = [ :fields, :parent, :preference, :realtime, :refresh, :routing, :version, :version_type, :_source, :_source_include, :_source_exclude, :_source_transform] 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, valid_params 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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/get_script.rb000066400000000000000000000014561253341257200312400ustar00rootroot00000000000000module Elasticsearch module API module Actions # Retrieve an indexed script from Elasticsearch # # @option arguments [String] :id Script ID (*Required*) # @option arguments [String] :lang Script language (*Required*) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html#_indexed_scripts # def get_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'lang' missing" unless arguments[:lang] method = HTTP_GET path = "_scripts/#{arguments[:lang]}/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/get_source.rb000066400000000000000000000057311253341257200312340ustar00rootroot00000000000000module 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 [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment # @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] :fields A comma-separated list of 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 [String] :_source Specify whether the _source field should be returned, # or a list of fields to return # @option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field # @option arguments [String] :_source_include A list of fields to extract and return from the _source field # # @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 valid_params = [ :fields, :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_include, :_source_exclude ] 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, valid_params 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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/get_template.rb000066400000000000000000000015371253341257200315470ustar00rootroot00000000000000module 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 = "_search/template/#{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-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/index.rb000066400000000000000000000115461253341257200302050ustar00rootroot00000000000000module 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 settint 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 (optional, will be auto-generated if missing) # @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 # @option arguments [String] :consistency Explicit write consistency setting for the operation # (options: one, quorum, all) # @option arguments [String] :op_type Explicit operation type (options: index, create) # @option arguments [String] :parent ID of the parent document # @option arguments [String] :percolate Percolator queries to execute while indexing the document # @option arguments [Boolean] :refresh Refresh the index after performing the operation # @option arguments [String] :replication Specific replication type (options: sync, async) # @option arguments [String] :routing Specific routing value # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :timestamp Explicit timestamp for the document # @option arguments [Duration] :ttl Expiration time for the document # @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/index_/ # def index(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :consistency, :op_type, :parent, :percolate, :refresh, :replication, :routing, :timeout, :timestamp, :ttl, :version, :version_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, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/000077500000000000000000000000001253341257200301605ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/analyze.rb000066400000000000000000000072121253341257200321520ustar00rootroot00000000000000module 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: 'The Quick Brown Jumping Fox', # tokenizer: 'whitespace', # filters: ['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 text: 'The Quick Brown Jumping Fox', # tokenizer: 'standard', # token_filters: 'lowercase,stop', # char_filters: 'html_strip' # # @option arguments [String] :index The name of the index to scope the operation # @option arguments [String] :body The text on which the analysis should be performed # @option arguments [String] :analyzer The name of the analyzer to use # @option arguments [String] :field Use the analyzer configured for this field # (instead of passing the analyzer name) # @option arguments [List] :filters A comma-separated list of token filters to use for the analysis. # (Also available as the `:token_filters` option) # @option arguments [List] :char_filters A comma-separated list of char filters to use for the analysis # @option arguments [String] :index The name of the index to scope the operation # @option arguments [Boolean] :prefer_local With `true`, specify that a local shard should be used if available, # with `false`, use a random shard (default: true) # @option arguments [String] :text The text on which the analysis should be performed # (when request body is not used) # @option arguments [String] :tokenizer The name of the tokenizer to use for the analysis # @option arguments [String] :format Format of the output (options: detailed, text) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-analyze/ # def analyze(arguments={}) valid_params = [ :analyzer, :char_filters, :field, :filters, :index, :prefer_local, :text, :tokenizer, :token_filters, :format ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_analyze' params = Utils.__validate_and_extract_params arguments, valid_params params[:filters] = Utils.__listify(params[:filters]) if params[:filters] body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/clear_cache.rb000066400000000000000000000073341253341257200327250ustar00rootroot00000000000000module 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] :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] :field_data Clear field data # @option arguments [Boolean] :fielddata Clear field data # @option arguments [List] :fields A comma-separated list of fields to clear when using the # `field_data` parameter(default: all) # @option arguments [Boolean] :filter Clear filter caches # @option arguments [Boolean] :filter_cache Clear filter caches # @option arguments [Boolean] :filter_keys A comma-separated list of keys to clear when using the # `filter_cache` parameter (default: all) # @option arguments [Boolean] :id Clear ID caches for parent/child # @option arguments [Boolean] :id_cache Clear ID caches for parent/child # @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 [List] :index A comma-separated list of index name to limit the operation # @option arguments [Boolean] :recycler Clear the recycler cache # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-clearcache/ # def clear_cache(arguments={}) valid_params = [ :field_data, :fielddata, :fields, :filter, :filter_cache, :filter_keys, :id, :id_cache, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :recycler ] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_cache/clear' params = Utils.__validate_and_extract_params arguments, valid_params body = nil params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/close.rb000066400000000000000000000042671253341257200316230ustar00rootroot00000000000000module 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 [String] :index The name of the index (*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) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close/ # def close(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :timeout ] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_close' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/create.rb000066400000000000000000000075471253341257200317650ustar00rootroot00000000000000module 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 Optional configuration for the index (`settings` and `mappings`) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index/ # def create(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :timeout ] method = HTTP_PUT path = Utils.__pathify Utils.__escape(arguments[:index]) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete.rb000066400000000000000000000031001253341257200317410ustar00rootroot00000000000000module 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` to delete all indices # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-delete-index/ # def delete(arguments={}) valid_params = [ :timeout ] method = HTTP_DELETE path = Utils.__pathify Utils.__listify(arguments[:index]) params = Utils.__validate_and_extract_params arguments, valid_params 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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_alias.rb000066400000000000000000000024771253341257200331320ustar00rootroot00000000000000module 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 [String] :index The name of the index with an alias (*Required*) # @option arguments [String] :name The name of the alias to be deleted (*Required*) # @option arguments [Time] :timeout Explicit timestamp for the document # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases/ # def delete_alias(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] valid_params = [ :timeout ] method = HTTP_DELETE path = Utils.__pathify Utils.__escape(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_mapping.rb000066400000000000000000000017411253341257200334650ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_template.rb000066400000000000000000000024241253341257200336440ustar00rootroot00000000000000module 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 # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-templates/ # def delete_template(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] valid_params = [ :timeout ] method = HTTP_DELETE path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params 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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/delete_warmer.rb000066400000000000000000000026021253341257200333240ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists.rb000066400000000000000000000045631253341257200320340ustar00rootroot00000000000000module 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 indices to check (*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) # @option arguments [Boolean] :local Return local information, do not retrieve the state from master node # (default: false) # # @return [true,false] # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-indices-exists/ # def exists(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ] method = HTTP_HEAD path = Utils.__listify(arguments[:index]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end alias_method :exists?, :exists end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists_alias.rb000066400000000000000000000046061253341257200332030ustar00rootroot00000000000000module 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 # @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] :local Return local information, do not retrieve the state from master node # (default: false) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases/ # def exists_alias(arguments={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ] method = HTTP_HEAD path = Utils.__pathify Utils.__listify(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params 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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists_template.rb000066400000000000000000000024541253341257200337240ustar00rootroot00000000000000module 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 [String] :name The name of the template (*Required*) # @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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-templates.html # def exists_template(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] valid_params = [ :local, :master_timeout ] method = HTTP_HEAD path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params 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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/exists_type.rb000066400000000000000000000051111253341257200330630ustar00rootroot00000000000000module Elasticsearch module API module Indices module Actions # Return true if the specified type exists, false otherwise. # # client.indices.exists_type? 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] :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] :local Return local information, do not retrieve the state from master node # (default: false) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-types-exists/ # def exists_type(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ] method = HTTP_HEAD path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__escape(arguments[:type]) params = Utils.__validate_and_extract_params arguments, valid_params 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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/flush.rb000066400000000000000000000052251253341257200316320ustar00rootroot00000000000000module 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. (Internal) # @option arguments [Boolean] :full If set to true a new index writer is created and settings that have been # changed related to the index writer will be refreshed. (Internal) # @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] :refresh Refresh the index after performing the operation # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-flush/ # def flush(arguments={}) valid_params = [ :force, :full, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :refresh ] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_flush' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get.rb000066400000000000000000000032711253341257200312670ustar00rootroot00000000000000module 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 [List] :feature A comma-separated list of features # @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 [List] :expand_wildcards Whether wildcard expressions should get expanded # to open or closed indices (default: open) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-get-index.html # def get(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :local, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments.delete(:feature)) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_alias.rb000066400000000000000000000046031253341257200324400ustar00rootroot00000000000000module 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] :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] :local Return local information, do not retrieve the state from master node # (default: false) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases/ # def get_alias(arguments={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_aliases.rb000066400000000000000000000023571253341257200327740ustar00rootroot00000000000000module 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={}) valid_params = [ :timeout, :local ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_aliases', Utils.__listify(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end get_field_mapping.rb000066400000000000000000000056031253341257200340670ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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] :field A comma-separated list of fields (*Required*) # @option arguments [Boolean] :include_defaults Whether default mapping values should be returned as well # @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/en/elasticsearch/reference/current/indices-get-field-mapping.html # def get_field_mapping(arguments={}) raise ArgumentError, "Required argument 'field' missing" unless arguments[:field] valid_params = [ :include_defaults, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), '_mapping', Utils.__listify(arguments[:type]), 'field', Utils.__listify(arguments[:field]) ) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_mapping.rb000066400000000000000000000051671253341257200330100ustar00rootroot00000000000000module 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; use `_all` or empty string for all indices # @option arguments [List] :type A comma-separated list of document 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) # @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-get-mapping.html # def get_mapping(arguments={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :local ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_mapping', Utils.__listify(arguments[:type]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_settings.rb000066400000000000000000000062531253341257200332120ustar00rootroot00000000000000module 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 in the response # @option arguments [String] :prefix The prefix all settings must have in order to be included # @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] :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) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-get-settings/ # def get_settings(arguments={}) valid_params = [ :prefix, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :flat_settings, :local ] 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, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_template.rb000066400000000000000000000026751253341257200331710ustar00rootroot00000000000000module 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 [String] :name The name of the template (supports wildcards) # @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 [Time] :master_timeout Explicit operation timeout for connection to master node # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-templates/ # def get_template(arguments={}) valid_params = [ :flat_settings, :local, :master_timeout ] method = HTTP_GET path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/get_warmer.rb000066400000000000000000000052701253341257200326450ustar00rootroot00000000000000module 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={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), '_warmer', Utils.__escape(arguments[:name]) ) params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/open.rb000066400000000000000000000041151253341257200314470ustar00rootroot00000000000000module 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 [String] :index The name of the index (*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) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close/ # def open(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :timeout ] method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), '_open' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/optimize.rb000066400000000000000000000076711253341257200323600ustar00rootroot00000000000000module 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. # # @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={}) valid_params = [ :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 ] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_optimize' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_alias.rb000066400000000000000000000031271253341257200324710ustar00rootroot00000000000000module 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 [String] :index The name of the index with an alias # @option arguments [String] :name The name of the alias to be created or updated # @option arguments [Hash] :body The settings for the alias, such as `routing` or `filter` # @option arguments [Time] :timeout Explicit timestamp for the document # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases/ # def put_alias(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] valid_params = [ :timeout ] method = HTTP_PUT path = Utils.__pathify Utils.__listify(arguments[:index]), '_alias', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_mapping.rb000066400000000000000000000065211253341257200330340ustar00rootroot00000000000000module 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 [Hash] :body The mapping definition (*Required*) # @option arguments [List] :index A comma-separated list of index names; use `_all` or omit to # update the mapping for all indices # @option arguments [String] :type The name of the document type (*Required*) # @option arguments [Boolean] :ignore_conflicts Specify whether to ignore conflicts while updating the mapping # (default: false) # @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 [Time] :master_timeout Specify timeout for connection to master # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping/ # def put_mapping(arguments={}) raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :ignore_conflicts, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :master_timeout, :timeout ] method = HTTP_PUT path = Utils.__pathify Utils.__listify(arguments[:index]), '_mapping', Utils.__escape(arguments[:type]) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_settings.rb000066400000000000000000000061331253341257200332400ustar00rootroot00000000000000module 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 [Hash] :body The index settings to be updated (*Required*) # @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 [Time] :master_timeout Specify timeout for connection to master # @option arguments [Boolean] :flat_settings Return settings in flat format (default: false) # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings/ # def put_settings(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :master_timeout, :flat_settings ] method = HTTP_PUT path = Utils.__pathify Utils.__listify(arguments[:index]), '_settings' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_template.rb000066400000000000000000000036311253341257200332130ustar00rootroot00000000000000module 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 [Boolean] :create Whether the index template should only be added for a new one, # or can also replace an existing one (default: false) # @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 [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.elasticsearch.org/guide/reference/api/admin-indices-templates/ # def put_template(arguments={}) raise ArgumentError, "Required argument 'name' missing" unless arguments[:name] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :create, :order, :timeout ] method = HTTP_PUT path = Utils.__pathify '_template', Utils.__escape(arguments[:name]) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/put_warmer.rb000066400000000000000000000067531253341257200327050ustar00rootroot00000000000000module 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] valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] 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, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/recovery.rb000066400000000000000000000031331253341257200323430ustar00rootroot00000000000000module 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 # @option arguments [Boolean] :human Whether to return time and byte values in human readable format # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-recovery.html # def recovery(arguments={}) valid_params = [ :detailed, :active_only, :human ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_recovery' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/refresh.rb000066400000000000000000000051341253341257200321460ustar00rootroot00000000000000module 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] :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-refresh/ # def refresh(arguments={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_refresh' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/seal.rb000066400000000000000000000013531253341257200314330ustar00rootroot00000000000000module 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={}) valid_params = [ ] 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/segments.rb000066400000000000000000000040541253341257200323350ustar00rootroot00000000000000module 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] :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://elasticsearch.org/guide/reference/api/admin-indices-segments/ # def segments(arguments={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_segments' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/snapshot_index.rb000066400000000000000000000040701253341257200335340ustar00rootroot00000000000000module 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={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_POST path = Utils.__pathify Utils.__listify(arguments[:index]), '_gateway/snapshot' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/stats.rb000066400000000000000000000140661253341257200316520ustar00rootroot00000000000000module 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) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-stats.html # def stats(arguments={}) valid_parts = [ :docs, :fielddata, :filter_cache, :flush, :get, :indexing, :merge, :metric, :refresh, :search, :suggest, :store, :warmer ] valid_params = [ :fields, :completion_fields, :fielddata_fields, :groups, :level, :types, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET parts = Utils.__extract_parts arguments, valid_parts path = Utils.__pathify Utils.__listify(arguments[:index]), '_stats', Utils.__listify(parts) params = Utils.__validate_and_extract_params arguments, valid_params params[:fields] = Utils.__listify(params[:fields]) if params[:fields] params[:groups] = Utils.__listify(params[:groups]) if params[:groups] body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/status.rb000066400000000000000000000050021253341257200320250ustar00rootroot00000000000000module 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={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :recovery, :snapshot ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), '_status' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/update_aliases.rb000066400000000000000000000031601253341257200334700ustar00rootroot00000000000000module 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 operations definition and other configuration (*Required*) # @option arguments [Time] :timeout Explicit operation timeout # # @see http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases/ # def update_aliases(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :timeout ] method = HTTP_POST path = "_aliases" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/upgrade.rb000066400000000000000000000033371253341257200321420ustar00rootroot00000000000000module 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] :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) # @option arguments [Boolean] :wait_for_completion Specify whether the request should block until the all # segments are upgraded (default: true) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-upgrade.html # def upgrade(arguments={}) valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :wait_for_completion ] method = HTTP_POST path = "_upgrade" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/indices/validate_query.rb000066400000000000000000000114041253341257200335230ustar00rootroot00000000000000module 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) # # client.indices.validate_query index: 'myindex', # 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. # @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] :operation_threading TODO: ? # @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.elasticsearch.org/guide/reference/api/validate/ # def validate_query(arguments={}) valid_params = [ :explain, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :operation_threading, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :lowercase_expanded_terms ] method = HTTP_GET path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_validate/query' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/info.rb000066400000000000000000000006021253341257200300200ustar00rootroot00000000000000module 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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/list_benchmarks.rb000066400000000000000000000014501253341257200322370ustar00rootroot00000000000000module 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={}) valid_params = [ ] method = HTTP_GET path = "_bench" params = {} body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/mget.rb000066400000000000000000000065031253341257200300270ustar00rootroot00000000000000module 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] :fields A comma-separated list of 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 [String] :_source Specify whether the _source field should be returned, # or a list of fields to return # @option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field # @option arguments [String] :_source_include 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] valid_params = [ :fields, :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_include, :_source_exclude ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_mget' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/mlt.rb000066400000000000000000000141471253341257200276720ustar00rootroot00000000000000module 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] valid_params = [ :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 ] 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, valid_params [: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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/mpercolate.rb000066400000000000000000000050621253341257200312250ustar00rootroot00000000000000module 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] valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = "_mpercolate" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] case when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : MultiJson.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/msearch.rb000066400000000000000000000056371253341257200305240ustar00rootroot00000000000000module 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: { facets: { 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: 'count' }, # { facets: { 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 [Array] :body An array of request definitions, each definition is a Hash; # pass the search definition as a `:search` argument # @option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch, # dfs_query_then_fetch, dfs_query_and_fetch, count, scan) # # @see http://www.elasticsearch.org/guide/reference/api/multi-search/ # def msearch(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :search_type ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_msearch' ) params = Utils.__validate_and_extract_params arguments, valid_params 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| MultiJson.dump(item) } payload << "" unless payload.empty? payload = payload.join("\n") when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : MultiJson.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/mtermvectors.rb000066400000000000000000000060371253341257200316270ustar00rootroot00000000000000module 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 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] :ids A comma-separated list of documents ids (alternative to `:body`) # @option arguments [Boolean] :term_statistics Whether total term frequency and # document frequency should be returned. # @option arguments [Boolean] :field_statistics Whether 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 Whether term offsets should be returned # @option arguments [Boolean] :positions Whether term positions should be returned # @option arguments [Boolean] :payloads Whether 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] :realtime Specifies if requests are real-time as opposed to near-real-time # (default: true) # @option arguments [String] :routing Specific routing value # @option arguments [String] :parent Parent ID of documents # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html # # @see #mget # @see #termvector # def mtermvectors(arguments={}) valid_params = [ :ids, :term_statistics, :field_statistics, :fields, :offsets, :positions, :payloads, :preference, :realtime, :routing, :parent ] 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, valid_params if ids body = { :ids => ids } else body = arguments[:body] end perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/nodes/000077500000000000000000000000001253341257200276525ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/nodes/hot_threads.rb000066400000000000000000000035531253341257200325110ustar00rootroot00000000000000module 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 [String] :type The type to sample (default: cpu) (options: cpu, wait, block) # # @return [String] # # @see http://www.elasticsearch.org/guide/reference/api/admin-cluster-nodes-hot-threads/ # def hot_threads(arguments={}) valid_params = [ :interval, :snapshots, :threads, :type ] method = HTTP_GET path = Utils.__pathify '_nodes', Utils.__listify(arguments[:node_id]), 'hot_threads' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/nodes/info.rb000066400000000000000000000055551253341257200311440ustar00rootroot00000000000000module 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 [Boolean] :_all Return all available information # @option arguments [Boolean] :http Return information about HTTP # @option arguments [Boolean] :jvm Return information about the JVM # @option arguments [Boolean] :network Return information about network # @option arguments [Boolean] :os Return information about the operating system # @option arguments [Boolean] :plugins Return information about plugins # @option arguments [Boolean] :process Return information about the Elasticsearch process # @option arguments [Boolean] :settings Return information about node settings # @option arguments [Boolean] :thread_pool Return information about the thread pool # @option arguments [Boolean] :transport Return information about transport # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-nodes-info/ # def info(arguments={}) arguments = arguments.clone metric = arguments.delete(:metric) valid_parts = [ :_all, :http, :jvm, :network, :os, :plugins, :process, :settings, :thread_pool, :transport ] valid_params = [] method = HTTP_GET if metric parts = metric else parts = Utils.__extract_parts arguments, valid_parts end path = Utils.__pathify '_nodes', Utils.__listify(arguments[:node_id]), Utils.__listify(parts) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/nodes/shutdown.rb000066400000000000000000000023431253341257200320540ustar00rootroot00000000000000module 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={}) valid_params = [ :delay, :exit ] method = HTTP_POST path = Utils.__pathify '_cluster/nodes', Utils.__listify(arguments[:node_id]), '_shutdown' params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/nodes/stats.rb000066400000000000000000000076111253341257200313420ustar00rootroot00000000000000module 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, network, # os, process, thread_pool, transport) # @option arguments [List] :index_metric Limit the information returned for the `indices` metric # to the specified index metrics. Used only when # `indices` or `all` metric is specified. # (options: _all, completion, docs, fielddata, filter_cache, flush, get, # id_cache, indexing, merge, percolate, refresh, search, segments, store, # warmer) # @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 metrics (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 # metrics (supports wildcards) # @option arguments [Boolean] :groups A comma-separated list of search groups for `search` index metric # @option arguments [Boolean] :human Whether to return time and byte values in human-readable format # @option arguments [String] :level Specify the level for aggregating indices stats # (options: node, indices, shards) # @option arguments [List] :types A comma-separated list of document types for the `indexing` index metric # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cluster-nodes-stats.html # def stats(arguments={}) arguments = arguments.clone valid_params = [ :metric, :index_metric, :node_id, :completion_fields, :fielddata_fields, :fields, :groups, :human, :level, :types ] method = HTTP_GET path = Utils.__pathify '_nodes', Utils.__listify(arguments[:node_id]), 'stats', Utils.__listify(arguments.delete(:metric)), Utils.__listify(arguments.delete(:index_metric)) params = Utils.__validate_and_extract_params arguments, valid_params [:completion_fields, :fielddata_fields, :fields, :groups, :types].each do |key| params[key] = Utils.__listify(params[key]) if params[key] end body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/percolate.rb000066400000000000000000000126601253341257200310520ustar00rootroot00000000000000module 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. # # @example Register queries named "alert-1" and "alert-2" for the "my-index" index # # client.index index: 'my-index', # type: '.percolator', # id: 'alert-1', # body: { query: { query_string: { query: 'foo' } } } # # client.index index: 'my-index', # type: '.percolator', # id: 'alert-2', # body: { query: { query_string: { query: 'bar' } } } # # @example Evaluate a custom document (passed as `:doc`) against the queries # # client.percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo" } } # # => {..., matches: [ {_index: 'my-index', _id: 'alert-1'} ]} # # client.percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo Bar" } } # # => {..., matches: [ {_index: 'my-index', _id: 'alert-2'}, {_index: 'my-index', _id: 'alert-1'} ] } # # @example Evaluate an existing document against the queries # # client.index index: 'my-index', type: 'my-type', id: 123, body: { title: "Foo Bar" } # # client.percolate index: 'my-index', type: 'my-type', id: '123' # # => { ..., matches: [ {_index: 'my-index', _id: 'alert-2'}, { _index: 'my-index', _id: 'alert-1'} ] } # # @example Register a query with custom `priority` property # # client.index index: 'my-index', # type: '.percolator', # id: 'alert-high-1', # body: { query: { query_string: { query: 'foo' } }, # priority: 'high' } # # @example Evaluate a document against "high priority" percolator queries # # client.percolate index: 'my-index', type: 'my-type', body: { # doc: { title: "Foo" }, # filter: { term: { priority: 'high' } } # } # # => {..., matches: [ {_index: 'my-index', _id: 'alert-high-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_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={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :routing, :preference, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_index, :percolate_type, :percolate_format, :version, :version_type ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), arguments[:id], '_percolate' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/ping.rb000066400000000000000000000010371253341257200300250ustar00rootroot00000000000000module Elasticsearch module API module Actions # Returns true if the cluster returns a sucessfull HTTP response, false otherwise. # # @example # # client.ping # # @see http://elasticsearch.org/guide/ # def ping(arguments={}) method = HTTP_HEAD path = "" params = {} body = nil Utils.__rescue_from_not_found do perform_request(method, path, params, body).status == 200 ? true : false end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/put_script.rb000066400000000000000000000040361253341257200312660ustar00rootroot00000000000000module 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] :lang Script language (*Required*) # @option arguments [Hash] :body A JSON document containing the script (*Required*) # @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 [String] :op_type Explicit operation type (options: index, create) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html#_indexed_scripts # def put_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'lang' missing" unless arguments[:lang] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :op_type, :version, :version_type ] method = HTTP_PUT path = "_scripts/#{arguments.delete(:lang)}/#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/put_template.rb000066400000000000000000000015451253341257200315770ustar00rootroot00000000000000module 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_PUT path = "_search/template/#{arguments[:id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/scroll.rb000066400000000000000000000052031253341257200303650ustar00rootroot00000000000000module 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. # # "Scrolling" the results is frequently used with the `scan` search type. # # @example A basic example # # result = client.search index: 'scrollindex', # scroll: '5m', # body: { query: { match: { title: 'test' } }, sort: '_id' } # # result = client.scroll scroll: '5m', 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}"} end # client.indices.refresh index: 'test' # # # Open the "view" of the index with the `scan` search_type # r = client.search index: 'test', search_type: 'scan', scroll: '5m', size: 10 # # # Call the `scroll` API until empty results are returned # while r = client.scroll(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 [Duration] :scroll Specify how long a consistent view of the index # should be maintained for scrolled search # # @see http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/scan-scroll.html#scan-scroll # @see http://www.elasticsearch.org/guide/reference/api/search/scroll/ # @see http://www.elasticsearch.org/guide/reference/api/search/search-type/ # def scroll(arguments={}) method = HTTP_GET path = "_search/scroll" valid_params = [ :scroll, :scroll_id ] params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] || params.delete(:scroll_id) perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/search.rb000066400000000000000000000177461253341257200303530ustar00rootroot00000000000000module 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' } }, # facets: { 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' } }, # facets: { tags: { terms: { field: 'tags' } } } # } # # response = Hashie::Mash.new response # # response.hits.hits.first._source.title # # response.facets.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] :fields A comma-separated list of fields to return as part of a hit # @option arguments [Number] :from Starting offset (default: 0) # @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore `missing` ones # (options: none, missing) # @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 # @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 [Duration] :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, count, scan) # @option arguments [Number] :size Number of hits to return (default: 10) # @option arguments [List] :sort A comma-separated list of : pairs # @option arguments [String] :source The URL-encoded request definition using the Query DSL # (instead of using request body) # @option arguments [String] :_source Specify whether the _source field should be returned, # or a list of fields to return # @option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field # @option arguments [String] :_source_include A list of fields to extract and return from the _source field # @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 [Text] :suggest_text The source text for which the suggestions should be returned # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Boolean] :version Specify whether to return document version as part of a hit # # @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] valid_params = [ :analyzer, :analyze_wildcard, :default_operator, :df, :explain, :fields, :from, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :lenient, :lowercase_expanded_terms, :preference, :q, :query_cache, :routing, :scroll, :search_type, :size, :sort, :source, :_source, :_source_include, :_source_exclude, :stats, :suggest_field, :suggest_mode, :suggest_size, :suggest_text, :timeout, :version ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), UNDERSCORE_SEARCH ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/search_exists.rb000066400000000000000000000062111253341257200317330ustar00rootroot00000000000000module 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={}) valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :min_score, :preference, :routing, :q, :analyzer, :analyze_wildcard, :default_operator, :df, :lenient, :lowercase_expanded_terms ] method = 'POST' path = "_search/exists" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/search_shards.rb000066400000000000000000000040561253341257200317050ustar00rootroot00000000000000module Elasticsearch module API module Actions # Returns the names of indices and shards on which a search request would be executed # # @option arguments [String] :index The name of the index # @option arguments [String] :type The type of the document # @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` 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-shards.html # def search_shards(arguments={}) valid_params = [ :preference, :routing, :local, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_search_shards' ) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/search_template.rb000066400000000000000000000064671253341257200322440ustar00rootroot00000000000000module 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 # @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] :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 [Duration] :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, count, scan) # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html # def search_template(arguments={}) valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :preference, :routing, :scroll, :search_type ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_search/template' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/000077500000000000000000000000001253341257200304015ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/create.rb000066400000000000000000000040601253341257200321710ustar00rootroot00000000000000module 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 Whether the request should block and wait until # the operation has completed # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html#_snapshot # def create(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] valid_params = [ :master_timeout, :wait_for_completion ] 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, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end create_repository.rb000066400000000000000000000033441253341257200344150ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html#_repositories # def create_repository(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :repository, :master_timeout, :timeout ] repository = arguments.delete(:repository) method = HTTP_PUT path = Utils.__pathify( '_snapshot', Utils.__escape(repository) ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/delete.rb000066400000000000000000000027251253341257200321760ustar00rootroot00000000000000module 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.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html # def delete(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] valid_params = [ :master_timeout ] 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, valid_params body = nil perform_request(method, path, params, body).body end end end end end delete_repository.rb000066400000000000000000000024131253341257200344100ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html # def delete_repository(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] valid_params = [ :master_timeout, :timeout ] repository = arguments.delete(:repository) method = HTTP_DELETE path = Utils.__pathify( '_snapshot', Utils.__listify(repository) ) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/get.rb000066400000000000000000000034341253341257200315110ustar00rootroot00000000000000module 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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html # def get(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] valid_params = [ :master_timeout ] 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, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/get_repository.rb000066400000000000000000000027241253341257200340110ustar00rootroot00000000000000module 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. Leave blank or use `_all` # to get a list of repositories # @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.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html # def get_repository(arguments={}) valid_params = [ :master_timeout, :local ] repository = arguments.delete(:repository) method = HTTP_GET path = Utils.__pathify( '_snapshot', Utils.__escape(repository) ) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/restore.rb000066400000000000000000000042721253341257200324160ustar00rootroot00000000000000module 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.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html # def restore(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] raise ArgumentError, "Required argument 'snapshot' missing" unless arguments[:snapshot] valid_params = [ :master_timeout, :wait_for_completion ] 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, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/snapshot/status.rb000066400000000000000000000026101253341257200322500ustar00rootroot00000000000000module 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 # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html#_snapshot_status # def status(arguments={}) valid_params = [ :master_timeout ] 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, valid_params body = nil perform_request(method, path, params, body).body end end end end end verify_repository.rb000066400000000000000000000022071253341257200344530ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html # def verify_repository(arguments={}) raise ArgumentError, "Required argument 'repository' missing" unless arguments[:repository] valid_params = [ :repository, :master_timeout, :timeout ] repository = arguments.delete(:repository) method = HTTP_POST path = Utils.__pathify( '_snapshot', Utils.__escape(repository), '_verify' ) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/suggest.rb000066400000000000000000000036341253341257200305560ustar00rootroot00000000000000module 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={}) valid_params = [ :ignore_indices, :preference, :routing, :source ] method = HTTP_POST path = Utils.__pathify( Utils.__listify(arguments[:index]), '_suggest' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/termvectors.rb000066400000000000000000000105001253341257200314400ustar00rootroot00000000000000module 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 name of the index (*Required*) # @option arguments [String] :type The type of the document (*Required*) # @option arguments [String] :id The document ID # @option arguments [Hash] :body The request definition # @option arguments [Boolean] :term_statistics Whether total term frequency and # document frequency should be returned # @option arguments [Boolean] :field_statistics Whether 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 Whether term offsets should be returned # @option arguments [Boolean] :positions Whether term positions should be returned # @option arguments [Boolean] :payloads Whether 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] :realtime Specifies if requests are real-time as opposed to near-real-time # (default: true) # @option arguments [String] :routing Specific routing value # @option arguments [String] :parent Parent ID of the documents # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/docs-termvectors.html # def termvectors(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :term_statistics, :field_statistics, :fields, :offsets, :positions, :payloads, :preference, :realtime, :routing, :parent ] 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, valid_params 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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/actions/update.rb000066400000000000000000000121641253341257200303550ustar00rootroot00000000000000module 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: 'ctx._source.tags += 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(tag) ? ctx.op = "delete" : ctx.op = "none"', # params: { tag: 'to-delete' } } # # @option arguments [String] :id Document ID (*Required*) # @option arguments [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment # @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 using either `script` or partial `doc` (*Required*) # @option arguments [String] :consistency Explicit write consistency setting for the operation # (options: one, quorum, all) # @option arguments [List] :fields A comma-separated list of fields to return in the response # @option arguments [String] :lang The script language (default: mvel) # @option arguments [String] :parent ID of the parent document # @option arguments [String] :percolate Perform percolation during the operation; # use specific registered query name, attribute, or wildcard # @option arguments [Boolean] :refresh Refresh the index after performing the operation # @option arguments [String] :replication Specific replication type (options: sync, async) # @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 [String] :script The URL-encoded script definition (instead of using request body) # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :timestamp Explicit timestamp for the document # @option arguments [Duration] :ttl Expiration time for the document # @option arguments [Number] :version Explicit version number for concurrency control # @option arguments [Number] :version_type Explicit version number for concurrency control # # @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] valid_params = [ :consistency, :fields, :lang, :parent, :percolate, :refresh, :replication, :retry_on_conflict, :routing, :script, :timeout, :timestamp, :ttl, :version, :version_type ] 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, valid_params 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 end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/000077500000000000000000000000001253341257200270365ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/cat.rb000066400000000000000000000006451253341257200301370ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/cluster.rb000066400000000000000000000007111253341257200310430ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/common.rb000066400000000000000000000010151253341257200306500ustar00rootroot00000000000000module 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) client.perform_request method, path, params, body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/indices.rb000066400000000000000000000007111253341257200310000ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/nodes.rb000066400000000000000000000006671253341257200305040ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/namespace/snapshot.rb000066400000000000000000000007221253341257200312230ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-api/lib/elasticsearch/api/utils.rb000066400000000000000000000162321253341257200265730ustar00rootroot00000000000000module 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' # # @api private def __listify(*list) Array(list).flatten. map { |e| e.respond_to?(:split) ? e.split(',') : e }. flatten. compact. map { |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 =~ /^\s*$/ }. join('/'). squeeze('/') end # Convert an array of payloads into Elasticsearch `header\ndata` format # # 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) case # Hashes with `:data` when payload.any? { |d| d.is_a?(Hash) && d.values.first.is_a?(Hash) && (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| MultiJson.dump(item) } payload << "" unless payload.empty? return payload.join("\n") # Array of strings when payload.all? { |d| d.is_a? String } payload << '' # Header/Data pairs else payload = payload.map { |item| MultiJson.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) 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=[]) 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)] : [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=[]) # require 'pry'; binding.pry; # parts = arguments.keys.select { |a| valid_parts.include?(a) }.map { |a| a.to_s }.sort 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 given block, rescuing from any exceptions. Returns `false` # if exception contains NotFound/404 in its class name or message, else re-raises exception. # # @yield [block] A block of code to be executed with exception handling. # # @api private # def __rescue_from_not_found(&block) yield rescue Exception => e if e.class.to_s =~ /NotFound/ || e.message =~ /Not\s*Found|404/i false else raise e end end extend self end end end elasticsearch-ruby-1.0.12/elasticsearch-api/lib/elasticsearch/api/version.rb000066400000000000000000000001031253341257200271060ustar00rootroot00000000000000module Elasticsearch module API VERSION = "1.0.12" end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/000077500000000000000000000000001253341257200217305ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/integration/000077500000000000000000000000001253341257200242535ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/integration/yaml_test_runner.rb000066400000000000000000000361021253341257200301740ustar00rootroot00000000000000RUBY_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' SKIP_FEATURES = ENV.fetch('TEST_SKIP_FEATURES', skip_features) # Turn configuration ENV['ansi'] = 'false' if ENV['CI'] Turn.config.format = :pretty # Launch test cluster # Elasticsearch::Extensions::Test::Cluster.start(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? # Register `at_exit` handler for server shutdown. # MUST be called before requiring `test/unit`. # at_exit { Elasticsearch::Extensions::Test::Cluster.stop if ENV['SERVER'] } 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.fetch('TEST_CLUSTER_URL', "http://localhost:#{ENV['TEST_CLUSTER_PORT'] || 9250}") $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 $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 "ARGUMENTS: #{arguments.inspect}" if ENV['DEBUG'] $results[test.hash] = 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 end def evaluate(test, property) property.gsub(/\\\./, '_____').split('.').reduce($results[test.hash]) do |memo, attr| if memo attr = attr.gsub(/_____/, '.') if attr 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'] # Skip version 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 # Skip features elsif skip && skip['skip']['features'] if (skip['skip']['features'].split(',') & SKIP_FEATURES.split(',') ).size > 0 return skip['skip']['features'] end end return false end extend self end class YamlTestCase < ::Test::Unit::TestCase; end end end include Elasticsearch::YamlTestSuite PATH = Pathname(ENV['TEST_REST_API_SPEC'] || \ File.expand_path('../../../../tmp/elasticsearch/rest-api-spec/test', __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 $client.indices.delete index: '_all' $client.indices.delete_template name: '*' $results = {} $stash = {} end # --- Register context teardown ---------------------------------------- # teardown do $client.indices.delete index: '_all' end files = Dir[suite.join('*.{yml,yaml}')] files.each do |file| tests = YAML.load_documents File.new(file) # 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 actions.select { |a| a['setup'] }.first['setup'].each do |action| next unless 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 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) end actions.each do |action| $stderr.puts "ACTION: #{action.inspect}" if ENV['DEBUG'] 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 false, is: #{result.inspect}" if ENV['DEBUG'] assert( !!! result, "Property '#{property}' should be false, is: #{result.inspect}") 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'] next property, value = a.to_a.first operator = action['lt'] ? '<' : '>' result = Runner.evaluate(test, property) message = "Expected '#{property}' to be #{operator} #{value}, is: #{result.inspect}" $stderr.puts "CHECK: #{message}" if ENV['DEBUG'] # operator == 'less than' ? assert(value.to_f < result.to_f, message) : assert(value.to_f > result.to_f, message) 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-1.0.12/elasticsearch-api/test/test_helper.rb000066400000000000000000000031331253341257200245730ustar00rootroot00000000000000RUBY_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 module Elasticsearch module Test class FakeClient include Elasticsearch::API 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-1.0.12/elasticsearch-api/test/unit/000077500000000000000000000000001253341257200227075ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/abort_benchmark_test.rb000066400000000000000000000011541253341257200274150ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class AbortBenchmarkTest < ::Test::Unit::TestCase context "Abort benchmark" 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 '_bench/abort/foo', url assert_equal nil, params[:name] assert_nil body true end.returns(FakeResponse.new) subject.abort_benchmark :name => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/api_test.rb000066400000000000000000000007501253341257200250460ustar00rootroot00000000000000# encoding: UTF-8 require 'test_helper' module Elasticsearch module Test class APITest < ::Test::Unit::TestCase context "The API module" do should "access the settings" do assert_not_nil Elasticsearch::API.settings end should "allow to set settings" do assert_nothing_raised { Elasticsearch::API.settings[:foo] = 'bar' } assert_equal 'bar', Elasticsearch::API.settings[:foo] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/benchmark_test.rb000066400000000000000000000011511253341257200262230ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class BenchmarkTest < ::Test::Unit::TestCase context "Benchmark" 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 '_bench', url assert_equal Hash.new, params assert_equal 'foo', body[:name] true end.returns(FakeResponse.new) subject.benchmark :body => { :name => 'foo' } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/bulk_test.rb000066400000000000000000000062071253341257200252350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class BulkTest < ::Test::Unit::TestCase context "Bulk" do subject { FakeClient.new } should "post correct payload to the endpoint" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_bulk', url assert_equal Hash.new, params if RUBY_1_8 lines = body.split("\n") assert_equal 5, lines.size assert_match /\{"index"\:\{/, lines[0] assert_match /\{"title"\:"Test"/, lines[1] assert_match /\{"update"\:\{/, lines[2] assert_match /\{"doc"\:\{"title"/, lines[3] else assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), body {"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 true end.returns(FakeResponse.new) subject.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' } } ] end should "post payload to the correct endpoint" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'myindex/_bulk', url true end.returns(FakeResponse.new) subject.bulk :index => 'myindex', :body => [] end should "post a string payload" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal "foo\nbar", body true end.returns(FakeResponse.new) subject.bulk :body => "foo\nbar" end should "post an array of strings payload" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal "foo\nbar\n", body true end.returns(FakeResponse.new) subject.bulk :body => ["foo", "bar"] end should "encode URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_bulk', url assert_equal({:refresh => true}, params) true end.returns(FakeResponse.new) subject.bulk :refresh => true, :body => [] end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_bulk', url true end.returns(FakeResponse.new) subject.bulk :index => 'foo^bar', :body => [] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/000077500000000000000000000000001253341257200234565ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/aliases_test.rb000066400000000000000000000011131253341257200264570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatAliasesTest < ::Test::Unit::TestCase context "Cat: Aliases" 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 '_cat/aliases', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.aliases end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/allocation_test.rb000066400000000000000000000011271253341257200271700ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatAllocationTest < ::Test::Unit::TestCase context "Cat: Allocation" 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 '_cat/allocation', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.allocation end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/count_test.rb000066400000000000000000000011031253341257200261650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatCountTest < ::Test::Unit::TestCase context "Cat: Count" 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 '_cat/count', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.count end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/fielddata_test.rb000066400000000000000000000017711253341257200267650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatFielddataTest < ::Test::Unit::TestCase context "Cat: Fielddata" 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 '_cat/fielddata', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.fielddata end should "pass the fields in the URL" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_cat/fielddata/foo,bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.fielddata :fields => ['foo', 'bar'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/health_test.rb000066400000000000000000000011071253341257200263060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatHealthTest < ::Test::Unit::TestCase context "Cat: Health" 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 '_cat/health', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.health end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/help_test.rb000066400000000000000000000010721253341257200257720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatHelpTest < ::Test::Unit::TestCase context "Cat: Help" 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 '_cat', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.help end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/indices_test.rb000066400000000000000000000011131253341257200264540ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatIndicesTest < ::Test::Unit::TestCase context "Cat: Indices" 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 '_cat/indices', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.indices end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/master_test.rb000066400000000000000000000011071253341257200263340ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatMasterTest < ::Test::Unit::TestCase context "Cat: Master" 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 '_cat/master', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.master end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/nodes_test.rb000066400000000000000000000011031253341257200261450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatNodesTest < ::Test::Unit::TestCase context "Cat: Nodes" 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 '_cat/nodes', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.nodes end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/pending_tasks_test.rb000066400000000000000000000011421253341257200276710ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatPendingTasksTest < ::Test::Unit::TestCase context "Cat: Pending tasks" 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 '_cat/pending_tasks', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.pending_tasks end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/plugins_test.rb000066400000000000000000000011141253341257200265200ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatPluginsTest < ::Test::Unit::TestCase context "Cat: Plugins" 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 '/_cat/plugins', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.plugins end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/recovery_test.rb000066400000000000000000000011171253341257200267000ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatRecoveryTest < ::Test::Unit::TestCase context "Cat: Recovery" 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 '_cat/recovery', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.recovery end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/segments_test.rb000066400000000000000000000011171253341257200266670ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatSegmentsTest < ::Test::Unit::TestCase context "Cat: Segments" 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 '_cat/segments', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.segments end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/shards_test.rb000066400000000000000000000011071253341257200263250ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatShardsTest < ::Test::Unit::TestCase context "Cat: Shards" 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 '_cat/shards', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.shards end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cat/thread_pool_test.rb000066400000000000000000000011321253341257200273370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CatThreadPoolTest < ::Test::Unit::TestCase context "Cat: Thread pool" 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 '_cat/thread_pool', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.thread_pool end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/clear_scroll_test.rb000066400000000000000000000020451253341257200267400ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClearScrollTest < ::Test::Unit::TestCase context "Clear scroll" 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 '_search/scroll', url assert_equal Hash.new, params assert_equal 'abc123', body true end.returns(FakeResponse.new) subject.clear_scroll :scroll_id => 'abc123' end should "listify scroll IDs" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_search/scroll', url assert_equal Hash.new, params assert_equal 'abc123,def456', body true end.returns(FakeResponse.new) subject.clear_scroll :scroll_id => ['abc123', 'def456'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/client_test.rb000066400000000000000000000011131253341257200255450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClientTest < ::Test::Unit::TestCase context "API Client" do class MyDummyClient include Elasticsearch::API end subject { MyDummyClient.new } should "have the cluster namespace" do assert_respond_to subject, :cluster end should "have the indices namespace" do assert_respond_to subject, :indices end should "have API methods" do assert_respond_to subject, :bulk end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/000077500000000000000000000000001253341257200243705ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/get_settings_test.rb000066400000000000000000000011521253341257200304520ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClusterGetSettingsTest < ::Test::Unit::TestCase context "Cluster: Get settings" 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 '_cluster/settings', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cluster.get_settings end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/health_test.rb000066400000000000000000000017541253341257200272300ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class Cluster_Test < ::Test::Unit::TestCase context "Health" 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 '_cluster/health', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cluster.health end should "encode URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_cluster/health', url assert_equal({:level => 'indices'}, params) assert_nil body true end.returns(FakeResponse.new) subject.cluster.health :level => 'indices' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/pending_tasks_test.rb000066400000000000000000000011631253341257200306060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClusterPendingTasksTest < ::Test::Unit::TestCase context "Cluster: Pending tasks" 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 '/_cluster/pending_tasks', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cluster.pending_tasks end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/put_settings_test.rb000066400000000000000000000011641253341257200305060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClusterPutSettingsTest < ::Test::Unit::TestCase context "Cluster: Put settings" 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 '_cluster/settings', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.cluster.put_settings end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/reroute_test.rb000066400000000000000000000021611253341257200274410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClusterRerouteTest < ::Test::Unit::TestCase context "Cluster: Reroute" 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 '_cluster/reroute', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.cluster.reroute end should "send the body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_cluster/reroute', url assert_equal Hash.new, params assert_equal({:commands => [ :move => { :index => 'myindex', :shard => 0 } ]}, body) true end.returns(FakeResponse.new) subject.cluster.reroute :body => { :commands => [ :move => { :index => 'myindex', :shard => 0 } ] } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/cluster/state_test.rb000066400000000000000000000024421253341257200270760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ClusterStateTest < ::Test::Unit::TestCase context "Cluster: State" 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 '_cluster/state', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cluster.state end should "build the correct path" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_cluster/state/foo,bar', url assert_equal({}, params) true end.returns(FakeResponse.new) subject.cluster.state :metric => ['foo', 'bar'] end should "send the API parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_cluster/state', url assert_equal({:index_templates => 'foo,bar'}, params) true end.returns(FakeResponse.new) subject.cluster.state :index_templates => ['foo', 'bar'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/count_percolate_test.rb000066400000000000000000000012751253341257200274660ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CountPercolateTest < ::Test::Unit::TestCase context "Count percolate" 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/bar/_percolate/count', url assert_equal Hash.new, params assert_equal 'bar', body[:doc][:foo] true end.returns(FakeResponse.new) subject.count_percolate :index => 'foo', :type => 'bar', :body => { :doc => { :foo => 'bar' } } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/count_test.rb000066400000000000000000000023661253341257200254320ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class CountTest < ::Test::Unit::TestCase context "Count" 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 '_count', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.count end should "encode indices and types" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo,bar/t1,t2/_count', url true end.returns(FakeResponse.new) subject.count :index => ['foo','bar'], :type => ['t1','t2'] end should "take the query" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal( {:match => {:foo => 'bar'}}, body) true end.returns(FakeResponse.new) subject.count :body => { :match => { :foo => 'bar' } } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/create_document_test.rb000066400000000000000000000030411253341257200274320ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndexDocumentTest < ::Test::Unit::TestCase context "Creating a document with the #create method" do subject { FakeClient.new } should "perform the create request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'foo/bar', url assert_equal({:op_type => 'create'}, params) assert_equal({:foo => 'bar'}, body) true end.returns(FakeResponse.new) subject.create :index => 'foo', :type => 'bar', :body => {:foo => 'bar'} end should "perform the create request with a specific ID" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo/bar/123', url assert_equal 'create', params[:op_type] assert_nil params[:id] assert_equal({:foo => 'bar'}, body) true end.returns(FakeResponse.new) subject.create :index => 'foo', :type => 'bar', :id => '123', :body => {:foo => 'bar'} end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar%2Fbam/123', url true end.returns(FakeResponse.new) subject.create :index => 'foo', :type => 'bar/bam', :id => '123', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/delete_by_query_test.rb000066400000000000000000000030111253341257200274470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class DeleteByQueryTest < ::Test::Unit::TestCase context "Delete by query" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.delete_by_query :body => {} end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal 'foo/_query', url assert_equal Hash.new, params assert_equal Hash.new, body[:term] true end.returns(FakeResponse.new) subject.delete_by_query :index => 'foo', :body => { :term => {} } end should "optionally take the :type argument" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/tweet,post/_query', url true end.returns(FakeResponse.new) subject.delete_by_query :index => 'foo', :type => ['tweet', 'post'], :body => { :term => {} } end should "pass the query in URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_query', url assert_equal 'foo:bar', params[:q] true end.returns(FakeResponse.new) subject.delete_by_query :index => 'foo', :q => 'foo:bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/delete_document_test.rb000066400000000000000000000050201253341257200274300ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class DeleteTest < ::Test::Unit::TestCase context "Delete document" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.delete :type => 'bar', :id => '1' end end should "require the :type argument" do assert_raise ArgumentError do subject.delete :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.delete :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal 'foo/bar/1', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.delete :index => 'foo', :type => 'bar', :id => '1' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1', url assert_equal 'abc123', params[:routing] true end.returns(FakeResponse.new) subject.delete :index => 'foo', :type => 'bar', :id => '1', :routing => 'abc123' end should "validate URL parameters" do assert_raise ArgumentError do subject.delete :index => 'foo', :type => 'bar', :id => '1', :qwertypoiuy => 'asdflkjhg' end end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/1', url true end.returns(FakeResponse.new) subject.delete :index => 'foo^bar', :type => 'bar/bam', :id => 1 end should "raise a NotFound exception" do subject.expects(:perform_request).raises(NotFound) assert_raise NotFound do subject.delete :index => 'foo', :type => 'bar', :id => 'XXX' end end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.delete :index => 'foo', :type => 'bar', :id => 'XXX', :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/delete_script_test.rb000066400000000000000000000011721253341257200271220ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class DeleteScriptTest < ::Test::Unit::TestCase context "Delete script" 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 '_scripts/groovy/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.delete_script :lang => "groovy", :id => "foo" end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/delete_template_test.rb000066400000000000000000000011561253341257200274330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class DeleteTemplateTest < ::Test::Unit::TestCase context "Delete template" 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 '_search/template/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.delete_template :id => "foo" end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/exists_document_test.rb000066400000000000000000000057771253341257200275300ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ExistsTest < ::Test::Unit::TestCase context "Exists document" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.exists :type => 'bar', :id => '1' end end should "NOT require the :type argument" do assert_nothing_raised do subject.exists :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.exists :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'HEAD', method assert_equal 'foo/bar/1', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.exists :index => 'foo', :type => 'bar', :id => '1' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1', url assert_equal 'abc123', params[:routing] true end.returns(FakeResponse.new) subject.exists :index => 'foo', :type => 'bar', :id => '1', :routing => 'abc123' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar%2Fbam/1', url true end.returns(FakeResponse.new) subject.exists :index => 'foo', :type => 'bar/bam', :id => '1' end should "return true for successful response" do subject.expects(:perform_request).returns(FakeResponse.new 200, 'OK') assert_equal true, subject.exists(:index => 'foo', :type => 'bar', :id => '1') end should "return false for 404 response" do subject.expects(:perform_request).returns(FakeResponse.new 404, 'Not Found') assert_equal false, subject.exists(:index => 'foo', :type => 'bar', :id => '1') end should "return false on 'not found' exceptions" do subject.expects(:perform_request).raises(StandardError.new '404 NotFound') assert_equal false, subject.exists(:index => 'foo', :type => 'bar', :id => '1') end should "re-raise generic exceptions" do subject.expects(:perform_request).raises(StandardError) assert_raise(StandardError) do assert_equal false, subject.exists(:index => 'foo', :type => 'bar', :id => '1') end end should "be aliased as predicate method" do assert_nothing_raised do subject.exists?(:index => 'foo', :type => 'bar', :id => '1') == subject.exists(:index => 'foo', :type => 'bar', :id => '1') end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/explain_document_test.rb000066400000000000000000000044171253341257200276370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ExplainTest < ::Test::Unit::TestCase context "Explain document" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.explain :type => 'bar', :id => '1' end end should "require the :type argument" do assert_raise ArgumentError do subject.explain :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.explain :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo/bar/1/_explain', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.explain :index => 'foo', :type => 'bar', :id => 1, :body => {} end should "pass the query in URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1/_explain', url assert_equal 'foo', params[:q] true end.returns(FakeResponse.new) subject.explain :index => 'foo', :type => 'bar', :id => 1, :q => 'foo' end should "pass the request definition in the body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1/_explain', url assert_equal Hash.new, body[:query][:match] true end.returns(FakeResponse.new) subject.explain :index => 'foo', :type => 'bar', :id => 1, :body => { :query => { :match => {} } } end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/1/_explain', url true end.returns(FakeResponse.new) subject.explain :index => 'foo^bar', :type => 'bar/bam', :id => '1', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/field_stats_test.rb000066400000000000000000000011121253341257200265670ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class FieldStatsTest < ::Test::Unit::TestCase context "Field 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 '_field_stats', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.field_stats end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/get_document_source_test.rb000066400000000000000000000041731253341257200303350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class GetSourceTest < ::Test::Unit::TestCase context "Get document source" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.get_source :type => 'bar', :id => '1' end end should "NOT require the :type argument" do assert_nothing_raised do subject.get_source :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.get_source :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo/bar/1/_source', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.get_source :index => 'foo', :type => 'bar', :id => '1' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1/_source', url assert_equal 'abc123', params[:routing] true end.returns(FakeResponse.new) subject.get_source :index => 'foo', :type => 'bar', :id => '1', :routing => 'abc123' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/1/_source', url true end.returns(FakeResponse.new) subject.get_source :index => 'foo^bar', :type => 'bar/bam', :id => '1' end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.get :index => 'foo', :type => 'bar', :id => 'XXX', :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/get_document_test.rb000066400000000000000000000047601253341257200267570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class GetTest < ::Test::Unit::TestCase context "Get document" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.get :type => 'bar', :id => '1' end end should "NOT require the :type argument" do assert_nothing_raised do subject.get :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.get :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo/bar/1', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.get :index => 'foo', :type => 'bar', :id => '1' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1', url assert_equal 'abc123', params[:routing] true end.returns(FakeResponse.new) subject.get :index => 'foo', :type => 'bar', :id => '1', :routing => 'abc123' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/1', url true end.returns(FakeResponse.new) subject.exists :index => 'foo^bar', :type => 'bar/bam', :id => '1' end should "validate URL parameters" do assert_raise ArgumentError do subject.get :index => 'foo', :type => 'bar', :id => '1', :qwertypoiuy => 'asdflkjhg' end end should "raise a NotFound exception" do subject.expects(:perform_request).raises(NotFound) assert_raise NotFound do subject.get :index => 'foo', :type => 'bar', :id => 'XXX' end end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.get :index => 'foo', :type => 'bar', :id => 'XXX', :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/get_script_test.rb000066400000000000000000000011561253341257200264410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class GetScriptTest < ::Test::Unit::TestCase context "Get script" 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 '_scripts/groovy/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.get_script :lang => "groovy", :id => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/get_template_test.rb000066400000000000000000000020751253341257200267510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class GetTemplateTest < ::Test::Unit::TestCase context "Get template" 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 '_search/template/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.get_template :id => "foo" end should "raise a NotFound exception" do subject.expects(:perform_request).raises(NotFound) assert_raise NotFound do subject.get_template :id => "foo" end end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.get_template :id => "foo", :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/hashie_test.rb000066400000000000000000000037521253341257200255430ustar00rootroot00000000000000require 'test_helper' require 'hashie' module Elasticsearch module Test class HashieTest < ::Test::Unit::TestCase context "Hashie" do subject { FakeClient.new } should "wrap the response" do json =<<-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 response = Hashie::Mash.new MultiJson.load(json) assert_equal 'Test 1', response.hits.hits.first._source.title assert_equal 'z', response.facets.tags.terms.first.term end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/index_document_test.rb000066400000000000000000000060331253341257200273020ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndexDocumentTest < ::Test::Unit::TestCase context "Indexing a document" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.index :type => 'foo' end end should "require the :type argument" do assert_raise ArgumentError do subject.index :index => 'foo' end end should "perform the index request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'foo/bar', url assert_equal({:foo => 'bar'}, body) true end.returns(FakeResponse.new) subject.index :index => 'foo', :type => 'bar', :body => {:foo => 'bar'} end should "perform the index request with a specific ID" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo/bar/123', url assert_nil params[:id] assert_equal({:foo => 'bar'}, body) true end.returns(FakeResponse.new) subject.index :index => 'foo', :type => 'bar', :id => '123', :body => {:foo => 'bar'} end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar%2Fbam/123', url true end.returns(FakeResponse.new) subject.index :index => 'foo', :type => 'bar/bam', :id => '123', :body => {} end should "validate URL parameters" do assert_raise ArgumentError do subject.index :index => 'foo', :type => 'bar/bam', :id => '123', :body => {}, :qwertypoiuy => 'asdflkjhg' end end end context "Creating a document" do subject { FakeClient.new } should "perform the create request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'foo/bar', url assert_equal({:op_type => 'create'}, params) assert_equal({:foo => 'bar'}, body) true end.returns(FakeResponse.new) subject.index :index => 'foo', :type => 'bar', :op_type => 'create', :body => {:foo => 'bar'} end should "perform the create request with a specific ID" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo/bar/123', url assert_equal 'create', params[:op_type] assert_nil params[:id] assert_equal({:foo => 'bar'}, body) true end.returns(FakeResponse.new) subject.index :index => 'foo', :type => 'bar', :id => '123', :op_type => 'create', :body => {:foo => 'bar'} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/000077500000000000000000000000001253341257200243255ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/analyze_test.rb000066400000000000000000000045061253341257200273610ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesAnalyzeTest < ::Test::Unit::TestCase context "Indices: Analyze" 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 '_analyze', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.analyze end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_analyze', url true end.returns(FakeResponse.new) subject.indices.analyze :index => 'foo' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_analyze', url assert_equal 'foo', params[:text] assert_equal 'bar', params[:analyzer] true end.returns(FakeResponse.new) subject.indices.analyze :text => 'foo', :analyzer => 'bar' end should "pass the text in body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_analyze', url assert_equal Hash.new, params assert_equal 'foo', body true end.returns(FakeResponse.new) subject.indices.analyze :body => 'foo' end should "pass the filters parameter as a list" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_analyze', url assert_equal 'foo,bar', params[:filters] true end.returns(FakeResponse.new) subject.indices.analyze :text => 'Test', :tokenizer => 'whitespace', :filters => ['foo,bar'] end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_analyze', url true end.returns(FakeResponse.new) subject.indices.analyze :index => 'foo^bar', :text => 'Test' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/clear_cache_test.rb000066400000000000000000000030441253341257200301230ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesClearCacheTest < ::Test::Unit::TestCase context "Indices: Clear cache" 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 '_cache/clear', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.clear_cache end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_cache/clear', url true end.returns(FakeResponse.new) subject.indices.clear_cache :index => 'foo' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_cache/clear', url assert_equal true, params[:field_data] true end.returns(FakeResponse.new) subject.indices.clear_cache :field_data => true end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_cache/clear', url true end.returns(FakeResponse.new) subject.indices.clear_cache :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/close_test.rb000066400000000000000000000025721253341257200270240ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesCloseTest < ::Test::Unit::TestCase context "Indices: Close" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.indices.close end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'foo/_close', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.close :index => 'foo' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_close', url assert_equal '1s', params[:timeout] true end.returns(FakeResponse.new) subject.indices.close :index => 'foo', :timeout => '1s' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_close', url true end.returns(FakeResponse.new) subject.indices.close :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/create_test.rb000066400000000000000000000025521253341257200271600ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesCreateTest < ::Test::Unit::TestCase context "Indices: Create" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.indices.create end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.create :index => 'foo' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo', url assert_equal '1s', params[:timeout] true end.returns(FakeResponse.new) subject.indices.create :index => 'foo', :timeout => '1s' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar', url true end.returns(FakeResponse.new) subject.indices.create :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/delete_alias_test.rb000066400000000000000000000024521253341257200303270ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesDeleteAliasTest < ::Test::Unit::TestCase context "Indices: Delete alias" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.indices.delete_alias :name => 'bar' end end should "require the :name argument" do assert_raise ArgumentError do subject.indices.delete_alias :index => 'foo' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal 'foo/_alias/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.delete_alias :index => 'foo', :name => 'bar' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_alias/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.delete_alias :index => 'foo^bar', :name => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/delete_mapping_test.rb000066400000000000000000000031711253341257200306700ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesDeleteMappingTest < ::Test::Unit::TestCase context "Indices: Delete mapping" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.indices.delete_mapping :type => 'bar' end end should "require the :type argument" do assert_raise ArgumentError do subject.indices.delete_mapping :index => 'foo' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal 'foo/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.delete_mapping :index => 'foo', :type => 'bar' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/baz', url true end.returns(FakeResponse.new) subject.indices.delete_mapping :index => ['foo','bar'], :type => 'baz' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.delete_mapping :index => 'foo^bar', :type => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/delete_template_test.rb000066400000000000000000000026741253341257200310570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesDeleteTemplateTest < ::Test::Unit::TestCase context "Indices: Delete template" 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 '_template/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.delete_template :name => 'foo' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_template/foo%5Ebar', url true end.returns(FakeResponse.new) subject.indices.delete_template :name => 'foo^bar' end should "raise a NotFound exception" do subject.expects(:perform_request).raises(NotFound) assert_raise NotFound do assert ! subject.indices.delete_template(:name => 'foo') end end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do assert ! subject.indices.delete_template(:name => 'foo', :ignore => 404) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/delete_test.rb000066400000000000000000000037551253341257200271650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesDeleteTest < ::Test::Unit::TestCase context "Indices: 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 'foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.delete :index => 'foo' end should "perform the request for more indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar', url true end.returns(FakeResponse.new) subject.indices.delete :index => ['foo','bar'] end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo', url assert_equal '1s', params[:timeout] true end.returns(FakeResponse.new) subject.indices.delete :index => 'foo', :timeout => '1s' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar', url true end.returns(FakeResponse.new) subject.indices.delete :index => 'foo^bar' end should "raise a NotFound exception" do subject.expects(:perform_request).raises(NotFound) assert_raise NotFound do subject.indices.delete :index => 'foo' end end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.indices.delete :index => 'foo', :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/delete_warmer_test.rb000066400000000000000000000041111253341257200305250ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesDeleteWarmerTest < ::Test::Unit::TestCase context "Indices: Delete warmer" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.indices.delete_warmer end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal 'foo/_warmer', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.delete_warmer :index => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_warmer', url true end.returns(FakeResponse.new) subject.indices.delete_warmer :index => ['foo','bar'] end should "perform request against single warmer" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_warmer/bar', url true end.returns(FakeResponse.new) subject.indices.delete_warmer :index => 'foo', :name => 'bar' end should "perform request against multiple warmers" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_warmer/bar,baz', url true end.returns(FakeResponse.new) subject.indices.delete_warmer :index => 'foo', :name => ['bar', 'baz'] end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_warmer/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.delete_warmer :index => 'foo^bar', :name => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/exists_alias_test.rb000066400000000000000000000047161253341257200304110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesExistsAliasTest < ::Test::Unit::TestCase context "Indices: Exists alias" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'HEAD', method assert_equal '_alias/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.exists_alias :name => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_alias/bam', url true end.returns(FakeResponse.new) subject.indices.exists_alias :index => ['foo','bar'], :name => 'bam' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_alias/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.exists_alias :index => 'foo^bar', :name => 'bar/bam' end should "return true for successful response" do subject.expects(:perform_request).returns(FakeResponse.new 200, 'OK') assert_equal true, subject.indices.exists_alias(:name => 'foo') end should "return false for 404 response" do subject.expects(:perform_request).returns(FakeResponse.new 404, 'Not Found') assert_equal false, subject.indices.exists_alias(:name => 'none') end should "return false on 'not found' exceptions" do subject.expects(:perform_request).raises(StandardError.new '404 NotFound') assert_nothing_raised do assert_equal false, subject.indices.exists_alias(:name => 'none') end end should "re-raise generic exceptions" do subject.expects(:perform_request).raises(StandardError) assert_raise(StandardError) do assert_equal false, subject.indices.exists_alias(:name => 'none') end end should "be aliased as predicate method" do assert_nothing_raised do subject.indices.exists_alias?(:name => 'foo') == subject.indices.exists_alias(:name => 'foo') end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/exists_template_test.rb000066400000000000000000000036351253341257200311320ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesExistsTemplateTest < ::Test::Unit::TestCase context "Indices: Exists template" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'HEAD', method assert_equal '_template/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.exists_template :name => 'foo' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_template/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.exists_template :name => 'bar/bam' end should "return true for successful response" do subject.expects(:perform_request).returns(FakeResponse.new 200, 'OK') assert_equal true, subject.indices.exists_template(:name => 'bar') end should "return false for 404 response" do subject.expects(:perform_request).returns(FakeResponse.new 404, 'Not Found') assert_equal false, subject.indices.exists_template(:name => 'none') end should "return false on 'not found' exceptions" do subject.expects(:perform_request).raises(StandardError.new '404 NotFound') assert_nothing_raised do assert_equal false, subject.indices.exists_template(:name => 'none') end end should "re-raise generic exceptions" do subject.expects(:perform_request).raises(StandardError) assert_raise(StandardError) do assert_equal false, subject.indices.exists_template(:name => 'none') end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/exists_test.rb000066400000000000000000000044631253341257200272370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesExistsTest < ::Test::Unit::TestCase context "Indices: Exists" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'HEAD', method assert_equal 'foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.exists(:index => 'foo') end should "perform the request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar', url true end.returns(FakeResponse.new) subject.indices.exists(:index => ['foo', 'bar']) end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar,bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.exists :index => 'foo^bar,bar/bam' end should "return true for successful response" do subject.expects(:perform_request).returns(FakeResponse.new 200, 'OK') assert_equal true, subject.indices.exists(:index => 'foo') end should "return false for 404 response" do subject.expects(:perform_request).returns(FakeResponse.new 404, 'Not Found') assert_equal false, subject.indices.exists(:index => 'none') end should "return false on 'not found' exceptions" do subject.expects(:perform_request).raises(StandardError.new '404 NotFound') assert_equal false, subject.indices.exists(:index => 'none') end should "re-raise generic exceptions" do subject.expects(:perform_request).raises(StandardError) assert_raise(StandardError) do assert_equal false, subject.indices.exists(:index => 'none') end end should "be aliased as predicate method" do assert_nothing_raised do subject.indices.exists?(:index => 'foo') == subject.indices.exists(:index => 'foo') end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/exists_type_test.rb000066400000000000000000000050511253341257200302720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesExistsTypeTest < ::Test::Unit::TestCase context "Indices: Exists type" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'HEAD', method assert_equal 'foo/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.exists_type :index => 'foo', :type => 'bar' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/bam', url true end.returns(FakeResponse.new) subject.indices.exists_type :index => ['foo','bar'], :type => 'bam' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.exists_type :index => 'foo^bar', :type => 'bar/bam' end should "return true for successful response" do subject.expects(:perform_request).returns(FakeResponse.new 200, 'OK') assert_equal true, subject.indices.exists_type(:index => 'foo', :type => 'bar') end should "return false for 404 response" do subject.expects(:perform_request).returns(FakeResponse.new 404, 'Not Found') assert_equal false, subject.indices.exists_type(:index => 'foo', :type => 'none') end should "return false on 'not found' exceptions" do subject.expects(:perform_request).raises(StandardError.new '404 NotFound') assert_nothing_raised do assert_equal false, subject.indices.exists_type(:index => 'foo', :type => 'none') end end should "re-raise generic exceptions" do subject.expects(:perform_request).raises(StandardError) assert_raise(StandardError) do assert_equal false, subject.indices.exists_type(:index => 'foo', :type => 'none') end end should "be aliased as predicate method" do assert_nothing_raised do subject.indices.exists_type?(:index => 'foo', :type => 'bar') == subject.indices.exists_type(:index => 'foo', :type => 'bar') end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/flush_test.rb000066400000000000000000000030141253341257200270300ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesFlushTest < ::Test::Unit::TestCase context "Indices: Flush" 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 '_flush', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.flush end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_flush', url true end.returns(FakeResponse.new) subject.indices.flush :index => ['foo','bar'] end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_flush', url true end.returns(FakeResponse.new) subject.indices.flush :index => 'foo^bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_flush', url assert_equal true, params[:refresh] true end.returns(FakeResponse.new) subject.indices.flush :index => 'foo', :refresh => true end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_alias_test.rb000066400000000000000000000024031253341257200276400ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetAliasTest < ::Test::Unit::TestCase context "Indices: Get alias" 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 '_alias/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_alias :name => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_alias/bam', url true end.returns(FakeResponse.new) subject.indices.get_alias :index => ['foo','bar'], :name => 'bam' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_alias/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.get_alias :index => 'foo^bar', :name => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_aliases_test.rb000066400000000000000000000030331253341257200301700ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetAliasesTest < ::Test::Unit::TestCase context "Indices: Get aliases" 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 '_aliases', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_aliases end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_aliases', url true end.returns(FakeResponse.new) subject.indices.get_aliases :index => 'foo' end should "get a specific alias" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_aliases/bar', url assert_equal Hash.new, params true end.returns(FakeResponse.new) subject.indices.get_aliases :index => 'foo', :name => 'bar' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_aliases', url true end.returns(FakeResponse.new) subject.indices.get_aliases :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_field_mapping_test.rb000066400000000000000000000025061253341257200313510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetFieldMappingTest < ::Test::Unit::TestCase context "Indices: Get field 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 '_mapping/field/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_field_mapping :field => 'foo' end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_mapping/field/bam', url true end.returns(FakeResponse.new) subject.indices.get_field_mapping :index => 'foo', :field => 'bam' end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_mapping/bar/field/bam', url true end.returns(FakeResponse.new) subject.indices.get_field_mapping :index => 'foo', :type => 'bar', :field => 'bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_mapping_test.rb000066400000000000000000000036231253341257200302070ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetMappingTest < ::Test::Unit::TestCase context "Indices: Get 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 '_mapping', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_mapping end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_mapping', url true end.returns(FakeResponse.new) subject.indices.get_mapping :index => 'foo' end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_mapping/bar', url true end.returns(FakeResponse.new) subject.indices.get_mapping :index => 'foo', :type => 'bar' end should "perform request against multiple indices and types" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_mapping/bam,baz', url true end.returns(FakeResponse.new) subject.indices.get_mapping :index => ['foo', 'bar'], :type => ['bam', 'baz'] end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_mapping/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.get_mapping :index => 'foo^bar', :type => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_settings_test.rb000066400000000000000000000030561253341257200304140ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetSettingsTest < ::Test::Unit::TestCase context "Indices: Get settings" 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 '_settings', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_settings end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_settings', url true end.returns(FakeResponse.new) subject.indices.get_settings :index => 'foo' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_settings', url true end.returns(FakeResponse.new) subject.indices.get_settings :index => 'foo^bar' end should "get specific settings" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_settings/foo.bar', url assert_equal Hash.new, params true end.returns(FakeResponse.new) subject.indices.get_settings :index => 'foo', :name => 'foo.bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_template_test.rb000066400000000000000000000022421253341257200303630ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetTemplateTest < ::Test::Unit::TestCase context "Indices: Get template" 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 '_template/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_template :name => 'foo' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_template/foo%5Ebar', url true end.returns(FakeResponse.new) subject.indices.get_template :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.get_template :id => 1, :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_test.rb000066400000000000000000000023601253341257200264710ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetTest < ::Test::Unit::TestCase context "Indices: 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 'foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get :index => 'foo' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo', url assert_equal 1, params[:ignore_unavailable] true end.returns(FakeResponse.new) subject.indices.get :index => 'foo', :ignore_unavailable => 1 end should "encode features in URL" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_settings', url true end.returns(FakeResponse.new) subject.indices.get :index => 'foo', :feature => '_settings' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/get_warmer_test.rb000066400000000000000000000023561253341257200300530ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesGetWarmerTest < ::Test::Unit::TestCase context "Indices: Get warmer" 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 '_all/_warmer', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.get_warmer :index => '_all' end should "return single warmer" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_warmer/bar', url true end.returns(FakeResponse.new) subject.indices.get_warmer :index => 'foo', :name => 'bar' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_warmer/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.get_warmer :index => 'foo^bar', :name => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/open_test.rb000066400000000000000000000025611253341257200266560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesOpenTest < ::Test::Unit::TestCase context "Indices: Open" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.indices.open end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'foo/_open', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.open :index => 'foo' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_open', url assert_equal '1s', params[:timeout] true end.returns(FakeResponse.new) subject.indices.open :index => 'foo', :timeout => '1s' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_open', url true end.returns(FakeResponse.new) subject.indices.open :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/optimize_test.rb000066400000000000000000000030661253341257200275560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesOptimizeTest < ::Test::Unit::TestCase context "Indices: Optimize" 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 '_optimize', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.optimize end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_optimize', url true end.returns(FakeResponse.new) subject.indices.optimize :index => ['foo','bar'] end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_optimize', url assert_equal 1, params[:max_num_segments] true end.returns(FakeResponse.new) subject.indices.optimize :index => 'foo', :max_num_segments => 1 end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_optimize', url true end.returns(FakeResponse.new) subject.indices.optimize :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/put_alias_test.rb000066400000000000000000000034511253341257200276750ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesPutAliasTest < ::Test::Unit::TestCase context "Indices: Put alias" do subject { FakeClient.new } should "require the :name argument" do assert_raise ArgumentError do subject.indices.put_alias :index => 'foo' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo/_alias/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.put_alias :index => 'foo', :name => 'bar' end should "send the alias settings in :body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo', body[:filter] true end.returns(FakeResponse.new) subject.indices.put_alias :index => 'foo', :name => 'bar', :body => { :filter => 'foo' } end should "Listify indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_alias/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.put_alias :index => ['foo', 'bar'], :name => 'bar/bam', :body => {} end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_alias/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.put_alias :index => 'foo^bar', :name => 'bar/bam', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/put_mapping_test.rb000066400000000000000000000036761253341257200302500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesPutMappingTest < ::Test::Unit::TestCase context "Indices: Put mapping" do subject { FakeClient.new } should "require the :type argument" do assert_raise ArgumentError do subject.indices.put_mapping :index => 'foo', :body => {} end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo/_mapping/bar', url assert_equal Hash.new, params assert_equal({ :foo => {} }, body) true end.returns(FakeResponse.new) subject.indices.put_mapping :index => 'foo', :type => 'bar', :body => { :foo => {} } end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_mapping/bam', url true end.returns(FakeResponse.new) subject.indices.put_mapping :index => ['foo','bar'], :type => 'bam', :body => {} end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_mapping/bar', url assert_equal true, params[:ignore_conflicts] true end.returns(FakeResponse.new) subject.indices.put_mapping :index => 'foo', :type => 'bar', :body => {}, :ignore_conflicts => true end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_mapping/bar%2Fbam', url true end.returns(FakeResponse.new) subject.indices.put_mapping :index => 'foo^bar', :type => 'bar/bam', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/put_settings_test.rb000066400000000000000000000041061253341257200304420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesPutSettingsTest < ::Test::Unit::TestCase context "Indices: Put settings" do subject { FakeClient.new } should "require the :body argument" do assert_raise ArgumentError do subject.indices.put_settings end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_settings', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.indices.put_settings :body => {} end should "perform request with parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal true, params[:flat_settings] true end.returns(FakeResponse.new) subject.indices.put_settings :index => 'foo', :flat_settings => true, :body => {} end should "perform request against a specific indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_settings', url true end.returns(FakeResponse.new) subject.indices.put_settings :index => 'foo', :body => {} end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_settings', url true end.returns(FakeResponse.new) subject.indices.put_settings :index => ['foo','bar'], :body => {} end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_settings', url true end.returns(FakeResponse.new) subject.indices.put_settings :index => 'foo^bar', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/put_template_test.rb000066400000000000000000000032411253341257200304140ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesPutTemplateTest < ::Test::Unit::TestCase context "Indices: Put template" do subject { FakeClient.new } should "require the :name argument" do assert_raise ArgumentError do subject.indices.put_template :body => {} end end should "require the :body argument" do assert_raise ArgumentError do subject.indices.put_template :name => 'foo' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_template/foo', url assert_equal Hash.new, params assert_equal 'bar', body[:template] true end.returns(FakeResponse.new) subject.indices.put_template :name => 'foo', :body => { :template => 'bar' } end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_template/foo', url assert_equal 3, params[:order] true end.returns(FakeResponse.new) subject.indices.put_template :name => 'foo', :body => {}, :order => 3 end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_template/foo%5Ebar', url true end.returns(FakeResponse.new) subject.indices.put_template :name => 'foo^bar', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/put_warmer_test.rb000066400000000000000000000041701253341257200301000ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesPutWarmerTest < ::Test::Unit::TestCase context "Indices: Put warmer" do subject { FakeClient.new } should "require the :name argument" do assert_raise ArgumentError do subject.indices.put_warmer :index => 'foo', :body => {} end end should "require the :body argument" do assert_raise ArgumentError do subject.indices.put_warmer :index => 'foo', :name => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal 'foo/_warmer/bar', url assert_equal Hash.new, params assert_equal :match_all, body[:query].keys.first true end.returns(FakeResponse.new) subject.indices.put_warmer :index => 'foo', :name => 'bar', :body => { :query => { :match_all => {} } } end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_warmer/xul', url true end.returns(FakeResponse.new) subject.indices.put_warmer :index => ['foo','bar'], :name => 'xul', :body => {} end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/_warmer/xul', url true end.returns(FakeResponse.new) subject.indices.put_warmer :index => 'foo', :type => 'bar', :name => 'xul', :body => {} end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/_warmer/qu+uz', url true end.returns(FakeResponse.new) subject.indices.put_warmer :index => 'foo^bar', :type => 'bar/bam', :name => 'qu uz', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/recovery_test.rb000066400000000000000000000011531253341257200275470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesRecoveryTest < ::Test::Unit::TestCase context "Indices: Recovery" 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/_recovery', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.recovery :index => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/refresh_test.rb000066400000000000000000000036531253341257200273560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesRefreshTest < ::Test::Unit::TestCase context "Indices: Refresh" 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 '_refresh', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.refresh end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_refresh', url true end.returns(FakeResponse.new) subject.indices.refresh :index => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_refresh', url true end.returns(FakeResponse.new).twice subject.indices.refresh :index => ['foo','bar'] subject.indices.refresh :index => 'foo,bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_refresh', url assert_equal 'missing', params[:ignore_indices] true end.returns(FakeResponse.new) subject.indices.refresh :index => ['foo','bar'], :ignore_indices => 'missing' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_refresh', url true end.returns(FakeResponse.new) subject.indices.refresh :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/seal_test.rb000066400000000000000000000010621253341257200266340ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesSealTest < ::Test::Unit::TestCase context "Indices: Seal" 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 'foo/_seal', url assert_nil body true end.returns(FakeResponse.new) subject.indices.seal :index => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/segments_test.rb000066400000000000000000000036671253341257200275520ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesSegmentsTest < ::Test::Unit::TestCase context "Indices: Segments" 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 '_segments', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.segments end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_segments', url true end.returns(FakeResponse.new) subject.indices.segments :index => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_segments', url true end.returns(FakeResponse.new).twice subject.indices.segments :index => ['foo','bar'] subject.indices.segments :index => 'foo,bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_segments', url assert_equal 'missing', params[:ignore_indices] true end.returns(FakeResponse.new) subject.indices.segments :index => ['foo','bar'], :ignore_indices => 'missing' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_segments', url true end.returns(FakeResponse.new) subject.indices.segments :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/snapshot_index_test.rb000066400000000000000000000040171253341257200307410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesSnapshotIndexTest < ::Test::Unit::TestCase context "Indices: Snapshot index" 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 '_gateway/snapshot', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.snapshot_index end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_gateway/snapshot', url true end.returns(FakeResponse.new) subject.indices.snapshot_index :index => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_gateway/snapshot', url true end.returns(FakeResponse.new).twice subject.indices.snapshot_index :index => ['foo','bar'] subject.indices.snapshot_index :index => 'foo,bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_gateway/snapshot', url assert_equal 'missing', params[:ignore_indices] true end.returns(FakeResponse.new) subject.indices.snapshot_index :index => ['foo','bar'], :ignore_indices => 'missing' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_gateway/snapshot', url true end.returns(FakeResponse.new) subject.indices.snapshot_index :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/stats_test.rb000066400000000000000000000046431253341257200270560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesStatsTest < ::Test::Unit::TestCase context "Indices: 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 '_stats', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.stats end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_stats', url true end.returns(FakeResponse.new) subject.indices.stats :index => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_stats', url true end.returns(FakeResponse.new).twice subject.indices.stats :index => ['foo','bar'] subject.indices.stats :index => 'foo,bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_stats', url assert_equal true, params[:expand_wildcards] true end.returns(FakeResponse.new) subject.indices.stats :index => 'foo', :expand_wildcards => true end should "pass the fields parameter as a list" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_stats/fielddata', url assert_nil params[:fielddata] assert_equal 'foo,bar', params[:fields] true end.returns(FakeResponse.new) subject.indices.stats :index => 'foo', :fielddata => true, :fields => ['foo', 'bar'] end should "pass the groups parameter as a list" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_stats/search', url assert_equal 'groupA,groupB', params[:groups] true end.returns(FakeResponse.new) subject.indices.stats :search => true, :groups => ['groupA','groupB'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/status_test.rb000066400000000000000000000035731253341257200272440ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesStatusTest < ::Test::Unit::TestCase context "Indices: Status" 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 '_status', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.status end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_status', url true end.returns(FakeResponse.new) subject.indices.status :index => 'foo' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_status', url true end.returns(FakeResponse.new).twice subject.indices.status :index => ['foo','bar'] subject.indices.status :index => 'foo,bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_status', url assert_equal true, params[:recovery] true end.returns(FakeResponse.new) subject.indices.status :index => 'foo', :recovery => true end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_status', url true end.returns(FakeResponse.new) subject.indices.status :index => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/update_aliases_test.rb000066400000000000000000000022171253341257200306760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesPutAliasesTest < ::Test::Unit::TestCase context "Indices: Update aliases" do subject { FakeClient.new } should "require the :body argument" do assert_raise ArgumentError do subject.indices.update_aliases end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_aliases', url assert_equal Hash.new, params assert_equal [], body[:actions] true end.returns(FakeResponse.new) subject.indices.update_aliases :body => { :actions => [] } end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_aliases', url assert_equal '1s', params[:timeout] true end.returns(FakeResponse.new) subject.indices.update_aliases :body => {}, :timeout => '1s' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/upgrade_test.rb000066400000000000000000000011241253341257200273360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesUpgradeTest < ::Test::Unit::TestCase context "Indices: 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 '_upgrade', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.upgrade end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/indices/validate_query_test.rb000066400000000000000000000053331253341257200307330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class IndicesValidateQueryTest < ::Test::Unit::TestCase context "Indices: Validate query" 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 '_validate/query', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.indices.validate_query end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_validate/query', url true end.returns(FakeResponse.new) subject.indices.validate_query :index => 'foo' end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/_validate/query', url true end.returns(FakeResponse.new) subject.indices.validate_query :index => 'foo', :type => 'bar' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_validate/query', url true end.returns(FakeResponse.new).twice subject.indices.validate_query :index => ['foo', 'bar'] subject.indices.validate_query :index => 'foo,bar' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_validate/query', url assert_equal true, params[:explain] assert_equal 'foo', params[:q] true end.returns(FakeResponse.new) subject.indices.validate_query :explain => true, :q => 'foo' end should "pass the query definition in body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_validate/query', url assert_equal Hash.new, body[:filtered] true end.returns(FakeResponse.new) subject.indices.validate_query :body => { :filtered => {} } end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_validate/query', url true end.returns(FakeResponse.new) subject.indices.validate_query :index => 'foo^bar', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/info_test.rb000066400000000000000000000010521253341257200252240ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class InfoTest < ::Test::Unit::TestCase context "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 '', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.info end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/json_builders_test.rb000066400000000000000000000033651253341257200271440ustar00rootroot00000000000000require 'test_helper' require 'jbuilder' if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' require 'jsonify' module Elasticsearch module Test class JsonBuildersTest < ::Test::Unit::TestCase context "JBuilder" do subject { FakeClient.new } should "build a JSON" do subject.expects(:perform_request).with do |method, url, params, body| json = MultiJson.load(body) assert_instance_of String, body assert_equal 'test', json['query']['match']['title']['query'] true end.returns(FakeResponse.new) json = Jbuilder.encode do |json| json.query do json.match do json.title do json.query 'test' end end end end subject.search :body => json end end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' context "Jsonify" do subject { FakeClient.new } should "build a JSON" do subject.expects(:perform_request).with do |method, url, params, body| json = MultiJson.load(body) assert_instance_of String, body assert_equal 'test', json['query']['match']['title']['query'] true end.returns(FakeResponse.new) json = Jsonify::Builder.compile do |json| json.query do json.match do json.title do json.query 'test' end end end end subject.search :body => json end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/list_benchmarks_test.rb000066400000000000000000000011201253341257200274350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ListBenchmarksTest < ::Test::Unit::TestCase context "List benchmarks" 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 '_bench', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.list_benchmarks end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/mget_test.rb000066400000000000000000000045721253341257200252370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class MgetTest < ::Test::Unit::TestCase context "Mget" do subject { FakeClient.new } should "require the :body argument" do assert_raise ArgumentError do subject.mget end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_mget', url assert_equal Hash.new, params assert_equal [], body[:docs] true end.returns(FakeResponse.new) subject.mget :body => { :docs => [] } end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_mget', url true end.returns(FakeResponse.new) subject.mget :index => 'foo', :body => {} end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/_mget', url assert_equal ['1', '2'], body[:ids] true end.returns(FakeResponse.new) subject.mget :index => 'foo', :type => 'bar', :body => { :ids => ['1','2'] } end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_mget', url assert_equal true, params[:refresh] true end.returns(FakeResponse.new) subject.mget :body => {}, :refresh => true end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/_mget', url true end.returns(FakeResponse.new) subject.mget :index => 'foo^bar', :type => 'bar/bam', :body => { :ids => ['1','2'] } end should "pass the fields parameter as a list" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar', params[:fields] true end.returns(FakeResponse.new) subject.mget :body => {}, :fields => ['foo', 'bar'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/mlt_test.rb000066400000000000000000000056051253341257200250750ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class MltTest < ::Test::Unit::TestCase context "More Like This" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.mlt :type => 'bar', :id => '1' end end should "require the :type argument" do assert_raise ArgumentError do subject.mlt :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.mlt :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo/bar/1/_mlt', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.mlt :index => 'foo', :type => 'bar', :id => '1' end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1/_mlt', url assert_equal 1, params[:max_doc_freq] true end.returns(FakeResponse.new) subject.mlt :index => 'foo', :type => 'bar', :id => '1', :max_doc_freq => 1 end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/1/_mlt', url true end.returns(FakeResponse.new) subject.mlt :index => 'foo^bar', :type => 'bar/bam', :id => '1' end should "pass the specific parameters as a list" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar', params[:mlt_fields] assert_equal 'A,B', params[:search_indices] assert_equal 'X,Y', params[:search_types] assert_equal 'lam,bam', params[:stop_words] true end.returns(FakeResponse.new) subject.mlt :index => 'foo', :type => 'bar', :id => '1', :mlt_fields => ['foo', 'bar'], :search_indices => ['A', 'B'], :search_types => ['X', 'Y'], :stop_words => ['lam','bam'] end should "pass a specific search definition in body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1/_mlt', url assert_equal Hash.new, body[:query] true end.returns(FakeResponse.new) subject.mlt :index => 'foo', :type => 'bar', :id => '1', :body => { :query => {} } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/mpercolate_test.rb000066400000000000000000000030221253341257200264230ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class MpercolateTest < ::Test::Unit::TestCase context "Mpercolate" do subject { FakeClient.new } should "require the :body argument" do assert_raise ArgumentError do subject.mpercolate end end should "post correct payload to the endpoint" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_mpercolate', url assert_equal Hash.new, params lines = body.split("\n") assert_match /\{"percolate"/, lines[0] assert_match /\{"doc"/, lines[1] assert_match /\{"percolate"/, lines[2] assert_match /\{\}/, lines[3] true end.returns(FakeResponse.new) subject.mpercolate :body => [ { :percolate => { :index => "my-index", :type => "my-type" } }, { :doc => { :message => "foo bar" } }, { :percolate => { :index => "my-other-index", :type => "my-other-type", :id => "1" } }, { } ] end should "post a string payload intact" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal %Q|{"foo":"bar"}\n{"moo":"lam"}|, body true end.returns(FakeResponse.new) subject.mpercolate :body => %Q|{"foo":"bar"}\n{"moo":"lam"}| end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/msearch_test.rb000066400000000000000000000104411253341257200257150ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class MsearchTest < ::Test::Unit::TestCase context "Msearch" do subject { FakeClient.new } should "require the :body argument" do assert_raise ArgumentError do subject.msearch end end should "post correct payload to the endpoint" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_msearch', url assert_equal Hash.new, params assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), body {"index":"foo"} {"query":{"match_all":{}}} {"index":"bar"} {"query":{"match":{"foo":"bar"}}} {"search_type":"count"} {"facets":{"tags":{}}} PAYLOAD true end.returns(FakeResponse.new) subject.msearch :body => [ { :index => 'foo', :search => { :query => { :match_all => {} } } }, { :index => 'bar', :search => { :query => { :match => { :foo => 'bar' } } } }, { :search_type => 'count', :search => { :facets => { :tags => {} } } } ] end should "post a string payload intact" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal %Q|{"foo":"bar"}\n{"moo":"lam"}|, body true end.returns(FakeResponse.new) subject.msearch :body => %Q|{"foo":"bar"}\n{"moo":"lam"}| end should "serialize and post header/data pairs" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_msearch', url assert_equal Hash.new, params assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), body {"index":"foo"} {"query":{"match_all":{}}} {"index":"bar"} {"query":{"match":{"foo":"bar"}}} PAYLOAD true end.returns(FakeResponse.new) subject.msearch :body => [ { :index => 'foo' }, { :query => { :match_all => {} } }, { :index => 'bar' }, { :query => { :match => { :foo => 'bar' } } } ] end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_msearch', url true end.returns(FakeResponse.new) subject.msearch :index => 'foo', :body => [] end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/_msearch', url true end.returns(FakeResponse.new) subject.msearch :index => 'foo', :type => 'bar', :body => [] end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_msearch', url true end.returns(FakeResponse.new) subject.msearch :index => ['foo', 'bar'], :body => [] end should "perform request against multiple indices and types" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/lam,bam/_msearch', url true end.returns(FakeResponse.new) subject.msearch :index => ['foo', 'bar'], :type => ['lam', 'bam'], :body => [] end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/_msearch', url true end.returns(FakeResponse.new) subject.msearch :index => 'foo^bar', :type => 'bar/bam', :body => [] end should "encode URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_msearch', url assert_equal 'scroll', params[:search_type] true end.returns(FakeResponse.new) subject.msearch :body => [], :search_type => 'scroll' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/mtermvectors_test.rb000066400000000000000000000022571253341257200270330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class MtermvectorsTest < ::Test::Unit::TestCase context "Mtermvectors" 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 'my-index/my-type/_mtermvectors', url assert_equal Hash.new, params assert_equal [1, 2, 3], body[:ids] true end.returns(FakeResponse.new) subject.mtermvectors :index => 'my-index', :type => 'my-type', :body => { :ids => [1, 2, 3] } end should "allow passing a list of IDs instead of the body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'my-index/my-type/_mtermvectors', url assert_equal Hash.new, params assert_equal [1, 2, 3], body[:ids] true end.returns(FakeResponse.new) subject.mtermvectors :index => 'my-index', :type => 'my-type', :ids => [1, 2, 3] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/nodes/000077500000000000000000000000001253341257200240175ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/nodes/hot_threads_test.rb000066400000000000000000000023111253341257200277040ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class NodesHotThreadsTest < ::Test::Unit::TestCase context "Nodes: Hot Threads" 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 '_nodes/hot_threads', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.nodes.hot_threads end should "send :node_id correctly" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/foo/hot_threads', url true end.returns(FakeResponse.new) subject.nodes.hot_threads :node_id => 'foo' end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/foo%5Ebar/hot_threads', url true end.returns(FakeResponse.new) subject.nodes.hot_threads :node_id => 'foo^bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/nodes/info_test.rb000066400000000000000000000044061253341257200263420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class NodesInfoTest < ::Test::Unit::TestCase context "Nodes: 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 '_nodes', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.nodes.info end should "send :node_id correctly" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/foo', url true end.returns(FakeResponse.new) subject.nodes.info :node_id => 'foo' end should "send multiple :node_id-s correctly" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/A,B,C', url true end.returns(FakeResponse.new).twice subject.nodes.info :node_id => 'A,B,C' subject.nodes.info :node_id => ['A', 'B', 'C'] end should "properly pass URL parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_same_elements ['http','jvm'], url.split('/').last.split(',') assert_nil params[:jvm] assert_nil params[:http] true end.returns(FakeResponse.new) subject.nodes.info :jvm => true, :http => true end should "properly pass URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes', url assert_equal 'yaml', params[:format] true end.returns(FakeResponse.new) subject.nodes.info :format => 'yaml' end should "encode metrics" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/http,network', url assert_nil params[:metric] true end.returns(FakeResponse.new) subject.nodes.info :metric => ['http', 'network'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/nodes/shutdown_test.rb000066400000000000000000000024311253341257200272560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class NodesShutdownTest < ::Test::Unit::TestCase context "Nodes: Shutdown" 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 '_cluster/nodes/_shutdown', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.nodes.shutdown end should "send :node_id correctly" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_cluster/nodes/foo/_shutdown', url true end.returns(FakeResponse.new) subject.nodes.shutdown :node_id => 'foo' end should "send multiple :node_id-s correctly" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_cluster/nodes/A,B,C/_shutdown', url true end.returns(FakeResponse.new).twice subject.nodes.shutdown :node_id => 'A,B,C' subject.nodes.shutdown :node_id => ['A', 'B', 'C'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/nodes/stats_test.rb000066400000000000000000000041411253341257200265410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class NodesStatsTest < ::Test::Unit::TestCase context "Nodes: 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 '_nodes/stats', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.nodes.stats end should "send :node_id correctly" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/foo/stats', url true end.returns(FakeResponse.new) subject.nodes.stats :node_id => 'foo' end should "get specific metric families" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/stats/http,fs', url assert_equal( {}, params ) true end.returns(FakeResponse.new) subject.nodes.stats :metric => [:http, :fs] end should "get specific metric for the indices family" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/stats/indices/filter_cache', url true end.returns(FakeResponse.new) subject.nodes.stats :metric => :indices, :index_metric => 'filter_cache' end should "get fielddata statistics for the indices family" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_nodes/stats/indices/fielddata', url assert_equal( {:fields => 'foo,bar'}, params ) true end.returns(FakeResponse.new).twice subject.nodes.stats :metric => 'indices', :index_metric => 'fielddata', :fields => 'foo,bar' subject.nodes.stats :metric => 'indices', :index_metric => 'fielddata', :fields => ['foo','bar'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/percolate_test.rb000066400000000000000000000025531253341257200262560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class PercolateTest < ::Test::Unit::TestCase context "Percolate" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.percolate :type => 'bar', :body => {} end end should "require the :type argument" do assert_raise ArgumentError do subject.percolate :index => 'bar', :body => {} end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo/bar/_percolate', url assert_equal Hash.new, params assert_equal 'bar', body[:doc][:foo] true end.returns(FakeResponse.new) subject.percolate :index => 'foo', :type => 'bar', :body => { :doc => { :foo => 'bar' } } end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/_percolate', url true end.returns(FakeResponse.new) subject.percolate :index => 'foo^bar', :type => 'bar/bam', :body => { :doc => { :foo => 'bar' } } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/ping_test.rb000066400000000000000000000025421253341257200252330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class PingTest < ::Test::Unit::TestCase context "Indices: Exists" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'HEAD', method assert_equal '', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.ping end should "return true for successful response" do subject.expects(:perform_request).returns(FakeResponse.new 200, 'OK') assert_equal true, subject.ping end should "return false for 404 response" do subject.expects(:perform_request).returns(FakeResponse.new 404, 'Not Found') assert_equal false, subject.ping end should "return false on 'not found' exceptions" do subject.expects(:perform_request).raises(StandardError.new '404 NotFound') assert_equal false, subject.ping end should "re-raise generic exceptions" do subject.expects(:perform_request).raises(StandardError) assert_raise(StandardError) do assert_equal false, subject.ping end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/put_script_test.rb000066400000000000000000000012351253341257200264700ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class PutScriptTest < ::Test::Unit::TestCase context "Put script" 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 '_scripts/groovy/foo', url assert_equal Hash.new, params assert_equal 'bar', body[:script] true end.returns(FakeResponse.new) subject.put_script :lang => 'groovy', :id => 'foo', :body => { :script => 'bar' } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/put_template_test.rb000066400000000000000000000011711253341257200267760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class PutTemplateTest < ::Test::Unit::TestCase context "Put template" 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 '_search/template/foo', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.put_template :id => 'foo', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/scroll_test.rb000066400000000000000000000010731253341257200255720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class ScrollTest < ::Test::Unit::TestCase context "Scroll" 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 '_search/scroll', url assert_equal 'cXVlcn...', body true end.returns(FakeResponse.new) subject.scroll :scroll_id => 'cXVlcn...' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/search_exists_test.rb000066400000000000000000000011401253341257200271330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchExistsTest < ::Test::Unit::TestCase context "Search exists" 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 '_search/exists', url assert_equal 'foo', params[:q] assert_nil body true end.returns(FakeResponse.new) subject.search_exists :q => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/search_shards_test.rb000066400000000000000000000011221253341257200271000ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchShardsTest < ::Test::Unit::TestCase context "Search shards" 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 '_search_shards', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.search_shards end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/search_template_test.rb000066400000000000000000000012271253341257200274350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchTemplateTest < ::Test::Unit::TestCase context "Search template" 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/_search/template', url assert_equal Hash.new, params assert_equal 'bar', body[:foo] true end.returns(FakeResponse.new) subject.search_template :index => 'foo', :body => { :foo => 'bar' } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/search_test.rb000066400000000000000000000066031253341257200255450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchTest < ::Test::Unit::TestCase context "Search" 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 '_search', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.search end should "have default value for index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_all/foo/_search', url true end.returns(FakeResponse.new) subject.search :type => 'foo' end should "post a request definition in body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal :match, body[:query].keys.first true end.returns(FakeResponse.new) subject.search :body => { :query => { :match => {} } } end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_search', url true end.returns(FakeResponse.new) subject.search :index => 'foo' end should "perform request against an index and type" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/_search', url true end.returns(FakeResponse.new) subject.search :index => 'foo', :type => 'bar' end should "perform request against multiple indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/_search', url true end.returns(FakeResponse.new).twice subject.search :index => ['foo', 'bar'] subject.search :index => 'foo,bar' end should "perform request against multiple indices and types" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo,bar/lam,bam/_search', url true end.returns(FakeResponse.new).twice subject.search :index => ['foo', 'bar'], :type => ['lam', 'bam'] subject.search :index => 'foo,bar', :type => 'lam,bam' end should "encode URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_search', url assert_equal 'count', params[:search_type] true end.returns(FakeResponse.new) subject.search :search_type => 'count' end should "validate URL parameters" do assert_raise ArgumentError do subject.search :search_type => 'count', :qwertypoiuy => 'asdflkjhg' end end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/_search', url true end.returns(FakeResponse.new) subject.search :index => 'foo^bar', :type => 'bar/bam' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/000077500000000000000000000000001253341257200245465ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/create_repository_test.rb000066400000000000000000000020151253341257200316720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotCreateRepositoryTest < ::Test::Unit::TestCase context "Snapshot: Create repository" do subject { FakeClient.new } should "require the :repository argument" do assert_raise ArgumentError do subject.snapshot.create_repository :body => {} end end should "require the :body argument" do assert_raise ArgumentError do subject.snapshot.create_repository :repository => 'foo' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_snapshot/foo', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.snapshot.create_repository :repository => 'foo', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/create_test.rb000066400000000000000000000020241253341257200273730ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotCreateTest < ::Test::Unit::TestCase context "Snapshot: Create" do subject { FakeClient.new } should "require the :repository argument" do assert_raise ArgumentError do subject.snapshot.create :snapshot => 'bar', :body => {} end end should "require the :snapshot argument" do assert_raise ArgumentError do subject.snapshot.create :repository => 'foo', :body => {} end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'PUT', method assert_equal '_snapshot/foo/bar', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.snapshot.create :repository => 'foo', :snapshot => 'bar', :body => {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/delete_repository_test.rb000066400000000000000000000017341253341257200317000ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotDeleteRepositoryTest < ::Test::Unit::TestCase context "Snapshot: Delete repository" 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 '_snapshot/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.snapshot.delete_repository :repository => 'foo' end should "perform the request for more indices" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_snapshot/foo,bar', url true end.returns(FakeResponse.new) subject.snapshot.delete_repository :repository => ['foo','bar'] end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/delete_test.rb000066400000000000000000000020001253341257200273640ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotDeleteTest < ::Test::Unit::TestCase context "Snapshot: Delete" do subject { FakeClient.new } should "require the :repository argument" do assert_raise ArgumentError do subject.snapshot.delete :snapshot => 'bar', :body => {} end end should "require the :snapshot argument" do assert_raise ArgumentError do subject.snapshot.delete :repository => 'foo', :body => {} end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'DELETE', method assert_equal '_snapshot/foo/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.snapshot.delete :repository => 'foo', :snapshot => 'bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/get_repository_test.rb000066400000000000000000000012041253341257200312050ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotGetRepositoryTest < ::Test::Unit::TestCase context "Snapshot: Get repository" 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 '_snapshot/foo', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.snapshot.get_repository :repository => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/get_test.rb000066400000000000000000000017561253341257200267220ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotGetTest < ::Test::Unit::TestCase context "Snapshot: Get" do subject { FakeClient.new } should "require the :repository argument" do assert_raise ArgumentError do subject.snapshot.get :snapshot => 'bar', :body => {} end end should "require the :snapshot argument" do assert_raise ArgumentError do subject.snapshot.get :repository => 'foo', :body => {} end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_snapshot/foo/bar', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.snapshot.get :repository => 'foo', :snapshot => 'bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/restore_test.rb000066400000000000000000000017671253341257200276300ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotRestoreTest < ::Test::Unit::TestCase context "Snapshot: Restore" do subject { FakeClient.new } should "require the :repository argument" do assert_raise ArgumentError do subject.snapshot.restore :snapshot => 'bar' end end should "require the :snapshot argument" do assert_raise ArgumentError do subject.snapshot.restore :repository => 'foo' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal '_snapshot/foo/bar/_restore', url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.snapshot.restore :repository => 'foo', :snapshot => 'bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/status_test.rb000066400000000000000000000020371253341257200274570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotStatusTest < ::Test::Unit::TestCase context "Snapshot: Status" 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 '_snapshot/_status', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.snapshot.status end should "encode repository and snapshot" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_snapshot/foo/bar/_status', url assert_equal Hash.new, params assert_equal nil, body true end.returns(FakeResponse.new) subject.snapshot.status :repository => 'foo', :snapshot => 'bar' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/snapshot/verify_repository_test.rb000066400000000000000000000012261253341257200317360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SnapshotVerifyRepositoryTest < ::Test::Unit::TestCase context "Snapshot: Verify repository" 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 '_snapshot/foo/_verify', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.snapshot.verify_repository :repository => 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/suggest_test.rb000066400000000000000000000036411253341257200257600ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SuggestTest < ::Test::Unit::TestCase context "Suggest" 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 '_suggest', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.suggest :body => {} end should "perform request against an index" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_suggest', url true end.returns(FakeResponse.new) subject.suggest :index => 'foo', :body => {} end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/_suggest', url assert_equal 'abc123', params[:routing] true end.returns(FakeResponse.new) subject.suggest :index => 'foo', :routing => 'abc123', :body => {} end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/_suggest', url true end.returns(FakeResponse.new) subject.suggest :index => 'foo^bar', :body => {} end should "pass the request definition in the body" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal '_suggest', url assert_equal 'tset', body[:my_suggest][:text] true end.returns(FakeResponse.new) subject.suggest :body => { :my_suggest => { :text => 'tset' } } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/termvectors_test.rb000066400000000000000000000025201253341257200266470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class TermvectorsTest < ::Test::Unit::TestCase context "Termvectors" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.termvectors :type => 'bar', :id => '1' end end should "require the :type argument" do assert_raise ArgumentError do subject.termvectors :index => 'foo', :id => '1' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal 'foo/bar/123/_termvectors', url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.termvectors :index => 'foo', :type => 'bar', :id => '123', :body => {} end should "be aliased to singular for older versions" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/123/_termvector', url true end.returns(FakeResponse.new) subject.termvector :index => 'foo', :type => 'bar', :id => '123' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/update_document_test.rb000066400000000000000000000051721253341257200274600ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class UpdateTest < ::Test::Unit::TestCase context "Update document" do subject { FakeClient.new } should "require the :index argument" do assert_raise ArgumentError do subject.update :type => 'bar', :id => '1' end end should "require the :type argument" do assert_raise ArgumentError do subject.update :index => 'foo', :id => '1' end end should "require the :id argument" do assert_raise ArgumentError do subject.update :index => 'foo', :type => 'bar' end end should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'POST', method assert_equal 'foo/bar/1/_update', url assert_equal Hash.new, params assert_equal Hash.new, body[:doc] true end.returns(FakeResponse.new) subject.update :index => 'foo', :type => 'bar', :id => '1', :body => { :doc => {} } end should "pass the URL parameters" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo/bar/1/_update', url assert_equal 100, params[:version] true end.returns(FakeResponse.new) subject.update :index => 'foo', :type => 'bar', :id => '1', :version => 100, :body => {} end should "validate URL parameters" do assert_raise ArgumentError do subject.update :index => 'foo', :type => 'bar', :id => '1', :body => { :doc => {} }, :qwertypoiuy => 'asdflkjhg' end end should "URL-escape the parts" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'foo%5Ebar/bar%2Fbam/1/_update', url true end.returns(FakeResponse.new) subject.update :index => 'foo^bar', :type => 'bar/bam', :id => '1', :body => {} end should "raise a NotFound exception" do subject.expects(:perform_request).raises(NotFound) assert_raise NotFound do subject.update :index => 'foo', :type => 'bar', :id => 'XXX' end end should "catch a NotFound exception with the ignore parameter" do subject.expects(:perform_request).raises(NotFound) assert_nothing_raised do subject.update :index => 'foo', :type => 'bar', :id => 'XXX', :ignore => 404 end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/test/unit/utils_test.rb000066400000000000000000000172751253341257200254470ustar00rootroot00000000000000# encoding: UTF-8 require 'test_helper' module Elasticsearch module Test class UtilsTest < ::Test::Unit::TestCase include Elasticsearch::API::Utils context "Utils" do context "__escape" do should "encode Unicode characters" do assert_equal '%E4%B8%AD%E6%96%87', __escape('中文') end should "encode special characters" do assert_equal 'foo+bar', __escape('foo bar') assert_equal 'foo%2Fbar', __escape('foo/bar') assert_equal 'foo%5Ebar', __escape('foo^bar') end should "not encode asterisks" do assert_equal '*', __escape('*') end should "use CGI.escape by default" do CGI.expects(:escape) __escape('foo bar') end should "use the escape_utils gem when available" do require 'escape_utils' CGI.expects(:escape).never EscapeUtils.expects(:escape_url) __escape('foo bar') end unless RUBY_1_8 || JRUBY end context "__listify" do should "create a list from single value" do assert_equal 'foo', __listify('foo') end should "create a list from an array" do assert_equal 'foo,bar', __listify(['foo', 'bar']) end should "create a list from multiple arguments" do assert_equal 'foo,bar', __listify('foo', 'bar') end should "ignore nil values" do assert_equal 'foo,bar', __listify(['foo', nil, 'bar']) end should "encode special characters" do assert_equal 'foo,bar%5Ebam', __listify(['foo', 'bar^bam']) end end context "__pathify" do should "create a path from single value" do assert_equal 'foo', __pathify('foo') end should "create a path from an array" do assert_equal 'foo/bar', __pathify(['foo', 'bar']) end should "ignore nil values" do assert_equal 'foo/bar', __pathify(['foo', nil, 'bar']) end should "ignore empty string values" do assert_equal 'foo/bar', __pathify(['foo', '', 'bar']) end end context "__bulkify" do should "serialize array of hashes" do result = 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' } } } }, { :delete => { :_index => 'myindexC', :_type => 'mytypeC', :_id => '3' } } ] if RUBY_1_8 lines = result.split("\n") assert_equal 5, lines.size assert_match /\{"index"\:\{/, lines[0] assert_match /\{"title"\:"Test"/, lines[1] assert_match /\{"update"\:\{/, lines[2] assert_match /\{"doc"\:\{"title"/, lines[3] else assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), result {"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 end should "serialize arrays of strings" do result = Elasticsearch::API::Utils.__bulkify ['{"foo":"bar"}','{"moo":"bam"}'] assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), result {"foo":"bar"} {"moo":"bam"} PAYLOAD end should "serialize arrays of header/data pairs" do result = Elasticsearch::API::Utils.__bulkify [{:foo => "bar"},{:moo => "bam"},{:foo => "baz"}] assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), result {"foo":"bar"} {"moo":"bam"} {"foo":"baz"} PAYLOAD end should "not modify the original payload" do original = [ { :index => {:foo => 'bar', :data => { :moo => 'bam' }} } ] result = Elasticsearch::API::Utils.__bulkify original assert_not_nil original.first[:index][:data], "Deleted :data from #{original}" assert_equal <<-PAYLOAD.gsub(/^\s+/, ''), result {"index":{"foo":"bar"}} {"moo":"bam"} PAYLOAD end end context "__validate_and_extract_params" do teardown do Elasticsearch::API.settings.clear end should "extract valid params from a Hash" do assert_equal( {:foo => 'qux'}, __validate_and_extract_params({ :foo => 'qux' }, [:foo, :bar]) ) end should "raise an exception when invalid keys present" do assert_raise ArgumentError do __validate_and_extract_params({ :foo => 'qux', :bam => 'mux' }, [:foo, :bar]) end end should "not raise an exception for COMMON_PARAMS" do assert_nothing_raised do __validate_and_extract_params({ :index => 'foo'}, [:foo]) end end should "extract COMMON_QUERY_PARAMS" do assert_equal( { :format => 'yaml' }, __validate_and_extract_params( { :format => 'yaml' } ) ) end should "not validate parameters when the option is set" do assert_nothing_raised do result = __validate_and_extract_params( { :foo => 'q', :bam => 'm' }, [:foo, :bar], { :skip_parameter_validation => true } ) assert_equal( { :foo => 'q', :bam => 'm' }, result ) end end should "not validate parameters when the module setting is set" do assert_nothing_raised do Elasticsearch::API.settings[:skip_parameter_validation] = true result = __validate_and_extract_params( { :foo => 'q', :bam => 'm' }, [:foo, :bar] ) assert_equal( { :foo => 'q', :bam => 'm' }, result ) end end should "listify Arrays" do result = __validate_and_extract_params( { :foo => ['a', 'b'] }, [:foo] ) assert_equal( { :foo => 'a,b'}, result ) end end context "__extract_parts" do should "extract parts with true value from a Hash" do assert_equal( ['foo'], __extract_parts({ :foo => true, :moo => 'blah' }, [:foo, :bar]) ) end should "extract parts with string value from a Hash" do assert_equal( ['qux'], __extract_parts({ :foo => 'qux', :moo => 'blah' }, [:foo, :bar]) ) end end context "__rescue_from_not_found" do should "return false if exception class name contains 'NotFound'" do assert_equal( false, __rescue_from_not_found { raise NotFound }) end should "return false if exception message contains 'Not Found'" do assert_equal( false, __rescue_from_not_found { raise Exception.new "Not Found" }) end should "return false if exception message contains '404'" do assert_equal( false, __rescue_from_not_found { raise Exception.new "404" }) end should "raise exception if exception class name and message do not contain NotFound/404" do assert_raise Exception do __rescue_from_not_found { raise Exception.new "Any other exception" } end end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/utils/000077500000000000000000000000001253341257200221115ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/utils/Gemfile000066400000000000000000000002041253341257200234000ustar00rootroot00000000000000source 'https://rubygems.org' gem 'activesupport' gem 'rest-client' gem 'coderay' gem 'multi_json' gem 'thor' gem 'json' gem 'pry' elasticsearch-ruby-1.0.12/elasticsearch-api/utils/Thorfile000066400000000000000000000002151253341257200236060ustar00rootroot00000000000000require File.expand_path('./thor/generate_api') require File.expand_path('./thor/generate_source') require File.expand_path('./thor/lister') elasticsearch-ruby-1.0.12/elasticsearch-api/utils/thor/000077500000000000000000000000001253341257200230655ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/utils/thor/generate_api.rb000066400000000000000000000153651253341257200260470ustar00rootroot00000000000000require '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-1.0.12/elasticsearch-api/utils/thor/generate_source.rb000066400000000000000000000110731253341257200265660ustar00rootroot00000000000000# 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| @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 # -- 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` 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-1.0.12/elasticsearch-api/utils/thor/lister.rb000066400000000000000000000017771253341257200247300ustar00rootroot00000000000000# 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-1.0.12/elasticsearch-api/utils/thor/templates/000077500000000000000000000000001253341257200250635ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/utils/thor/templates/ruby/000077500000000000000000000000001253341257200260445ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-api/utils/thor/templates/ruby/method.erb000066400000000000000000000067021253341257200300230ustar00rootroot00000000000000module Elasticsearch module API <%- @module_namespace.each_with_index do |name, i| -%> <%= ' '*i %>module <%= 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['required'] ? ' (*Required*)' : '' ) -%><%= " (options: #{info['options'].join(', ')})" if info['options'] -%> <%= "\n" -%> <%- end -%> <%# Body -%> <%= ' '*(@namespace_depth+3) + '# @option arguments [Hash] :body ' + (@spec['body']['description'] || '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']}" -%><%= " (options: #{info['options'].join(', ')})" if info['options'] -%> <%= "\n" -%> <%- end if @spec['url']['parts'] -%> <%= ' '*@namespace_depth -%># <%# Documentation link -%> <%= ' '*@namespace_depth %># @see <%= @spec['documentation'] %> <%= ' '*@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 %> valid_params = [ <%= ' '*(@namespace_depth+2) %><%= @spec['url']['params'].keys.map { |k| ":#{k}" }.join(",\n#{' '*(@namespace_depth+5)}") %> ] <%= ' '*@namespace_depth %> method = '<%= @spec['methods'].first %>' <%- unless @spec['url']['parts'].empty? -%> <%= ' '*@namespace_depth %> path = "<%= @spec['url']['path'].split('/').compact.reject {|p| p =~ /^\s*$/}.map do |p| p =~ /\{/ ? "\#\{arguments[:#{p.tr('{}', '')}]\}" : p end.join('/') %>" <%- else -%> <%= ' '*@namespace_depth %> path = "<%= @spec['url']['path'] %>" <%- end -%> <%- unless @spec['url']['params'].keys.empty? -%> <%= ' '*@namespace_depth %> params = Utils.__validate_and_extract_params arguments, valid_params <%- 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 -%> end end end elasticsearch-ruby-1.0.12/elasticsearch-api/utils/thor/templates/ruby/test.erb000066400000000000000000000015671253341257200275260ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class <%= @module_namespace.empty? ? @method_name.camelize : @module_namespace.map {|n| n.capitalize}.join + @method_name.camelize %>Test < ::Test::Unit::TestCase context "<%= @module_namespace.empty? ? '' : @module_namespace.map {|n| n.capitalize}.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('.') %> end end end end end elasticsearch-ruby-1.0.12/elasticsearch-api/utils/thor/templates/ruby/test_helper.rb000066400000000000000000000034201253341257200307060ustar00rootroot00000000000000RUBY_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-1.0.12/elasticsearch-dsl/000077500000000000000000000000001253341257200207625ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/.gitignore000066400000000000000000000002321253341257200227470ustar00rootroot00000000000000*.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-1.0.12/elasticsearch-dsl/Gemfile000066400000000000000000000015661253341257200222650ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-dsl.gemspec gemspec if File.exists? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-transport", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => true end if File.exists? File.expand_path("../../elasticsearch-api", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end elasticsearch-ruby-1.0.12/elasticsearch-dsl/LICENSE.txt000066400000000000000000000010561253341257200226070ustar00rootroot00000000000000Copyright (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-1.0.12/elasticsearch-dsl/README.md000066400000000000000000000200161253341257200222400ustar00rootroot00000000000000# 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 would look like this: ```ruby require 'awesome_print' require 'elasticsearch' require 'elasticsearch/dsl' include Elasticsearch::DSL client = Elasticsearch::Client.new transport_options: { request: { timeout: 3600, open_timeout: 3600 } } # Restore an index from a snapshot # client.indices.delete index: 'bicycles.stackexchange.com', ignore: 404 puts "Recovering the 'bicycles.stackexchange.com' index...".gray 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.status(index: 'bicycles.stackexchange.com', human: true, recovery: true)['indices']['bicycles.stackexchange.com']['shards']['0'][0] print "\r#{r['index']['size']} of #{r['gateway_recovery']['index']['expected_recovered_size']}".ljust(52).gray sleep 1 end # 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 a (slightly normalized) document rating # functions << { script_score: { script: '_score * log10( doc["rating"].value )' } } end end # Calculate the most frequently used tags # aggregation :tags do terms do field 'tags' end end # Calculate the posting frequency # aggregation :frequency do date_histogram do field 'creation_date' interval 'month' format 'yyyy-MM' 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".gray 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".gray 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-1.0.12/elasticsearch-dsl/Rakefile000066400000000000000000000154371253341257200224410ustar00rootroot00000000000000require "bundler/gem_tasks" task(:default) { system "rake --tasks" } 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 = true # test.warning = true end Rake::TestTask.new(:integration) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/**/*_test.rb"] 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 --------------------------------------------------- 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 < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/elasticsearch-dsl.gemspec000066400000000000000000000030201253341257200257140ustar00rootroot00000000000000# 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" 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.add_development_dependency "bundler", "~> 1.3" s.add_development_dependency "rake" 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', '~> 4.0' s.add_development_dependency 'minitest-reporters' s.add_development_dependency 'simplecov' s.add_development_dependency 'simplecov-rcov' s.add_development_dependency 'ci_reporter', '~> 1.9' s.add_development_dependency 'yard' s.add_development_dependency 'cane' s.add_development_dependency 'pry' end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/000077500000000000000000000000001253341257200215305ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch-dsl.rb000066400000000000000000000000341253341257200254440ustar00rootroot00000000000000require 'elasticsearch/dsl' elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/000077500000000000000000000000001253341257200243425ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl.rb000066400000000000000000000027311253341257200254540ustar00rootroot00000000000000require '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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/000077500000000000000000000000001253341257200251245ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search.rb000066400000000000000000000142761253341257200267300ustar00rootroot00000000000000module 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 # # @example Using the class imperatively # # definition = Search.new # query = Query.new # 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 instance_eval(&block) 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 ||= {} 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 `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(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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/000077500000000000000000000000001253341257200263715ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregation.rb000066400000000000000000000037111253341257200312070ustar00rootroot00000000000000module Elasticsearch module DSL module Search # Contains the classes for Elasticsearch aggregations # module Aggregations;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 a nested aggregation # 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/000077500000000000000000000000001253341257200310435ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/avg.rb000066400000000000000000000011161253341257200321440ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/cardinality.rb000066400000000000000000000014611253341257200336750ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/children.rb000066400000000000000000000021451253341257200331620ustar00rootroot00000000000000module 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.rb000066400000000000000000000021451253341257200343050ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/date_range.rb000066400000000000000000000016641253341257200334700ustar00rootroot00000000000000module 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.rb000066400000000000000000000012141253341257200343250ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/filter.rb000066400000000000000000000014461253341257200326620ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/filters.rb000066400000000000000000000017171253341257200330460ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/geo_bounds.rb000066400000000000000000000022071253341257200335150ustar00rootroot00000000000000module 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 geo_distance.rb000066400000000000000000000020721253341257200337360ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule 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 geohash_grid.rb000066400000000000000000000015611253341257200337370ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregationsmodule 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/global.rb000066400000000000000000000010711253341257200326270ustar00rootroot00000000000000module 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 # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-global-aggregation.html # class Global include BaseComponent end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/histogram.rb000066400000000000000000000016011253341257200333630ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/ip_range.rb000066400000000000000000000014311253341257200331530ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/max.rb000066400000000000000000000011261253341257200321550ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/min.rb000066400000000000000000000011261253341257200321530ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/nested.rb000066400000000000000000000015211253341257200326510ustar00rootroot00000000000000module 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.rb000066400000000000000000000015751253341257200346510ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/percentiles.rb000066400000000000000000000015061253341257200337070ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/range.rb000066400000000000000000000027701253341257200324720ustar00rootroot00000000000000module 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 def key(key, value) @hash[name].update(@args) if @args @hash[name][:keyed] ||= true @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.rb000066400000000000000000000017551253341257200343360ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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.rb000066400000000000000000000023631253341257200344750ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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.rb000066400000000000000000000023371253341257200350260ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/stats.rb000066400000000000000000000011421253341257200325240ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-value metrics aggregation which returns statistical information on numeric values # # @example # # search do # aggregation :clicks_stats do # stats field: 'clicks' # end # end # # @see http://elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-stats-aggregation.html # class Stats include BaseComponent end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/sum.rb000066400000000000000000000011121253341257200321670ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/terms.rb000066400000000000000000000015521253341257200325250ustar00rootroot00000000000000module Elasticsearch module DSL module Search module Aggregations # A multi-bucket aggregation which returns the collection of terms and their document counts # # @example # # aggregation :tags do # terms field: 'tags' # end # # @see http://elasticsearch.org/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/top_hits.rb000066400000000000000000000016041253341257200332220ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/aggregations/value_count.rb000066400000000000000000000011661253341257200337200ustar00rootroot00000000000000module 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.rb000066400000000000000000000034061253341257200342050ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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 ||= {} @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.map { |name, value| @hash[:aggregations][name] = value.to_hash } end @hash end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/base_component.rb000066400000000000000000000123241253341257200317140ustar00rootroot00000000000000module 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) 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 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.rb000066400000000000000000000050351253341257200351070ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filter.rb000066400000000000000000000026301253341257200302040ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/000077500000000000000000000000001253341257200300415ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/and.rb000066400000000000000000000023741253341257200311360ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/bool.rb000066400000000000000000000044021253341257200313210ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/exists.rb000066400000000000000000000013671253341257200317140ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_bounding_box.rb000066400000000000000000000024021253341257200336730ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_distance.rb000066400000000000000000000034641253341257200330210ustar00rootroot00000000000000module 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.rb000066400000000000000000000014441253341257200341120ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_polygon.rb000066400000000000000000000021311253341257200327040ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geo_shape.rb000066400000000000000000000016311253341257200323210ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/geohash_cell.rb000066400000000000000000000030171253341257200330040ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/has_child.rb000066400000000000000000000040661253341257200323120ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/has_parent.rb000066400000000000000000000040371253341257200325160ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/ids.rb000066400000000000000000000012751253341257200311520ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/indices.rb000066400000000000000000000043121253341257200320040ustar00rootroot00000000000000module 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: _filter) end hash end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/limit.rb000066400000000000000000000012331253341257200315030ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/match_all.rb000066400000000000000000000011551253341257200323140ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/missing.rb000066400000000000000000000014741253341257200320450ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/nested.rb000066400000000000000000000027171253341257200316570ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/not.rb000066400000000000000000000041011253341257200311620ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/or.rb000066400000000000000000000023561253341257200310140ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/prefix.rb000066400000000000000000000012261253341257200316640ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/query.rb000066400000000000000000000024661253341257200315430ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/range.rb000066400000000000000000000016251253341257200314660ustar00rootroot00000000000000module 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 end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/regexp.rb000066400000000000000000000014241253341257200316610ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/script.rb000066400000000000000000000013561253341257200316770ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/term.rb000066400000000000000000000014251253341257200313370ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/terms.rb000066400000000000000000000014731253341257200315250ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/filters/type.rb000066400000000000000000000013371253341257200313530ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/highlight.rb000066400000000000000000000045321253341257200306710ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/options.rb000066400000000000000000000023461253341257200304160ustar00rootroot00000000000000module 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) super @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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/000077500000000000000000000000001253341257200300465ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/bool.rb000066400000000000000000000041251253341257200313300ustar00rootroot00000000000000module 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 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 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/boosting.rb000066400000000000000000000015161253341257200322220ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/common.rb000066400000000000000000000020451253341257200316640ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/constant_score.rb000066400000000000000000000033601253341257200334210ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/dis_max.rb000066400000000000000000000016061253341257200320220ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/filtered.rb000066400000000000000000000042711253341257200321750ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/function_score.rb000066400000000000000000000056671253341257200334310ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/fuzzy.rb000066400000000000000000000021161253341257200315620ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/fuzzy_like_this.rb000066400000000000000000000016761253341257200336270ustar00rootroot00000000000000module 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.rb000066400000000000000000000016451253341257200347070ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/geo_shape.rb000066400000000000000000000014411253341257200323250ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/has_child.rb000066400000000000000000000027421253341257200323160ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/has_parent.rb000066400000000000000000000026731253341257200325270ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/ids.rb000066400000000000000000000011151253341257200311500ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/indices.rb000066400000000000000000000016321253341257200320130ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/match.rb000066400000000000000000000016241253341257200314720ustar00rootroot00000000000000module 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 :type option_method :boost end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/match_all.rb000066400000000000000000000010321253341257200323130ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/more_like_this.rb000066400000000000000000000032131253341257200333670ustar00rootroot00000000000000module 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_text '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 # ids [1, 2, 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 option_method :fields option_method :like_text option_method :min_term_freq option_method :max_query_terms option_method :docs option_method :ids 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/multi_match.rb000066400000000000000000000023361253341257200327050ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/nested.rb000066400000000000000000000026311253341257200316570ustar00rootroot00000000000000module 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 # 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/prefix.rb000066400000000000000000000011511253341257200316660ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/query_string.rb000066400000000000000000000031341253341257200331270ustar00rootroot00000000000000module 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 :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 end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/range.rb000066400000000000000000000022121253341257200314640ustar00rootroot00000000000000module 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 end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/regexp.rb000066400000000000000000000012571253341257200316720ustar00rootroot00000000000000module 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.rb000066400000000000000000000020071253341257200344170ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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 :lowercase_expanded_terms option_method :locale option_method :lenient end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_first.rb000066400000000000000000000013421253341257200325430ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_multi.rb000066400000000000000000000013251253341257200325470ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_near.rb000066400000000000000000000016101253341257200323370ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_not.rb000066400000000000000000000016311253341257200322150ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_or.rb000066400000000000000000000013701253341257200320350ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/span_term.rb000066400000000000000000000012211253341257200323570ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/template.rb000066400000000000000000000013411253341257200322050ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/term.rb000066400000000000000000000011621253341257200313420ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/terms.rb000066400000000000000000000012101253341257200315170ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/top_children.rb000066400000000000000000000030441253341257200330460ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/queries/wildcard.rb000066400000000000000000000012601253341257200321630ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/query.rb000066400000000000000000000025731253341257200300720ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/sort.rb000066400000000000000000000020361253341257200277060ustar00rootroot00000000000000module 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 else @value << @args if @args end @hash = @value.flatten @hash end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/search/suggest.rb000066400000000000000000000011331253341257200303750ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/utils.rb000066400000000000000000000007121253341257200266110ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-dsl/lib/elasticsearch/dsl/version.rb000066400000000000000000000001021253341257200271270ustar00rootroot00000000000000module Elasticsearch module DSL VERSION = "0.1.0" end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/000077500000000000000000000000001253341257200217415ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/integration/000077500000000000000000000000001253341257200242645ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/integration/search_aggregation_children_test.rb000066400000000000000000000054561253341257200333460ustar00rootroot00000000000000require '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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end setup do @client.indices.create index: 'articles-test', body: { mappings: { article: {}, comment: { _routing: { required: true }, _parent: { type: 'article' }, properties: { author: { type: 'string', analyzer: 'keyword' } } } } } @client.index index: 'articles-test', type: 'article', id: 1, body: { title: 'A', category: 'one' } @client.index index: 'articles-test', type: 'article', id: 2, body: { title: 'B', category: 'one' } @client.index index: 'articles-test', type: 'article', id: 3, body: { title: 'C', category: 'two' } @client.index index: 'articles-test', type: 'comment', parent: '1', body: { author: 'John' } @client.index index: 'articles-test', type: 'comment', parent: '1', body: { author: 'Mary' } @client.index index: 'articles-test', type: 'comment', parent: '2', body: { author: 'John' } @client.index index: 'articles-test', type: 'comment', parent: '2', body: { author: 'Dave' } @client.index index: 'articles-test', type: 'comment', parent: '3', body: { author: 'Ruth' } @client.indices.refresh index: 'articles-test' end should "return the top commenters per article category" do response = @client.search index: 'articles-test', 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-1.0.12/elasticsearch-dsl/test/integration/search_aggregation_geo_test.rb000066400000000000000000000067141253341257200323260ustar00rootroot00000000000000require '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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end setup do @client.indices.create index: 'venues-test', body: { mappings: { venue: { properties: { location: { type: 'geo_point', normalize: false, validate: true } } } } } @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-1.0.12/elasticsearch-dsl/test/integration/search_aggregation_nested_test.rb000066400000000000000000000070261253341257200330330ustar00rootroot00000000000000require '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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end setup do @client.indices.create index: 'products-test', body: { mappings: { product: { properties: { offers: { type: 'nested', properties: { name: { type: 'string' }, 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 filtered do filter do nested do path 'offers' filter do range 'offers.price' do gte 100 lte 300 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-1.0.12/elasticsearch-dsl/test/integration/search_aggregations_test.rb000066400000000000000000000213071253341257200316520ustar00rootroot00000000000000require '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' @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" 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 "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 "_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 }.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-1.0.12/elasticsearch-dsl/test/integration/search_filters_test.rb000066400000000000000000000274371253341257200306620ustar00rootroot00000000000000# 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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? 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 filtered 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 filtered do filter do terms color: ['red', 'grey', 'gold'] end end end }.to_hash assert_equal 7, response['hits']['total'] end end context "and/or/not filters" do should "find the document with and as a Hash" do response = @client.search index: 'test', body: search { query do filtered do filter do _and filters: [ { term: { color: 'red' } }, { term: { size: 'xxl' } } ] end end end }.to_hash assert_equal 1, response['hits']['total'] end should "find the document with and as a block" do response = @client.search index: 'test', body: search { query do filtered do filter do _and do term color: 'red' term size: 'xxl' end end end end }.to_hash assert_equal 1, response['hits']['total'] end should "find the documents with or" do response = @client.search index: 'test', body: search { query do filtered do filter do _or do term size: 'l' term size: 'm' end end end end }.to_hash assert_equal 3, response['hits']['total'] assert response['hits']['hits'].all? { |h| ['l', 'm'].include? h['_source']['size'] } end should "find the documents with not as a Hash" do response = @client.search index: 'test', body: search { query do filtered do filter do _not term: { size: 'xxl' } end end end }.to_hash assert_equal 6, response['hits']['total'] assert response['hits']['hits'].none? { |h| h['_source']['size'] == 'xxl' } end should "find the documents with not as a block" do response = @client.search index: 'test', body: search { query do filtered do filter do _not do term size: 'xxl' end end end end }.to_hash assert_equal 6, response['hits']['total'] assert response['hits']['hits'].none? { |h| h['_source']['size'] == 'xxl' } end end context "bool filter" do should "return correct documents" do response = @client.search index: 'test', body: search { query do filtered 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', geohash: true, geohash_prefix: true, geohash_precision: 6 } } } } } @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 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 }.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 filtered 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 filtered 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 filtered do filter do geo_distance_range location: { lat: '50.090223', lon: '14.399590' }, gte: '10km', lte: '50km' end end end }.to_hash assert_equal 1, response['hits']['hits'].size assert_equal 'Karlštejn', response['hits']['hits'][0]['_source']['name'] end should "find documents within the polygon" do response = @client.search index: 'places', body: search { 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 }.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 geohash cell" do response = @client.search index: 'places', body: search { query do filtered do filter do geohash_cell :location do lat '50.090223' lon '14.399590' precision '10km' neighbors true 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-1.0.12/elasticsearch-dsl/test/integration/search_options_test.rb000066400000000000000000000015411253341257200306710ustar00rootroot00000000000000require '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-1.0.12/elasticsearch-dsl/test/integration/search_query_test.rb000066400000000000000000000034411253341257200303440ustar00rootroot00000000000000require '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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? 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 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 end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/integration/search_size_from_test.rb000066400000000000000000000025521253341257200311760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SizeIntegrationTest < ::Elasticsearch::Test::IntegrationTestCase include Elasticsearch::DSL::Search context "Search results pagination" do setup do 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' and type 'phrase_prefix' } } size 5 from 5 sort { by :title } }.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-1.0.12/elasticsearch-dsl/test/integration/search_sort_test.rb000066400000000000000000000023131253341257200301630ustar00rootroot00000000000000require '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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end setup do @client.indices.create index: 'test' @client.index index: 'test', type: 'd', id: '1', body: { tags: ['one'], clicks: 5 } @client.index index: 'test', type: 'd', id: '2', body: { tags: ['one', 'two'], clicks: 15 } @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', '2', '1'], response['hits']['hits'].map { |d| d['_id'] } end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/integration/search_suggest_test.rb000066400000000000000000000040601253341257200306560ustar00rootroot00000000000000# 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(nodes: 1) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end setup do @client.indices.create index: 'test', body: { mappings: { d: { properties: { title: { type: 'string' }, title_suggest: { type: 'completion', payloads: true } } } } } @client.index index: 'test', type: 'd', id: '1', body: { title: 'One', title_suggest: { input: ['one', 'uno', 'jedna'] }, output: 'ONE', payload: { id: '1' } } @client.index index: 'test', type: 'd', id: '2', body: { title: 'Two', title_suggest: { input: ['two', 'due', 'dvě'] }, output: 'TWO', payload: { id: '2' } } @client.index index: 'test', type: 'd', id: '3', body: { title: 'Three', title_suggest: { input: ['three', 'tres', 'tři'] }, output: 'THREE', payload: { id: '3' } } @client.indices.refresh index: 'test' end should "return suggestions" do s = search do suggest :title, text: 't', completion: { field: 'title_suggest' } end response = @client.search index: 'test', body: s.to_hash assert_equal 4, response['suggest']['title'][0]['options'].size end should "return a single suggestion" do s = search do suggest :title, text: 'th', completion: { field: 'title_suggest' } end response = @client.search index: 'test', body: s.to_hash assert_equal 1, response['suggest']['title'][0]['options'].size end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/test_helper.rb000066400000000000000000000032671253341257200246140ustar00rootroot00000000000000JRUBY = defined?(JRUBY_VERSION) if ENV['COVERAGE'] || ENV['CI'] require 'simplecov' SimpleCov.start { add_filter "/test|test_" } end at_exit { Elasticsearch::Test::IntegrationTestCase.__run_at_exit_hooks } require 'test/unit' require 'shoulda-context' require 'mocha/setup' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require 'elasticsearch' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/dsl' module Elasticsearch module Test class IntegrationTestCase < ::Test::Unit::TestCase include Elasticsearch::Extensions::Test extend StartupShutdown startup do Cluster.start(nodes: 1) if ENV['SERVER'] \ && ! Elasticsearch::Extensions::Test::Cluster.running? end shutdown do Cluster.stop if ENV['SERVER'] \ && started? \ && Elasticsearch::Extensions::Test::Cluster.running? end def setup @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i @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: "localhost:#{@port}", logger: @logger end def teardown @client.indices.delete index: '_all' end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/000077500000000000000000000000001253341257200227205ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/000077500000000000000000000000001253341257200253725ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/avg_test.rb000066400000000000000000000010541253341257200275330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class AvgTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Avg agg" do subject { Avg.new } should "be converted to a Hash" do assert_equal({ avg: {} }, subject.to_hash) end should "take a Hash" do subject = Avg.new foo: 'bar' assert_equal({ avg: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/cardinality_test.rb000066400000000000000000000023141253341257200312610ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class CardinalityTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Cardinality agg" do subject { Cardinality.new } should "be converted to a Hash" do assert_equal({ cardinality: {} }, subject.to_hash) end should "have option methods" do subject = Cardinality.new :foo subject.field 'bar' subject.precision_threshold 'bar' subject.rehash 'bar' subject.script 'bar' subject.params 'bar' assert_equal %w[ field params precision_threshold rehash script ], subject.to_hash[:cardinality][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:cardinality][:foo][:field] end should "take a block" do subject = Cardinality.new :foo do field 'bar' end assert_equal({cardinality: { foo: { field: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/children_test.rb000066400000000000000000000016421253341257200305510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class ChildrenTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Children aggregation" do subject { Children.new } should "be converted to a Hash" do assert_equal({ children: {} }, subject.to_hash) end should "have option methods" do subject = Children.new subject.type 'bar' assert_equal %w[ type ], subject.to_hash[:children].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:children][:type] end should "take a block" do subject = Children.new do type 'bar' end assert_equal({children: { type: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/date_histogram_test.rb000066400000000000000000000031571253341257200317560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class DateHistogramTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "DateHistogram aggregation" do subject { DateHistogram.new } should "be converted to a Hash" do assert_equal({ date_histogram: {} }, subject.to_hash) end should "have option methods" do subject = DateHistogram.new subject.field 'bar' subject.interval 'bar' subject.pre_zone 'bar' subject.post_zone 'bar' subject.time_zone 'bar' subject.pre_zone_adjust_large_interval 'bar' subject.pre_offset 'bar' subject.post_offset 'bar' subject.format 'bar' subject.min_doc_count 'bar' subject.extended_bounds 'bar' subject.order 'bar' assert_equal %w[ extended_bounds field format interval min_doc_count order post_offset post_zone pre_offset pre_zone pre_zone_adjust_large_interval time_zone ], subject.to_hash[:date_histogram].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:date_histogram][:field] end should "take a block" do subject = DateHistogram.new do field 'bar' interval 'day' format 'yyyy-MM-dd' end assert_equal({date_histogram: { field: 'bar', interval: 'day', format: 'yyyy-MM-dd' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/date_range_test.rb000066400000000000000000000024601253341257200310510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class DateRangeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "DateRange aggregation" do subject { DateRange.new } should "be converted to a Hash" do assert_equal({ date_range: {} }, subject.to_hash) subject = DateRange.new field: 'test', ranges: [ {to: 'foo'}, {from: 'bar'} ] assert_equal({ date_range: { field: 'test', ranges: [ {to: 'foo'}, {from: 'bar'} ] } }, subject.to_hash) end should "have option methods" do subject = DateRange.new subject.field 'bar' subject.format 'bar' subject.ranges 'bar' assert_equal %w[ field format ranges ], subject.to_hash[:date_range].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:date_range][:field] end should "take a block" do subject = DateRange.new do field 'bar' ranges [ {to: 'foo'}, {from: 'bar'} ] end assert_equal({date_range: { field: 'bar', ranges: [ {to: 'foo'}, {from: 'bar'} ] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/extended_stats_test.rb000066400000000000000000000011521253341257200317730ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class ExtendedStatsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "ExtendedStats agg" do subject { ExtendedStats.new } should "be converted to a Hash" do assert_equal({ extended_stats: {} }, subject.to_hash) end should "take a Hash" do subject = ExtendedStats.new foo: 'bar' assert_equal({ extended_stats: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/filter_test.rb000066400000000000000000000014431253341257200302450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class FilterTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Filter agg" do subject { Filter.new } should "be converted to a Hash" do assert_equal({ filter: {} }, subject.to_hash) end should "nest another aggregation" do subject = Filter.new terms: { foo: 'bar' } do aggregation :sum_clicks do sum moo: 'bam' end end assert_equal( { filter: { terms: { foo: 'bar' } }, aggregations: { sum_clicks: { sum: { moo: 'bam' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/filters_test.rb000066400000000000000000000032461253341257200304330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class FiltersTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Filters agg" do subject { Elasticsearch::DSL::Search::Aggregations::Filters.new } should "be converted to a Hash" do assert_equal({ filters: {} }, subject.to_hash) end should "have option methods" do subject = Elasticsearch::DSL::Search::Aggregations::Filters.new subject.filters foo: 'bar' assert_equal 'bar', subject.to_hash[:filters][:filters][:foo] end should "define filters" do subject = Elasticsearch::DSL::Search::Aggregations::Filters.new filters: { foo: 'bar' } assert_equal({ filters: { filters: { foo: 'bar' } } }, subject.to_hash) end should "define filters with a block" do subject = Elasticsearch::DSL::Search::Aggregations::Filters.new do filters foo: 'bar' end assert_equal({ filters: { filters: { foo: 'bar' } } }, subject.to_hash) end should "define aggregations" do subject = Elasticsearch::DSL::Search::Aggregations::Filters.new do filters foo: { terms: { foo: 'bar' } } aggregation :sum_clicks do sum moo: 'bam' end end assert_equal( { filters: { filters: { foo: { terms: { foo: 'bar' } } } }, aggregations: { sum_clicks: { sum: { moo: 'bam' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/geo_bounds_test.rb000066400000000000000000000017441253341257200311100ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class GeoBoundsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "GeoBounds agg" do subject { GeoBounds.new } should "be converted to a Hash" do assert_equal({ geo_bounds: {} }, subject.to_hash) end should "have option methods" do subject = GeoBounds.new subject.field 'bar' subject.wrap_longitude 'bar' assert_equal %w[ field wrap_longitude ], subject.to_hash[:geo_bounds].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_bounds][:field] end should "take a block" do subject = GeoBounds.new do field 'bar' end assert_equal({geo_bounds: { field: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/geo_distance_test.rb000066400000000000000000000025461253341257200314110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class GeoDistanceTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "GeoDistance aggregation" do subject { GeoDistance.new } should "be converted to a Hash" do assert_equal({ geo_distance: {} }, subject.to_hash) end should "have option methods" do subject = GeoDistance.new subject.field 'bar' subject.origin 'bar' subject.ranges 'bar' subject.unit 'bar' subject.distance_type 'bar' assert_equal %w[ distance_type field origin ranges unit ], subject.to_hash[:geo_distance].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_distance][:field] end should "take a block" do subject = GeoDistance.new do field 'bar' origin lat: 50, lon: 5 ranges [ { to: 50 }, { from: 50, to: 100 }, { from: 100 } ] end assert_equal( { geo_distance: { field: 'bar', origin: { lat: 50, lon: 5 }, ranges: [ { to: 50 }, { from: 50, to: 100 }, { from: 100 } ] } }, subject.to_hash ) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/geohash_grid_test.rb000066400000000000000000000021641253341257200314040ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class GeohashGridTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "GeohashGrid aggregation" do subject { GeohashGrid.new } should "be converted to a Hash" do assert_equal({ geohash_grid: {} }, subject.to_hash) end should "have option methods" do subject = GeohashGrid.new subject.field 'bar' subject.precision 'bar' subject.size 'bar' subject.shard_size 'bar' assert_equal %w[ field precision shard_size size ], subject.to_hash[:geohash_grid].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geohash_grid][:field] end should "take a block" do subject = GeohashGrid.new do field 'bar' precision 5 end assert_equal({geohash_grid: { field: 'bar', precision: 5 } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/global_test.rb000066400000000000000000000006461253341257200302240ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class GlobalTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Global agg" do subject { Global.new } should "be converted to a Hash" do assert_equal({ global: {} }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/histogram_test.rb000066400000000000000000000023011253341257200307470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class HistogramTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Histogram aggregation" do subject { Histogram.new } should "be converted to a Hash" do assert_equal({ histogram: {} }, subject.to_hash) end should "have option methods" do subject = Histogram.new subject.field 'bar' subject.interval 'bar' subject.min_doc_count 'bar' subject.extended_bounds 'bar' subject.order 'bar' subject.keyed 'bar' assert_equal %w[ extended_bounds field interval keyed min_doc_count order ], subject.to_hash[:histogram].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:histogram][:field] end should "take a block" do subject = Histogram.new do field 'bar' interval 5 end assert_equal({histogram: { field: 'bar', interval: 5 } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/ip_range_test.rb000066400000000000000000000023621253341257200305450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class IpRangeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "IpRange aggregation" do subject { IpRange.new } should "be converted to a Hash" do assert_equal({ ip_range: {} }, subject.to_hash) subject = IpRange.new field: 'test', ranges: [ {to: 'foo'}, {from: 'bar'} ] assert_equal({ ip_range: { field: 'test', ranges: [ {to: 'foo'}, {from: 'bar'} ] } }, subject.to_hash) end should "have option methods" do subject = IpRange.new subject.field 'bar' subject.ranges 'bar' assert_equal %w[ field ranges ], subject.to_hash[:ip_range].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:ip_range][:field] end should "take a block" do subject = IpRange.new do field 'bar' ranges [ {to: 'foo'}, {from: 'bar'} ] end assert_equal({ip_range: { field: 'bar', ranges: [ {to: 'foo'}, {from: 'bar'} ] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/max_test.rb000066400000000000000000000010541253341257200275430ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class MaxTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Max agg" do subject { Max.new } should "be converted to a Hash" do assert_equal({ max: {} }, subject.to_hash) end should "take a Hash" do subject = Max.new foo: 'bar' assert_equal({ max: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/min_test.rb000066400000000000000000000010541253341257200275410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class MinTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Min agg" do subject { Min.new } should "be converted to a Hash" do assert_equal({ min: {} }, subject.to_hash) end should "take a Hash" do subject = Min.new foo: 'bar' assert_equal({ min: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/nested_test.rb000066400000000000000000000023611253341257200302420ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class NestedTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Nested aggregation" do subject { Nested.new } should "be converted to a Hash" do assert_equal({ nested: {} }, subject.to_hash) end should "have option methods" do subject = Nested.new subject.path 'bar' assert_equal %w[ path ], subject.to_hash[:nested].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:nested][:path] end should "take a block" do subject = Nested.new do path 'bar' end assert_equal({nested: { path: 'bar' } }, subject.to_hash) end should "define aggregations" do subject = Nested.new do path 'bar' aggregation :min_price do min field: 'bam' end end assert_equal({nested: { path: 'bar' }, aggregations: { min_price: { min: { field: 'bam' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/percentile_ranks_test.rb000066400000000000000000000022721253341257200323110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class PercentileRanksTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "PercentileRanks agg" do subject { PercentileRanks.new } should "be converted to a Hash" do assert_equal({ percentile_ranks: {} }, subject.to_hash) end should "have option methods" do subject = PercentileRanks.new subject.field 'bar' subject.values 'bar' subject.script 'bar' subject.params 'bar' subject.compression 'bar' assert_equal %w[ compression field params script values ], subject.to_hash[:percentile_ranks].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:percentile_ranks][:field] end should "take a block" do subject = PercentileRanks.new do field 'bar' values [5, 10] end assert_equal({percentile_ranks: { field: 'bar', values: [5, 10] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/percentiles_test.rb000066400000000000000000000021501253341257200312710ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class PercentilesTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Percentiles agg" do subject { Percentiles.new } should "be converted to a Hash" do assert_equal({ percentiles: {} }, subject.to_hash) end should "have option methods" do subject = Percentiles.new subject.field 'bar' subject.percents 'bar' subject.script 'bar' subject.params 'bar' subject.compression 'bar' assert_equal %w[ compression field params percents script ], subject.to_hash[:percentiles].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:percentiles][:field] end should "take a block" do subject = Percentiles.new do field 'bar' end assert_equal({percentiles: { field: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/range_test.rb000066400000000000000000000027651253341257200300640ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class RangeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Range aggregation" do should "take a Hash" do subject = Range.new( { field: 'test', ranges: [ { to: 50 } ] } ) assert_equal({ range: { field: "test", ranges: [ {to: 50} ] } }, subject.to_hash) end should "have option methods" do subject = Range.new subject.field 'foo' subject.script 'bar*2' assert_equal %w[ field script ], subject.to_hash[:range].keys.map(&:to_s).sort assert_equal 'foo', subject.to_hash[:range][:field] end should "take a block with keyed ranges" do subject = Range.new field: 'test' do key 'foo', to: 10 key 'bar', from: 10, to: 20 end assert_equal({ range: { field: "test", keyed: true, ranges: [ {to: 10, key: 'foo'}, { from: 10, to: 20, key: 'bar'}]}}, subject.to_hash) end should "define field in the block" do subject = Range.new do field 'test' key 'foo', to: 10 key 'bar', from: 10, to: 20 end assert_equal({ range: { field: "test", keyed: true, ranges: [ {to: 10, key: 'foo'}, { from: 10, to: 20, key: 'bar'}]}}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/reverse_nested_test.rb000066400000000000000000000007131253341257200317740ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class ReverseNestedTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "ReverseNested aggregation" do subject { ReverseNested.new } should "be converted to a Hash" do assert_equal({ reverse_nested: {} }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/scripted_metric_test.rb000066400000000000000000000023411253341257200321360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class ScriptedMetricTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "ScriptedMetric agg" do subject { ScriptedMetric.new } should "be converted to a Hash" do assert_equal({ scripted_metric: {} }, subject.to_hash) end should "have option methods" do subject = ScriptedMetric.new subject.init_script 'bar' subject.map_script 'bar' subject.combine_script 'bar' subject.reduce_script 'bar' subject.params 'bar' subject.lang 'bar' assert_equal %w[ combine_script init_script lang map_script params reduce_script ], subject.to_hash[:scripted_metric].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:scripted_metric][:init_script] end should "take a block" do subject = ScriptedMetric.new do init_script 'bar' end assert_equal({scripted_metric: { init_script: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/significant_terms_test.rb000066400000000000000000000027431253341257200324740ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class SignificantTermsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "SignificantTerms aggregation" do subject { SignificantTerms.new } should "be converted to a Hash" do assert_equal({ significant_terms: {} }, subject.to_hash) end should "have option methods" do subject = SignificantTerms.new subject.field 'bar' subject.size 'bar' subject.shard_size 'bar' subject.min_doc_count 'bar' subject.shard_min_doc_count 'bar' subject.include 'bar' subject.exclude 'bar' subject.background_filter 'bar' subject.mutual_information 'bar' subject.chi_square 'bar' subject.gnd 'bar' assert_equal %w[ background_filter chi_square exclude field gnd include min_doc_count mutual_information shard_min_doc_count shard_size size ], subject.to_hash[:significant_terms].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:significant_terms][:field] end should "take a block" do subject = SignificantTerms.new do field 'bar' end assert_equal({significant_terms: { field: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/stats_test.rb000066400000000000000000000010701253341257200301120ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class StatsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Stats agg" do subject { Stats.new } should "be converted to a Hash" do assert_equal({ stats: {} }, subject.to_hash) end should "take a Hash" do subject = Stats.new foo: 'bar' assert_equal({ stats: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/sum_test.rb000066400000000000000000000010541253341257200275620ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class SumTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Sum agg" do subject { Sum.new } should "be converted to a Hash" do assert_equal({ sum: {} }, subject.to_hash) end should "take a Hash" do subject = Sum.new foo: 'bar' assert_equal({ sum: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/terms_test.rb000066400000000000000000000026411253341257200301130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class TermsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "Terms aggregation" do subject { Terms.new } should "be converted to a Hash" do assert_equal({ terms: {} }, subject.to_hash) end should "have option methods" do subject = Terms.new subject.field 'bar' subject.size 'bar' subject.shard_size 'bar' subject.order 'bar' subject.min_doc_count 'bar' subject.shard_min_doc_count 'bar' subject.script 'bar' subject.include 'bar' subject.exclude 'bar' assert_equal %w[ exclude field include min_doc_count order script shard_min_doc_count shard_size size ], subject.to_hash[:terms].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:terms][:field] end should "take a Hash" do subject = Terms.new field: 'test' assert_equal({:terms=>{:field=>"test"}}, subject.to_hash) end should "take a block" do subject = Terms.new do field 'bar' end assert_equal({terms: { field: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/top_hits_test.rb000066400000000000000000000017351253341257200306150ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class TopHitsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "TopHits agg" do subject { TopHits.new } should "be converted to a Hash" do assert_equal({ top_hits: {} }, subject.to_hash) end should "have option methods" do subject = TopHits.new subject.from 'bar' subject.size 'bar' subject.sort 'bar' assert_equal %w[ from size sort ], subject.to_hash[:top_hits].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:top_hits][:from] end should "take a block" do subject = TopHits.new do from 'bar' end assert_equal({top_hits: { from: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/aggregations/value_count_test.rb000066400000000000000000000011301253341257200312750ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Aggregations class ValueCountTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Aggregations context "ValueCount agg" do subject { ValueCount.new } should "be converted to a Hash" do assert_equal({ value_count: {} }, subject.to_hash) end should "take a Hash" do subject = ValueCount.new foo: 'bar' assert_equal({ value_count: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/dsl_test.rb000066400000000000000000000007241253341257200250710ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class DSLTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/filters/000077500000000000000000000000001253341257200243705ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/and_test.rb000066400000000000000000000037241253341257200265240ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class AndTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "And filter" do subject { And.new } should "be converted to a Hash" do assert_equal({ and: {} }, subject.to_hash) end should "take a Hash" do subject = And.new filters: [ { term: { foo: 'bar' } } ] assert_equal({ and: { filters: [ { term: { foo: 'bar' } } ] } }, subject.to_hash) end should "take a block" do subject = And.new do term foo: 'bar' term moo: 'mam' end assert_equal({and: [ {term: { foo: 'bar'}}, {term: { moo: 'mam'}} ]}, subject.to_hash) end should "behave like an Enumerable" do subject = And.new subject << { term: { foo: 'bar' } } subject << { term: { moo: 'mam' } } assert_equal 2, subject.size assert_equal 'bar', subject[0][:term][:foo] assert subject.any? { |d| d[:term] == { foo: 'bar' } } end should "behave like an Enumerable with a block" do subject = And.new do term foo: 'bar' term moo: 'mam' end subject.call assert_equal 2, subject.size hash = subject.to_hash assert_equal 'bar', hash[:and][0][:term][:foo] assert hash[:and].any? { |d| d[:term] == { foo: 'bar' } } end should "behave like an Array" do subject = And.new assert subject.empty? subject << { term: { foo: 'bar' } } subject << { term: { moo: 'xam' } } assert ! subject.empty? assert_equal({ and: [ { term: { foo: 'bar' } }, { term: { moo: 'xam' } } ] }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/bool_test.rb000066400000000000000000000062761253341257200267220ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class BoolTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Bool Filter" do subject { Bool.new } should "be converted to a Hash" do assert_equal({ bool: {} }, subject.to_hash) end should "take a Hash" do subject = Bool.new must: [ {term: { foo: 'bar' } } ] assert_equal( { bool: { must: [ {term: { foo: 'bar' } } ] } }, subject.to_hash ) end should "take a block" do subject = Bool.new do must { term foo: 'bar' } end assert_equal( { bool: { must: [ {term: { foo: 'bar' }} ] } }, subject.to_hash ) end should "take a block with multiple methods" do subject = Bool.new do must { term foo: 'bar' } must_not { term moo: 'bam' } should { term xoo: 'bax' } end assert_equal( { bool: { must: [ {term: { foo: 'bar' }} ], must_not: [ {term: { moo: 'bam' }} ], should: [ {term: { xoo: 'bax' }} ] } }, subject.to_hash ) end should "take a block with multiple conditions" do subject = Bool.new do must { term foo: 'bar' } must { term moo: 'bam' } should { term xoo: 'bax' } should { term zoo: 'baz' } end # Make sure we're not additive subject.to_hash subject.to_hash assert_equal( { bool: { must: [ {term: { foo: 'bar' }}, {term: { moo: 'bam' }} ], should: [ {term: { xoo: 'bax' }}, {term: { zoo: 'baz' }} ] } }, subject.to_hash ) end should "take method calls" do subject = Bool.new subject.must { term foo: 'bar' } assert_equal( { bool: { must: [ {term: { foo: 'bar' }} ] } }, subject.to_hash ) subject.must { term moo: 'bam' } assert_equal( { bool: { must: [ {term: { foo: 'bar' }}, {term: { moo: 'bam' }} ]} }, subject.to_hash ) subject.should { term xoo: 'bax' } assert_equal( { bool: { must: [ {term: { foo: 'bar' }}, {term: { moo: 'bam' }} ], should: [ {term: { xoo: 'bax' }} ] } }, subject.to_hash ) end should "be chainable" do subject = Bool.new assert_instance_of Bool, subject.must { term foo: 'bar' } assert_instance_of Bool, subject.must { term foo: 'bar' }.must { term moo: 'bam' } assert_instance_of Bool, subject.must_not { term foo: 'bar' } assert_instance_of Bool, subject.should { term foo: 'bar' } end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/exists_test.rb000066400000000000000000000016071253341257200272770ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class ExistsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Exists filter" do subject { Exists.new } should "be converted to a Hash" do assert_equal({ exists: {} }, subject.to_hash) end should "have option methods" do subject = Exists.new subject.field 'bar' assert_equal %w[ field ], subject.to_hash[:exists].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:exists][:field] end should "take a block" do subject = Exists.new do field 'bar' end assert_equal({ exists: { field: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/geo_bounding_box_test.rb000066400000000000000000000026141253341257200312660ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class GeoBoundingBoxTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "GeoBoundingBox filter" do subject { GeoBoundingBox.new } should "be converted to a Hash" do assert_equal({ geo_bounding_box: {} }, subject.to_hash) end should "have option methods" do subject = GeoBoundingBox.new :foo subject.top_left 'bar' subject.bottom_right 'bar' subject.top_right 'bar' subject.bottom_left 'bar' subject.top 'bar' subject.left 'bar' subject.bottom 'bar' subject.right 'bar' assert_equal %w[ bottom bottom_left bottom_right left right top top_left top_right ], subject.to_hash[:geo_bounding_box][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_bounding_box][:foo][:top_left] end should "take a block" do subject = GeoBoundingBox.new :foo do top_left [0,1] bottom_right [3,2] end assert_equal({geo_bounding_box: { foo: { top_left: [0,1], bottom_right: [3,2] } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/geo_distance_range_test.rb000066400000000000000000000031701253341257200315550ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class GeoDistanceRangeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "GeoDistanceRange filter" do subject { GeoDistanceRange.new } should "be converted to a Hash" do assert_equal({ geo_distance_range: {} }, subject.to_hash) end should "have option methods" do subject = GeoDistanceRange.new :foo subject.lat 'bar' subject.lon 'bar' assert_equal %w[ lat lon ], subject.to_hash[:geo_distance_range][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_distance_range][:foo][:lat] end should "take a block" do subject = GeoDistanceRange.new :foo do lat 40 lon -70 end assert_equal({geo_distance_range: { foo: { lat: 40, lon: -70 } } }, subject.to_hash) end should "take a Hash" do subject = GeoDistanceRange.new from: '10km', to: '20km', foo: { lat: 40, lon: -70 } assert_equal({geo_distance_range: { foo: { lat: 40, lon: -70 }, from: '10km', to: '20km' }}, subject.to_hash) end should "take options" do subject = GeoDistanceRange.new :foo, from: '10km', to: '20km' do lat 40 lon -70 end assert_equal({geo_distance_range: { foo: { lat: 40, lon: -70 }, from: '10km', to: '20km' }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/geo_distance_test.rb000066400000000000000000000035351253341257200304060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class GeoDistanceTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "GeoDistance filter" do subject { GeoDistance.new } should "be converted to a Hash" do assert_equal({ geo_distance: {} }, subject.to_hash) end should "have option methods" do subject = GeoDistance.new :foo subject.distance 'bar' subject.distance_type 'bar' subject.lat 'bar' subject.lon 'bar' assert_equal %w[ distance distance_type foo ], subject.to_hash[:geo_distance].keys.map(&:to_s).sort assert_equal %w[ lat lon ], subject.to_hash[:geo_distance][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_distance][:distance] assert_equal 'bar', subject.to_hash[:geo_distance][:foo][:lat] end should "take a block" do subject = GeoDistance.new :foo do distance '1km' lat 40 lon -70 end assert_equal({geo_distance: { distance: '1km', foo: { lat: 40, lon: -70 } }}, subject.to_hash) end should "take a Hash" do subject = GeoDistance.new distance: '10km', foo: { lat: 40, lon: -70 } assert_equal({geo_distance: { foo: { lat: 40, lon: -70 }, distance: '10km' }}, subject.to_hash) end should "take options" do subject = GeoDistance.new :foo, distance: '10km' do lat 40 lon -70 end assert_equal({geo_distance: { foo: { lat: 40, lon: -70 }, distance: '10km' }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/geo_polygon_test.rb000066400000000000000000000017211253341257200302760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class GeoPolygonTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "GeoPolygon filter" do subject { GeoPolygon.new } should "be converted to a Hash" do assert_equal({ geo_polygon: {} }, subject.to_hash) end should "have option methods" do subject = GeoPolygon.new :foo subject.points 'bar' assert_equal %w[ points ], subject.to_hash[:geo_polygon][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_polygon][:foo][:points] end should "take a block" do subject = GeoPolygon.new :foo do points 'bar' end assert_equal({geo_polygon: { foo: { points: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/geo_shape_test.rb000066400000000000000000000020521253341257200277050ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class GeoShapeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "GeoShape filter" do subject { GeoShape.new } should "be converted to a Hash" do assert_equal({ geo_shape: {} }, subject.to_hash) end should "have option methods" do subject = GeoShape.new :foo subject.shape 'bar' subject.indexed_shape 'bar' assert_equal %w[ indexed_shape shape ], subject.to_hash[:geo_shape][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_shape][:foo][:shape] end should "take a block" do subject = GeoShape.new :foo do shape 'bar' end assert_equal({geo_shape: { foo: { shape: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/geohash_cell_test.rb000066400000000000000000000024071253341257200303740ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class GeohashCellTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "GeohashCell filter" do subject { GeohashCell.new } should "be converted to a Hash" do assert_equal({ geohash_cell: {} }, subject.to_hash) end should "have option methods" do subject = GeohashCell.new :foo subject.precision 'bar' subject.neighbors 'bar' subject.lat 'bar' subject.lon 'bar' assert_equal %w[ foo neighbors precision ], subject.to_hash[:geohash_cell].keys.map(&:to_s).sort assert_equal %w[ lat lon ], subject.to_hash[:geohash_cell][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geohash_cell][:precision] assert_equal 'bar', subject.to_hash[:geohash_cell][:foo][:lat] end should "take a block" do subject = GeohashCell.new :foo do lat 'bar' end assert_equal({geohash_cell: { foo: { lat: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/has_child_test.rb000066400000000000000000000027171253341257200277010ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class HasChildTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "HasChild filter" do subject { HasChild.new } should "be converted to a Hash" do assert_equal({ has_child: {} }, subject.to_hash) end should "have option methods" do subject = HasChild.new subject.type 'bar' subject.query 'bar' subject.filter 'bar' subject.min_children 'bar' subject.max_children 'bar' assert_equal %w[ filter max_children min_children query type ], subject.to_hash[:has_child].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:has_child][:type] end should "take a block" do subject = HasChild.new do type 'bar' end assert_equal({has_child: { type: 'bar' } }, subject.to_hash) end should "take a block for option method" do subject = HasChild.new do type 'bar' query do match :foo do query 'bar' end end end assert_equal({ has_child: { type: 'bar', query: { match: { foo: { query: 'bar'} } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/has_parent_test.rb000066400000000000000000000030401253341257200300750ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class HasParentTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "HasParent filter" do subject { HasParent.new } should "be converted to a Hash" do assert_equal({ has_parent: {} }, subject.to_hash) end should "have option methods" do subject = HasParent.new subject.parent_type 'bar' subject.filter 'bar' subject.query 'bar' subject.score_mode 'bar' assert_equal %w[ filter parent_type query score_mode ], subject.to_hash[:has_parent].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:has_parent][:parent_type] end should "take a block" do subject = HasParent.new do parent_type 'bar' query match: { foo: 'bar' } end assert_equal({ has_parent: { parent_type: 'bar', query: { match: { foo: 'bar' } } } }, subject.to_hash) end should "take a block for option method" do subject = HasParent.new do parent_type 'bar' query do match :foo do query 'bar' end end end assert_equal({ has_parent: { parent_type: 'bar', query: { match: { foo: { query: 'bar'} } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/ids_test.rb000066400000000000000000000017141253341257200265360ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class IdsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Ids filter" do subject { Ids.new } should "be converted to a Hash" do assert_equal({ ids: {} }, subject.to_hash) end should "have option methods" do subject = Ids.new subject.type 'bar' subject.values 'bar' assert_equal %w[ type values ], subject.to_hash[:ids].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:ids][:type] end should "take a block" do subject = Ids.new do type 'bar' values ['1', '2', '3'] end assert_equal({ids: { type: 'bar', values: ['1', '2', '3'] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/indices_test.rb000066400000000000000000000027001253341257200273710ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class IndicesTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Indices filter" do subject { Indices.new } should "be converted to a Hash" do assert_equal({ indices: {} }, subject.to_hash) end should "have option methods" do subject = Indices.new subject.indices 'bar' subject.filter 'bar' subject.no_match_filter 'bar' assert_equal %w[ filter indices no_match_filter ], subject.to_hash[:indices].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:indices][:indices] end should "take a block" do subject = Indices.new do indices 'bar' end assert_equal({indices: { indices: 'bar' } }, subject.to_hash) end should "take a block for methods" do subject = Indices.new do indices 'bar' filter do term foo: 'bar' end no_match_filter do term foo: 'bam' end end assert_equal({ indices: { indices: 'bar', filter: { term: { foo: 'bar' } }, no_match_filter: { term: { foo: 'bar' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/limit_test.rb000066400000000000000000000015751253341257200271020ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class LimitTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Limit filter" do subject { Limit.new } should "be converted to a Hash" do assert_equal({ limit: {} }, subject.to_hash) end should "have option methods" do subject = Limit.new subject.value 'bar' assert_equal %w[ value ], subject.to_hash[:limit].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:limit][:value] end should "take a block" do subject = Limit.new do value 'bar' end assert_equal({limit: { value: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/match_all_test.rb000066400000000000000000000006501253341257200277010ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class MatchAllTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "MatchAll filter" do subject { MatchAll.new } should "be converted to a Hash" do assert_equal({ match_all: {} }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/missing_test.rb000066400000000000000000000017551253341257200274350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class MissingTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Missing filter" do subject { Missing.new } should "be converted to a Hash" do assert_equal({ missing: {} }, subject.to_hash) end should "have option methods" do subject = Missing.new subject.field 'bar' subject.existence 'bar' subject.null_value 'bar' assert_equal %w[ existence field null_value ], subject.to_hash[:missing].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:missing][:field] end should "take a block" do subject = Missing.new do field 'bar' end assert_equal({missing: { field: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/nested_test.rb000066400000000000000000000020251253341257200272350ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class NestedTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Nested filter" do subject { Nested.new } should "be converted to a Hash" do assert_equal({ nested: {} }, subject.to_hash) end should "have option methods" do subject = Nested.new subject.path 'bar' subject.filter 'bar' assert_equal %w[ filter path ], subject.to_hash[:nested].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:nested][:path] end should "take a block" do subject = Nested.new do path 'bar' filter do term foo: 'bar' end end assert_equal({nested: { path: 'bar', filter: { term: { foo: 'bar' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/not_test.rb000066400000000000000000000016571253341257200265650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class NotTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Not filter" do subject { Not.new } should "be converted to a Hash" do assert_equal({ not: {} }, subject.to_hash) end should "take a Hash" do subject = Not.new filters: [ { term: { foo: 'bar' } } ] assert_equal({ not: { filters: [ { term: { foo: 'bar' } } ] } }, subject.to_hash) end should "take a block" do subject = Not.new do term foo: 'bar' end assert_equal({not: {term: { foo: 'bar'}} }, subject.to_hash) end should "raise an exception for unknown DSL method" do assert_raise(NoMethodError) { subject.foofoo } end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/or_test.rb000066400000000000000000000026711253341257200264020ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class OrTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Or filter" do subject { Or.new } should "be converted to a Hash" do assert_equal({ or: {} }, subject.to_hash) end should "take a Hash" do subject = Or.new filters: [ { term: { foo: 'bar' } } ] assert_equal({ or: { filters: [ { term: { foo: 'bar' } } ] } }, subject.to_hash) end should "take a block" do subject = Or.new do term foo: 'bar' term moo: 'mam' end assert_equal({or: [ {term: { foo: 'bar'}}, {term: { moo: 'mam'}} ]}, subject.to_hash) end should "behave like an Enumerable" do subject = Or.new subject << { term: { foo: 'bar' } } assert_equal 1, subject.size assert subject.any? { |d| d[:term] == { foo: 'bar' } } end should "behave like an Array" do subject = Or.new assert subject.empty? subject << { term: { foo: 'bar' } } subject << { term: { moo: 'xam' } } assert ! subject.empty? assert_equal({ or: [ { term: { foo: 'bar' } }, { term: { moo: 'xam' } } ] }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/prefix_test.rb000066400000000000000000000010701253341257200272470ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class PrefixTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Prefix filter" do subject { Prefix.new } should "be converted to a Hash" do assert_equal({ prefix: {} }, subject.to_hash) end should "take a Hash" do subject = Prefix.new foo: 'bar' assert_equal({ prefix: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/query_test.rb000066400000000000000000000014571253341257200271300ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class QueryTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Query filter" do subject { Query.new } should "be converted to a Hash" do assert_equal({ query: {} }, subject.to_hash) end should "take a Hash" do subject = Query.new query_string: { query: 'foo' } assert_equal({ query: { query_string: { query: 'foo' } } }, subject.to_hash) end should "take a block" do subject = Query.new do match foo: 'bar' end assert_equal({ query: { match: { foo: 'bar' } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/range_test.rb000066400000000000000000000022751253341257200270560ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class RangeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Range filter" do subject { Range.new } should "be converted to a Hash" do assert_equal({ range: {} }, subject.to_hash) end should "have option methods" do subject = Range.new :foo subject.gte 'bar' subject.lte 'bar' subject.time_zone 'bar' assert_equal %w[ gte lte time_zone ], subject.to_hash[:range][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:range][:foo][:gte] end should "take a hash" do subject = Range.new age: { gte: 10, lte: 20 } assert_equal({ range: { age: { gte: 10, lte: 20 } } }, subject.to_hash) end should "take a block" do subject = Range.new :age do gte 10 lte 20 end assert_equal({ range: { age: { gte: 10, lte: 20 } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/regexp_test.rb000066400000000000000000000021551253341257200272510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class RegexpTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Regexp filter" do subject { Regexp.new } should "be converted to a Hash" do assert_equal({ regexp: {} }, subject.to_hash) end should "have option methods" do subject = Regexp.new :foo subject.value 'bar' subject.flags 'bar' assert_equal %w[ flags value ], subject.to_hash[:regexp][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:regexp][:foo][:value] end should "take a Hash" do subject = Regexp.new foo: 'b.*r' assert_equal({regexp: { foo: 'b.*r' }}, subject.to_hash) end should "take a block" do subject = Regexp.new :foo do value 'b*r' end assert_equal({regexp: { foo: { value: 'b*r' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/script_test.rb000066400000000000000000000020441253341257200272600ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class ScriptTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Script filter" do subject { Script.new } should "be converted to a Hash" do assert_equal({ script: {} }, subject.to_hash) end should "have option methods" do subject = Script.new :foo subject.script 'bar' subject.params foo: 'bar' assert_equal %w[ params script ], subject.to_hash[:script][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:script][:foo][:script] assert_equal 'bar', subject.to_hash[:script][:foo][:params][:foo] end should "take a block" do subject = Script.new :foo do script 'bar' end assert_equal({script: { foo: { script: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/term_test.rb000066400000000000000000000012601253341257200267220ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class TermTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters subject { Term.new message: 'test' } context "Term Filter" do should "take a concrete value" do @subject = Term.new message: 'test' assert_equal({ term: { message: 'test' } }, @subject.to_hash) end should "take a Hash" do @subject = Term.new message: { query: 'test', boost: 2 } assert_equal({ term: { message: { query: 'test', boost: 2 }}}, @subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/terms_test.rb000066400000000000000000000011061253341257200271040ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class TermsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Terms filter" do subject { Terms.new } should "be converted to a Hash" do assert_equal({ terms: {} }, subject.to_hash) end should "be take a Hash" do subject = Terms.new foo: ['abc', 'xyz'] assert_equal({ terms: { foo: ['abc', 'xyz'] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/filters/type_test.rb000066400000000000000000000017141253341257200267400ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Filters class TypeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Filters context "Type filter" do subject { Type.new } should "be converted to a Hash" do assert_equal({ type: {} }, subject.to_hash) end should "have option methods" do subject = Type.new :foo subject.value 'bar' assert_equal %w[ value ], subject.to_hash[:type][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:type][:foo][:value] end should "take a block" do subject = Type.new :foo do value 'bar' end assert_equal({type: { foo: { value: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/000077500000000000000000000000001253341257200243755ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/bool_test.rb000066400000000000000000000065371253341257200267270ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class BoolTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Bool Query" do subject { Bool.new } should "be converted to a Hash" do assert_equal({ bool: {} }, subject.to_hash) end should "take a Hash" do subject = Bool.new must: [ {match: { foo: 'bar' }} ] assert_equal( { bool: { must: [ {match: { foo: 'bar' }} ] } }, subject.to_hash ) end should "take a block" do subject = Bool.new do must { match foo: 'bar' } end assert_equal( { bool: {must: [ {match: { foo: 'bar' }} ] } }, subject.to_hash ) end should "take a block with multiple methods" do subject = Bool.new do must { match foo: 'bar' } must_not { match moo: 'bam' } should { match xoo: 'bax' } end assert_equal( { bool: { must: [ {match: { foo: 'bar' }} ], must_not: [ {match: { moo: 'bam' }} ], should: [ {match: { xoo: 'bax' }} ] } }, subject.to_hash ) end should "take a block with multiple conditions" do subject = Bool.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 # Make sure we're not additive subject.to_hash subject.to_hash assert_equal( { bool: { must: [ {match: { foo: 'bar' }}, {match: { moo: 'bam' }} ], should: [ {match: { xoo: 'bax' }}, {match: { zoo: 'baz' }} ] } }, subject.to_hash ) end should "take method calls" do subject = Bool.new subject.must { match foo: 'bar' } assert_equal( { bool: { must: [ {match: { foo: 'bar' }} ] } }, subject.to_hash ) subject.must { match moo: 'bam' } assert_equal( { bool: { must: [ {match: { foo: 'bar' }}, {match: { moo: 'bam' }} ]} }, subject.to_hash ) subject.should { match xoo: 'bax' } assert_equal( { bool: { must: [ {match: { foo: 'bar' }}, {match: { moo: 'bam' }} ], should: [ {match: { xoo: 'bax' }} ] } }, subject.to_hash ) end should "be chainable" do subject = Bool.new assert_instance_of Bool, subject.must { match foo: 'bar' } assert_instance_of Bool, subject.must { match foo: 'bar' }.must { match moo: 'bam' } assert_instance_of Bool, subject.must_not { match foo: 'bar' } assert_instance_of Bool, subject.should { match foo: 'bar' } end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/boosting_test.rb000066400000000000000000000021761253341257200276130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class BoostingTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Boosting query" do subject { Boosting.new } should "be converted to a Hash" do assert_equal({ boosting: {} }, subject.to_hash) end should "have option methods" do subject = Boosting.new subject.positive 'bar' subject.negative 'bar' subject.negative_boost 'bar' assert_equal %w[ negative negative_boost positive ], subject.to_hash[:boosting].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:boosting][:positive] end should "take a block" do subject = Boosting.new do positive foo: 'bar' negative moo: 'xoo' end assert_equal 'bar', subject.to_hash[:boosting][:positive][:foo] assert_equal 'xoo', subject.to_hash[:boosting][:negative][:moo] end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/common_test.rb000066400000000000000000000023411253341257200272510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class CommonTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Common query" do subject { Common.new } should "be converted to a Hash" do assert_equal({ common: {} }, subject.to_hash) end should "have option methods" do subject = Common.new :foo subject.query 'bar' subject.cutoff_frequency 'bar' subject.low_freq_operator 'bar' subject.minimum_should_match 'bar' subject.boost 'bar' subject.analyzer 'bar' subject.disable_coord 'bar' assert_equal %w[ analyzer boost cutoff_frequency disable_coord low_freq_operator minimum_should_match query ], subject.to_hash[:common][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:common][:foo][:query] end should "take a block" do subject = Common.new :foo do query 'bar' end assert_equal 'bar', subject.to_hash[:common][:foo][:query] end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/constant_score_test.rb000066400000000000000000000025301253341257200310050ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class ConstantScoreTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "ConstantScore query" do subject { ConstantScore.new } should "be converted to a Hash" do assert_equal({ constant_score: {} }, subject.to_hash) end should "have option methods" do subject = ConstantScore.new subject.query 'bar' subject.filter 'bar' subject.boost 'bar' assert_equal %w[ boost filter query ], subject.to_hash[:constant_score].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:constant_score][:query] end should "take a block" do subject = ConstantScore.new do query term: { foo: 'bar' } end assert_equal 'bar', subject.to_hash[:constant_score][:query][:term][:foo] end should "evaluate a block passed to the option method" do subject = ConstantScore.new do query do term foo: 'bar' end end assert_equal 'bar', subject.to_hash[:constant_score][:query][:term][:foo] end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/dis_max_test.rb000066400000000000000000000017611253341257200274120ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class DisMaxTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "DisMax query" do subject { DisMax.new } should "be converted to a Hash" do assert_equal({ dis_max: {} }, subject.to_hash) end should "have option methods" do subject = DisMax.new subject.tie_breaker 'bar' subject.boost 'bar' subject.queries 'bar' assert_equal %w[ boost queries tie_breaker ], subject.to_hash[:dis_max].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:dis_max][:tie_breaker] end should "take a block" do subject = DisMax.new do tie_breaker 'bar' end assert_equal 'bar', subject.to_hash[:dis_max][:tie_breaker] end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/filtered_test.rb000066400000000000000000000026051253341257200275620ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class FilteredTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Filtered query" do subject { Filtered.new } should "be converted to a Hash" do assert_equal({ filtered: {} }, subject.to_hash) end should "have option methods" do subject = Filtered.new subject.query 'bar' subject.filter 'bar' subject.strategy 'bar' assert_equal %w[ filter query strategy ], subject.to_hash[:filtered].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:filtered][:query] end should "take a block" do subject = Filtered.new do query 'bar' end assert_equal 'bar', subject.to_hash[:filtered][:query] end should "evaluate a block passed to the option method" do subject = Filtered.new do query do match foo: 'BLAM' end filter do term bar: 'slam' end end assert_equal({filtered: { query: { match: { foo: 'BLAM' } }, filter: { term: { bar: 'slam' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/function_score_test.rb000066400000000000000000000042521253341257200310040ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class FunctionScoreTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "FunctionScore query" do subject { FunctionScore.new } should "be converted to a Hash" do assert_equal({ function_score: {} }, subject.to_hash) end should "have option methods" do subject = FunctionScore.new subject.query 'bar' subject.filter 'bar' subject.functions ['bar'] subject.script_score 'bar' subject.boost 'bar' subject.max_boost 'bar' subject.score_mode 'bar' subject.boost_mode 'bar' assert_equal %w[ boost boost_mode filter functions max_boost query score_mode script_score ], subject.to_hash[:function_score].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:function_score][:query] end should "take a block" do subject = FunctionScore.new do query 'bar' end assert_equal 'bar', subject.to_hash[:function_score][:query] end should "evaluate a block passed to the option method" do subject = FunctionScore.new do query do match foo: 'BLAM' end filter do term bar: 'slam' end functions << { foo: { abc: '123' } } functions << { foo: { xyz: '456' } } end assert_equal({ function_score: { query: { match: { foo: 'BLAM' } }, filter: { term: { bar: 'slam' } }, functions: [ { foo: { abc: '123' } }, { foo: { xyz: '456' } } ] } }, subject.to_hash) end should "set the functions directly" do subject = FunctionScore.new subject.functions = [ {foo: { abc: '123' }} ] assert_equal({function_score: { functions: [ {foo: { abc: '123' }} ] }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/fuzzy_like_this_field_test.rb000066400000000000000000000025771253341257200323610ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class FuzzyLikeThisFieldTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "FuzzyLikeThisField query" do subject { FuzzyLikeThisField.new } should "be converted to a Hash" do assert_equal({ fuzzy_like_this_field: {} }, subject.to_hash) end should "have option methods" do subject = FuzzyLikeThisField.new :foo subject.like_text 'bar' subject.fuzziness 'bar' subject.analyzer 'bar' subject.max_query_terms 'bar' subject.prefix_length 'bar' subject.boost 'bar' subject.ignore_tf 'bar' assert_equal %w[ analyzer boost fuzziness ignore_tf like_text max_query_terms prefix_length ], subject.to_hash[:fuzzy_like_this_field][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:fuzzy_like_this_field][:foo][:like_text] end should "take a block" do subject = FuzzyLikeThisField.new :foo do like_text 'bar' end assert_equal 'bar', subject.to_hash[:fuzzy_like_this_field][:foo][:like_text] end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/fuzzy_like_this_test.rb000066400000000000000000000024451253341257200312100ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class FuzzyLikeThisTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "FuzzyLikeThis query" do subject { FuzzyLikeThis.new } should "be converted to a Hash" do assert_equal({ fuzzy_like_this: {} }, subject.to_hash) end should "have option methods" do subject = FuzzyLikeThis.new subject.fields 'bar' subject.like_text 'bar' subject.fuzziness 'bar' subject.analyzer 'bar' subject.max_query_terms 'bar' subject.prefix_length 'bar' subject.boost 'bar' assert_equal %w[ analyzer boost fields fuzziness like_text max_query_terms prefix_length ], subject.to_hash[:fuzzy_like_this].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:fuzzy_like_this][:fields] end should "take a block" do subject = FuzzyLikeThis.new do fields ['foo'] like_text 'bar' end assert_equal({ fuzzy_like_this: { fields: ['foo'], like_text: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/fuzzy_test.rb000066400000000000000000000021341253341257200271500ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class FuzzyTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Fuzzy query" do subject { Fuzzy.new } should "be converted to a Hash" do assert_equal({ fuzzy: {} }, subject.to_hash) end should "have option methods" do subject = Fuzzy.new :foo subject.value 'bar' subject.boost 'bar' subject.fuzziness 'bar' subject.prefix_length 'bar' subject.max_expansions 'bar' assert_equal %w[ boost fuzziness max_expansions prefix_length value ], subject.to_hash[:fuzzy][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:fuzzy][:foo][:value] end should "take a block" do subject = Fuzzy.new :foo do value 'bar' end assert_equal({fuzzy: { foo: { value: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/geo_shape_test.rb000066400000000000000000000017571253341257200277250ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class GeoShapeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "GeoShape query" do subject { GeoShape.new } should "be converted to a Hash" do assert_equal({ geo_shape: {} }, subject.to_hash) end should "have option methods" do subject = GeoShape.new :foo subject.shape 'bar' subject.indexed_shape 'bar' assert_equal %w[ indexed_shape shape ], subject.to_hash[:geo_shape][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:geo_shape][:foo][:shape] end should "take a block" do subject = GeoShape.new :foo do shape 'bar' end assert_equal({geo_shape: { foo: { shape: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/has_child_test.rb000066400000000000000000000030431253341257200276770ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class HasChildTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "HasChild query" do subject { HasChild.new } should "be converted to a Hash" do assert_equal({ has_child: {} }, subject.to_hash) end should "have option methods" do subject = HasChild.new subject.type 'bar' subject.query 'bar' subject.score_mode 'bar' subject.min_children 'bar' subject.max_children 'bar' assert_equal %w[ max_children min_children query score_mode type ], subject.to_hash[:has_child].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:has_child][:type] end should "take a block" do subject = HasChild.new do type 'bar' query match: { foo: 'bar' } end assert_equal({ has_child: { type: 'bar', query: { match: { foo: 'bar' } } } }, subject.to_hash) end should "take a block for option method" do subject = HasChild.new do type 'bar' query do match :foo do query 'bar' end end end assert_equal({ has_child: { type: 'bar', query: { match: { foo: { query: 'bar'} } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/has_parent_test.rb000066400000000000000000000021451253341257200301070ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class HasParentTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "HasParent query" do subject { HasParent.new } should "be converted to a Hash" do assert_equal({ has_parent: {} }, subject.to_hash) end should "have option methods" do subject = HasParent.new subject.parent_type 'bar' subject.query 'bar' subject.score_mode 'bar' assert_equal %w[ parent_type query score_mode ], subject.to_hash[:has_parent].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:has_parent][:parent_type] end should "take a block" do subject = HasParent.new do parent_type 'bar' query match: { foo: 'bar' } end assert_equal({ has_parent: { parent_type: 'bar', query: { match: { foo: 'bar' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/ids_test.rb000066400000000000000000000016771253341257200265530ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class IdsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Ids query" do subject { Ids.new } should "be converted to a Hash" do assert_equal({ ids: {} }, subject.to_hash) end should "have option methods" do subject = Ids.new subject.type 'bar' subject.values 'bar' assert_equal %w[ type values ], subject.to_hash[:ids].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:ids][:type] end should "take a block" do subject = Ids.new do type 'bar' values [1, 2, 3] end assert_equal({ids: { type: 'bar', values: [1, 2, 3] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/indices_test.rb000066400000000000000000000021001253341257200273700ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class IndicesTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Indices query" do subject { Indices.new } should "be converted to a Hash" do assert_equal({ indices: {} }, subject.to_hash) end should "have option methods" do subject = Indices.new subject.indices 'bar' subject.query 'bar' subject.no_match_query 'bar' assert_equal %w[ indices no_match_query query ], subject.to_hash[:indices].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:indices][:indices] end should "take a block" do subject = Indices.new do indices 'bar' query term: { foo: 'bar' } end assert_equal({indices: { indices: 'bar', query: { term: { foo: 'bar' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/match_all_test.rb000066400000000000000000000016331253341257200277100ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class MatchAllTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "MatchAll query" do subject { MatchAll.new } should "be converted to a Hash" do assert_equal({ match_all: {} }, subject.to_hash) end should "have option methods" do subject = MatchAll.new subject.boost 'bar' assert_equal %w[ boost ], subject.to_hash[:match_all].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:match_all][:boost] end should "take a block" do subject = MatchAll.new do boost 'bar' end assert_equal({match_all: { boost: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/match_test.rb000066400000000000000000000034541253341257200270630ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class MatchTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Match Query" do subject { Match.new } should "be converted to a Hash" do assert_equal({ match: {} }, subject.to_hash) end should "take a concrete value" do subject = Match.new message: 'test' assert_equal({match: {message: "test"}}, subject.to_hash) end should "have option methods" do subject = Match.new subject.query 'bar' subject.operator 'bar' subject.type 'bar' assert_equal %w[ operator query type ], subject.to_hash[:match].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:match][:query] end should "take a Hash" do subject = Match.new message: { query: 'test', operator: 'and' } assert_equal({match: {message: {query: "test", operator: "and"}}}, subject.to_hash) end should "take a block" do subject = Match.new :message do query 'test' operator 'and' type 'phrase_prefix' boost 2 end assert_equal({match: {message: {query: "test", operator: "and", type: 'phrase_prefix', boost: 2}}}, subject.to_hash) end should "take a method call" do subject = Match.new :message subject.query 'test' subject.operator 'and' assert_equal({match: {message: {query: "test", operator: "and"}}}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/more_like_this_test.rb000066400000000000000000000034311253341257200307570ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class MoreLikeThisTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "MoreLikeThis query" do subject { MoreLikeThis.new } should "be converted to a Hash" do assert_equal({ more_like_this: {} }, subject.to_hash) end should "have option methods" do subject = MoreLikeThis.new subject.fields 'bar' subject.like_text 'bar' subject.min_term_freq 'bar' subject.max_query_terms 'bar' subject.docs 'bar' subject.ids 'bar' subject.include 'bar' subject.exclude 'bar' subject.percent_terms_to_match 'bar' subject.stop_words 'bar' subject.min_doc_freq 'bar' subject.max_doc_freq 'bar' subject.min_word_length 'bar' subject.max_word_length 'bar' subject.boost_terms 'bar' subject.boost 'bar' subject.analyzer 'bar' assert_equal %w[ analyzer boost boost_terms docs exclude fields ids include like_text max_doc_freq max_query_terms max_word_length min_doc_freq min_term_freq min_word_length percent_terms_to_match stop_words ], subject.to_hash[:more_like_this].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:more_like_this][:fields] end should "take a block" do subject = MoreLikeThis.new do fields ['foo', 'bar'] like_text 'abc' end assert_equal({more_like_this: { fields: ['foo','bar'], like_text: 'abc' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/multi_match_test.rb000066400000000000000000000022221253341257200302650ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class MultiMatchTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "MultiMatch query" do subject { MultiMatch.new } should "be converted to a Hash" do assert_equal({ multi_match: {} }, subject.to_hash) end should "have option methods" do subject = MultiMatch.new subject.query 'bar' subject.fields 'bar' subject.type 'bar' subject.use_dis_max 'bar' assert_equal %w[ fields query type use_dis_max ], subject.to_hash[:multi_match].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:multi_match][:query] end should "take a block" do subject = MultiMatch.new do query 'bar' fields ['a', 'b'] end assert_equal 'bar', subject.to_hash[:multi_match][:query] assert_equal ['a', 'b'], subject.to_hash[:multi_match][:fields] end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/nested_test.rb000066400000000000000000000025321253341257200272450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class NestedTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Nested query" do subject { Nested.new } should "be converted to a Hash" do assert_equal({ nested: {} }, subject.to_hash) end should "have option methods" do subject = Nested.new subject.path 'bar' subject.score_mode 'bar' subject.query 'bar' assert_equal %w[ path query score_mode ], subject.to_hash[:nested].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:nested][:path] end should "take the query as a Hash" do subject = Nested.new subject.path 'bar' subject.query match: { foo: 'bar' } assert_equal({nested: { path: 'bar', query: { match: { foo: 'bar' } } } }, subject.to_hash) end should "take a block" do subject = Nested.new do path 'bar' query do match foo: 'bar' end end assert_equal({nested: { path: 'bar', query: { match: { foo: 'bar' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/prefix_test.rb000066400000000000000000000020031253341257200272510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class PrefixTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Prefix query" do subject { Prefix.new } should "be converted to a Hash" do assert_equal({ prefix: {} }, subject.to_hash) end should "have option methods" do subject = Prefix.new :foo subject.value 'bar' subject.boost 'bar' assert_equal %w[ boost value ], subject.to_hash[:prefix][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:prefix][:foo][:value] end should "take a block" do subject = Prefix.new :foo do value 'bar' end assert_equal({prefix: { foo: { value: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/query_string_test.rb000066400000000000000000000040461253341257200305200ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class QueryStringTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "QueryString query" do subject { QueryString.new } should "be converted to a Hash" do assert_equal({ query_string: {} }, subject.to_hash) end should "have option methods" do subject = QueryString.new :foo subject.query 'bar' subject.fields 'bar' subject.default_field 'bar' subject.default_operator 'bar' subject.analyzer 'bar' subject.allow_leading_wildcard 'bar' subject.lowercase_expanded_terms 'bar' subject.enable_position_increments 'bar' subject.fuzzy_max_expansions 'bar' subject.fuzziness 'bar' subject.fuzzy_prefix_length 'bar' subject.phrase_slop 'bar' subject.boost 'bar' subject.analyze_wildcard 'bar' subject.auto_generate_phrase_queries 'bar' subject.minimum_should_match 'bar' subject.lenient 'bar' subject.locale 'bar' subject.use_dis_max 'bar' subject.tie_breaker 'bar' assert_equal %w[ allow_leading_wildcard analyze_wildcard analyzer auto_generate_phrase_queries boost default_field default_operator enable_position_increments fields fuzziness fuzzy_max_expansions fuzzy_prefix_length lenient locale lowercase_expanded_terms minimum_should_match phrase_slop query tie_breaker use_dis_max ], subject.to_hash[:query_string][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:query_string][:foo][:query] end should "take a block" do subject = QueryString.new :foo do query 'foo AND bar' end assert_equal({ query_string: { foo: { query: 'foo AND bar' } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/range_test.rb000066400000000000000000000016631253341257200270630ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class RangeTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Range Query" do should "take a Hash" do @subject = Range.new age: { gte: 10, lte: 20 } assert_equal({:range=>{:age=>{:gte=>10, :lte=>20}}}, @subject.to_hash) end should "take a block" do @subject = Range.new :age do gte 10 lte 20 boost 2 end assert_equal({:range=>{:age=>{:gte=>10, :lte=>20, :boost=>2}}}, @subject.to_hash) end should "take a method call" do @subject = Range.new :age @subject.gte 10 @subject.lte 20 assert_equal({:range=>{:age=>{:gte=>10, :lte=>20}}}, @subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/regexp_test.rb000066400000000000000000000022221253341257200272510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class RegexpTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Regexp query" do subject { Regexp.new } should "be converted to a Hash" do assert_equal({ regexp: {} }, subject.to_hash) end should "have option methods" do subject = Regexp.new :foo subject.value 'bar' subject.boost 'bar' subject.flags 'bar' assert_equal %w[ boost flags value ], subject.to_hash[:regexp][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:regexp][:foo][:value] end should "take a Hash" do subject = Regexp.new foo: 'b.*r' assert_equal({regexp: { foo: 'b.*r' }}, subject.to_hash) end should "take a block" do subject = Regexp.new :foo do value 'bar' end assert_equal({regexp: { foo: { value: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/simple_query_string_test.rb000066400000000000000000000026341253341257200320720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SimpleQueryStringTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SimpleQueryString query" do subject { SimpleQueryString.new } should "be converted to a Hash" do assert_equal({ simple_query_string: {} }, subject.to_hash) end should "have option methods" do subject = SimpleQueryString.new :foo subject.query 'bar' subject.fields 'bar' subject.default_operator 'bar' subject.analyzer 'bar' subject.flags 'bar' subject.lowercase_expanded_terms 'bar' subject.locale 'bar' subject.lenient 'bar' assert_equal %w[ analyzer default_operator fields flags lenient locale lowercase_expanded_terms query ], subject.to_hash[:simple_query_string][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:simple_query_string][:foo][:query] end should "take a block" do subject = SimpleQueryString.new :foo do query 'bar' end assert_equal({simple_query_string: { foo: { query: 'bar' } }}, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/span_first_test.rb000066400000000000000000000016451253341257200301370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SpanFirstTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SpanFirst query" do subject { SpanFirst.new } should "be converted to a Hash" do assert_equal({ span_first: {} }, subject.to_hash) end should "have option methods" do subject = SpanFirst.new subject.match 'bar' assert_equal %w[ match ], subject.to_hash[:span_first].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:span_first][:match] end should "take a block" do subject = SpanFirst.new do match 'bar' end assert_equal({ span_first: { match: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/span_multi_test.rb000066400000000000000000000016441253341257200301410ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SpanMultiTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SpanMulti query" do subject { SpanMulti.new } should "be converted to a Hash" do assert_equal({ span_multi: {} }, subject.to_hash) end should "have option methods" do subject = SpanMulti.new subject.match 'bar' assert_equal %w[ match ], subject.to_hash[:span_multi].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:span_multi][:match] end should "take a block" do subject = SpanMulti.new do match 'bar' end assert_equal({span_multi: { match: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/span_near_test.rb000066400000000000000000000020741253341257200277320ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SpanNearTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SpanNear query" do subject { SpanNear.new } should "be converted to a Hash" do assert_equal({ span_near: {} }, subject.to_hash) end should "have option methods" do subject = SpanNear.new subject.span_near 'bar' subject.slop 'bar' subject.in_order 'bar' subject.collect_payloads 'bar' assert_equal %w[ collect_payloads in_order slop span_near ], subject.to_hash[:span_near].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:span_near][:span_near] end should "take a block" do subject = SpanNear.new do span_near 'bar' end assert_equal({ span_near: { span_near: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/span_not_test.rb000066400000000000000000000020611253341257200276010ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SpanNotTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SpanNot query" do subject { SpanNot.new } should "be converted to a Hash" do assert_equal({ span_not: {} }, subject.to_hash) end should "have option methods" do subject = SpanNot.new subject.include 'bar' subject.exclude 'bar' subject.pre 'bar' subject.post 'bar' subject.dist 'bar' assert_equal %w[ dist exclude include post pre ], subject.to_hash[:span_not].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:span_not][:include] end should "take a block" do subject = SpanNot.new do include 'bar' end assert_equal({ span_not: { include: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/span_or_test.rb000066400000000000000000000016231253341257200274240ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SpanOrTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SpanOr query" do subject { SpanOr.new } should "be converted to a Hash" do assert_equal({ span_or: {} }, subject.to_hash) end should "have option methods" do subject = SpanOr.new subject.clauses 'bar' assert_equal %w[ clauses ], subject.to_hash[:span_or].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:span_or][:clauses] end should "take a block" do subject = SpanOr.new do clauses 'bar' end assert_equal({span_or: { clauses: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/span_term_test.rb000066400000000000000000000011041253341257200277450ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class SpanTermTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "SpanTerm query" do subject { SpanTerm.new } should "be converted to a Hash" do assert_equal({ span_term: {} }, subject.to_hash) end should "take a Hash" do subject = SpanTerm.new foo: 'bar' assert_equal({ span_term: { foo: 'bar' } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/template_test.rb000066400000000000000000000023211253341257200275720ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class TemplateTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Template query" do subject { Template.new } should "be converted to a Hash" do assert_equal({ template: {} }, subject.to_hash) end should "have option methods" do subject = Template.new subject.query 'bar' subject.params 'bar' assert_equal %w[ params query ], subject.to_hash[:template].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:template][:query] end should "take a hash" do subject = Template.new query: 'bar', params: { foo: 'abc' } assert_equal({template: { query: 'bar', params: { foo: 'abc' } } }, subject.to_hash) end should "take a block" do subject = Template.new do query 'bar' params foo: 'abc' end assert_equal({template: { query: 'bar', params: { foo: 'abc' } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/term_test.rb000066400000000000000000000012551253341257200267330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class TermTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries subject { Term.new message: 'test' } context "Term Query" do should "take a concrete value" do @subject = Term.new message: 'test' assert_equal({:term=>{:message=>"test"}}, @subject.to_hash) end should "take a Hash" do @subject = Term.new message: { query: 'test', boost: 2 } assert_equal({:term=>{:message=>{:query=>"test", :boost=>2}}}, @subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/terms_test.rb000066400000000000000000000011021253341257200271050ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class TermsTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Terms query" do subject { Terms.new } should "be converted to a Hash" do assert_equal({ terms: {} }, subject.to_hash) end should "take a Hash" do subject = Terms.new foo: ['abc', 'xyz'] assert_equal({ terms: { foo: ['abc', 'xyz'] } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/top_children_test.rb000066400000000000000000000030251253341257200304330ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class TopChildrenTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "TopChildren query" do subject { TopChildren.new } should "be converted to a Hash" do assert_equal({ top_children: {} }, subject.to_hash) end should "have option methods" do subject = TopChildren.new subject.type 'bar' subject.query 'bar' subject.score 'bar' subject.factor 'bar' subject.incremental_factor 'bar' subject._scope 'bar' assert_equal %w[ _scope factor incremental_factor query score type ], subject.to_hash[:top_children].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:top_children][:type] end should "take a block" do subject = TopChildren.new do type 'bar' query 'foo' end assert_equal({ top_children: { type: 'bar', query: 'foo' } }, subject.to_hash) end should "evaluate a block passed to the query method" do subject = TopChildren.new do type 'bar' query do match foo: 'BLAM' end end assert_equal({ top_children: { type: 'bar', query: { match: { foo: 'BLAM' } } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/queries/wildcard_test.rb000066400000000000000000000022051253341257200275510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test module Queries class WildcardTest < ::Test::Unit::TestCase include Elasticsearch::DSL::Search::Queries context "Wildcard query" do subject { Wildcard.new } should "be converted to a Hash" do assert_equal({ wildcard: {} }, subject.to_hash) end should "have option methods" do subject = Wildcard.new :foo subject.value 'bar' subject.boost 'bar' assert_equal %w[ boost value ], subject.to_hash[:wildcard][:foo].keys.map(&:to_s).sort assert_equal 'bar', subject.to_hash[:wildcard][:foo][:value] end should "take a hash" do subject = Wildcard.new foo: 'bar' assert_equal({ wildcard: { foo: 'bar' } }, subject.to_hash) end should "take a block" do subject = Wildcard.new :foo do value 'bar' end assert_equal({ wildcard: { foo: { value: 'bar' } } }, subject.to_hash) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/search_aggregation_test.rb000066400000000000000000000043511253341257200301230ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchAggregationTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_base_aggregation_component_test.rb000066400000000000000000000025051253341257200331760ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class BaseAggregationComponentTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_base_component_test.rb000066400000000000000000000130461253341257200306310ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class BaseComponentTest < ::Test::Unit::TestCase 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 "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-1.0.12/elasticsearch-dsl/test/unit/search_filter_test.rb000066400000000000000000000035201253341257200271160ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchFilterTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_highlight_test.rb000066400000000000000000000047621253341257200276110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class HighlightTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_options_test.rb000066400000000000000000000045751253341257200273370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchOptionsTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_query_test.rb000066400000000000000000000036471253341257200270100ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchQueryTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_size_from_test.rb000066400000000000000000000022731253341257200276320ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchSizeTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_sort_test.rb000066400000000000000000000021531253341257200266210ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchSortTest < ::Test::Unit::TestCase 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 end end end end elasticsearch-ruby-1.0.12/elasticsearch-dsl/test/unit/search_suggest_test.rb000066400000000000000000000010351253341257200273110ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchSuggestTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-dsl/test/unit/search_test.rb000066400000000000000000000153741253341257200255630ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class SearchTest < ::Test::Unit::TestCase 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 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-1.0.12/elasticsearch-dsl/test/unit/utils_test.rb000066400000000000000000000011031253341257200254370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class UtilsTest < ::Test::Unit::TestCase 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-1.0.12/elasticsearch-extensions/000077500000000000000000000000001253341257200223775ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/.gitignore000066400000000000000000000002321253341257200243640ustar00rootroot00000000000000*.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-1.0.12/elasticsearch-extensions/Gemfile000066400000000000000000000016461253341257200237010ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-extensions.gemspec gemspec if File.exists? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-transport/elasticsearch-transport.gemspec", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch/", __FILE__) end elasticsearch-ruby-1.0.12/elasticsearch-extensions/LICENSE.txt000066400000000000000000000010561253341257200242240ustar00rootroot00000000000000Copyright (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-1.0.12/elasticsearch-extensions/README.md000066400000000000000000000160551253341257200236650ustar00rootroot00000000000000# 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 ### 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, 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" [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-1.0.12/elasticsearch-extensions/Rakefile000066400000000000000000000046341253341257200240530ustar00rootroot00000000000000require "bundler/gem_tasks" desc "Run unit tests" task :default => 'test:unit' task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' namespace :test do task :ci_reporter do ENV['CI_REPORTS'] ||= 'tmp/reports' if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' require 'ci/reporter/rake/test_unit' Rake::Task['ci:setup:testunit'].invoke else require 'ci/reporter/rake/minitest' Rake::Task['ci:setup:minitest'].invoke end end Rake::TestTask.new(:unit) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/**/unit/**/*_test.rb"] # test.verbose = true # test.warning = true end Rake::TestTask.new(:integration) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/**/integration/**/*_test.rb"] end Rake::TestTask.new(:all) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/**/unit/**/*_test.rb", "test/**/unit/**/*_test.rb"] end Rake::TestTask.new(:profile) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] 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-1.0.12/elasticsearch-extensions/elasticsearch-extensions.gemspec000066400000000000000000000040011253341257200307460ustar00rootroot00000000000000# 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 = "" s.license = "Apache 2" 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" unless File.exists? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) s.add_dependency "elasticsearch" end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' s.add_development_dependency "minitest", "~> 4.0" s.add_dependency "ruby-prof" unless defined?(JRUBY_VERSION) || defined?(Rubinius) end s.add_development_dependency "bundler", "> 1" s.add_development_dependency "rake" s.add_development_dependency "awesome_print" 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" s.add_development_dependency "ci_reporter", "~> 1.9" if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_development_dependency "json" end if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9' 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 # Gems for testing integrations s.add_development_dependency "patron" s.add_development_dependency "oj" end elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/000077500000000000000000000000001253341257200231455ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch-extensions.rb000066400000000000000000000000431253341257200304760ustar00rootroot00000000000000require 'elasticsearch/extensions' elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/000077500000000000000000000000001253341257200257575ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions.rb000066400000000000000000000001671253341257200305070ustar00rootroot00000000000000require 'elasticsearch' require 'elasticsearch/extensions/version' module Elasticsearch module Extensions end end elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/000077500000000000000000000000001253341257200301565ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/ansi.rb000066400000000000000000000017211253341257200314360ustar00rootroot00000000000000# 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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/000077500000000000000000000000001253341257200311105ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/actions.rb000066400000000000000000000204401253341257200330750ustar00rootroot00000000000000# 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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/helpers.rb000066400000000000000000000032241253341257200331000ustar00rootroot00000000000000# 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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/ansi/response.rb000066400000000000000000000032431253341257200332750ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/backup.rb000066400000000000000000000072351253341257200317570ustar00rootroot00000000000000# encoding: utf-8 require 'pathname' require 'fileutils' require 'multi_json' require 'oj' require 'elasticsearch' require 'patron' module Backup module Database # Integration with the Backup gem [https://github.com/meskyanichi/backup/] # # This extension allows to backup Elasticsearch indices as flat JSON files on the disk. # # 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 = '/usr/local/var/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 # # # A simple recover script could look like this: # # 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://meskyanichi.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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/test/000077500000000000000000000000001253341257200311355ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/test/cluster.rb000066400000000000000000000304051253341257200331450ustar00rootroot00000000000000require 'timeout' require 'net/http' require 'fileutils' require 'socket' require 'uri' require 'json' require 'ansi' STDOUT.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 a separate testing in-memory cluster, # to not depend on -- and not mess up -- . # # @example Start a cluster with default configuration # require 'elasticsearch/extensions/test/cluster' # Elasticsearch::Extensions::Test::Cluster.start # # @see Cluster#start Cluster.start # @see Cluster#stop Cluster.stop # module Cluster @@number_of_nodes = (ENV['TEST_CLUSTER_NODES'] || 2).to_i @@default_cluster_name = "elasticsearch-test-#{Socket.gethostname.downcase}" # Starts a cluster # # Launches the specified number of nodes in test-suitable configuration by default # and prints information about the cluster -- unless this specific cluster is running already. # # Use the {Cluster#stop Cluster.stop} command with the same arguments to stop this cluster. # # @option arguments [String] :cluster_name Cluster name (default: `elasticsearch_test`) # @option arguments [Integer] :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 [Boolean] :multicast_enabled Whether multicast is enabled (default: true) # @option arguments [Integer] :timeout Timeout when starting the cluster (default: 30) # # You can also use environment variables to set these options. # # @example Start a cluster with default configuration (2 nodes, in-memory, etc) # Elasticsearch::Extensions::Test::Cluster.start # # @example Start a cluster with a custom configuration # Elasticsearch::Extensions::Test::Cluster.start \ # cluster_name: 'my-cluster', # nodes: 3, # node_name: 'my-node', # port: 9350 # # @example Start a cluster with a different Elasticsearch version # Elasticsearch::Extensions::Test::Cluster.start \ # command: "/usr/local/Cellar/elasticsearch/1.0.0.Beta2/bin/elasticsearch" # # @return Boolean # @see Cluster#stop Cluster.stop # def start(arguments={}) @@number_of_nodes = ( ENV.fetch('TEST_CLUSTER_NODES', arguments[:nodes] || 2) ).to_i 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[:es_params] ||= ENV.fetch('TEST_CLUSTER_PARAMS', '') arguments[:multicast_enabled] ||= ENV.fetch('TEST_CLUSTER_MULTICAST', 'true') arguments[:timeout] ||= (ENV.fetch('TEST_CLUSTER_TIMEOUT', 30).to_i) # Make sure `cluster_name` is not dangerous if arguments[:cluster_name] =~ /^[\/\\]?$/ raise ArgumentError, "The `cluster_name` parameter cannot be empty string or a slash" end if running? :on => arguments[:port], :as => arguments[:cluster_name] print "[!] Elasticsearch cluster already running".ansi(:red) wait_for_green(arguments[:port], arguments[:timeout]) return false end # Wipe out data for this cluster name FileUtils.rm_rf "#{arguments[:path_data]}/#{arguments[:cluster_name]}" print "Starting ".ansi(:faint) + @@number_of_nodes.to_s.ansi(:bold, :faint) + " Elasticsearch nodes..".ansi(:faint) pids = [] @@number_of_nodes.times do |n| n += 1 command = <<-COMMAND #{arguments[:command]} \ -D es.foreground=yes \ -D es.cluster.name=#{arguments[:cluster_name]} \ -D es.node.name=#{arguments[:node_name]}-#{n} \ -D es.http.port=#{arguments[:port].to_i + (n-1)} \ -D es.path.data=#{arguments[:path_data]} \ -D es.path.work=#{arguments[:path_work]} \ -D es.cluster.routing.allocation.disk.threshold_enabled=false \ -D es.network.host=0.0.0.0 \ -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.bench=true \ -D es.logger.level=DEBUG \ #{arguments[:es_params]} \ > /dev/null COMMAND STDERR.puts command.gsub(/ {1,}/, ' ') if ENV['DEBUG'] pid = Process.spawn(command) Process.detach pid pids << pid end # Check for proceses running if `ps -p #{pids.join(' ')}`.split("\n").size < @@number_of_nodes+1 STDERR.puts "", "[!!!] Process failed to start (see output above)".ansi(:red) exit(1) end wait_for_green(arguments[:port], arguments[:timeout]) return true end # Stop the cluster. # # Fetches the PID numbers from "Nodes Info" API and terminates matching nodes. # # @example Stop the default cluster # Elasticsearch::Extensions::Test::Cluster.stop # # @example Stop the cluster reachable on specific port # Elasticsearch::Extensions::Test::Cluster.stop port: 9350 # # @return Boolean # @see Cluster#start Cluster.start # def stop(arguments={}) arguments[:port] ||= (ENV['TEST_CLUSTER_PORT'] || 9250).to_i nodes = begin JSON.parse(Net::HTTP.get(URI("http://localhost:#{arguments[:port]}/_nodes/?process"))) rescue Exception => e STDERR.puts "[!] 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? print "\nStopping Elasticsearch nodes... ".ansi(:faint) pids.each_with_index do |pid, i| ['INT','KILL'].each do |signal| begin Process.kill signal, pid rescue Exception => e print "[#{e.class}] PID #{pid} not found. ".ansi(:red) end # Give the system some breathing space to finish... 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 print "stopped PID #{pid} with #{signal} signal. ".ansi(:green) break # pid is dead end end end puts else false end return pids end # Returns true when a specific test node is running within the cluster. # # @option arguments [Integer] :on The port on which the node is running. # @option arguments [String] :as The cluster name. # # @return Boolean # def running?(arguments={}) port = arguments[:on] || (ENV['TEST_CLUSTER_PORT'] || 9250).to_i cluster_name = arguments[:as] || ENV['TEST_CLUSTER_NAME'] || 'elasticsearch_test' if cluster_health = Timeout::timeout(0.25) { __get_cluster_health(port) } rescue nil return cluster_health['cluster_name'] == cluster_name && \ cluster_health['number_of_nodes'] == @@number_of_nodes end return false end # Waits until the cluster is green and prints information # # @example Print the information about the default cluster # Elasticsearch::Extensions::Test::Cluster.wait_for_green # # @param (see #__wait_for_status) # # @return Boolean # def wait_for_green(port=9250, timeout=60) __wait_for_status('green', port, timeout) 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 port [Integer] The port on which the cluster is reachable # @param timeout [Integer] The explicit timeout for the operation # # @api private # # @return Boolean # def __wait_for_status(status='green', port=9250, timeout=30) uri = URI("http://localhost:#{port}/_cluster/health?wait_for_status=#{status}") Timeout::timeout(timeout) do loop do response = begin JSON.parse(Net::HTTP.get(uri)) rescue Exception => e STDERR.puts e.inspect if ENV['DEBUG'] nil end STDERR.puts response.inspect if response && ENV['DEBUG'] if response && response['status'] == status && ( @@number_of_nodes.nil? || @@number_of_nodes == response['number_of_nodes'].to_i ) __print_cluster_info(port) and break end print '.'.ansi(:faint) sleep 1 end end return true end # Print information about the cluster on STDOUT # # @api private # def __print_cluster_info(port) health = JSON.parse(Net::HTTP.get(URI("http://localhost:#{port}/_cluster/health"))) nodes = JSON.parse(Net::HTTP.get(URI("http://localhost:#{port}/_nodes/process,http"))) master = JSON.parse(Net::HTTP.get(URI("http://localhost:#{port}/_cluster/state")))['master_node'] puts "\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) nodes['nodes'].each do |id, info| m = id == master ? '*' : '+' puts ''.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 end # Tries to load cluster health information # # @api private # def __get_cluster_health(port=9250) uri = URI("http://localhost:#{port}/_cluster/health") if response = Net::HTTP.get(uri) rescue nil return JSON.parse(response) end end extend self end end end end elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/test/cluster/000077500000000000000000000000001253341257200326165ustar00rootroot00000000000000tasks.rb000066400000000000000000000005011253341257200342050ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/test/clusterrequire '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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/test/profiling.rb000066400000000000000000000065701253341257200334630ustar00rootroot00000000000000require '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 = 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("#{name} (#{count}x)", count) should "#{name} (#{count}x)" do RubyProf.start count.times do ticks << Benchmark.realtime { self.instance_eval(&block) } # RubyProf.pause # progress.inc # RubyProf.resume end result = RubyProf.stop # progress.finish total = result.threads.reduce(0) { |total,info| total += info.total_time; total } mean = (ticks.sort[(ticks.size/2).round-1])*1000 avg = (ticks.inject {|sum,el| sum += el; sum}.to_f/ticks.size)*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", ___, 'Context: ' + ANSI.bold(context_name) + ' should ' + ANSI.bold(name) + " (#{count}x)", "mean: #{sprintf('%.2f', mean)}ms | " + "avg: #{sprintf('%.2f', avg)}ms | " + "max: #{sprintf('%.2f', max)}ms", ___ printer.print(STDOUT, {}) unless ENV['QUIET'] || options[:quiet] end end end end end end startup_shutdown.rb000066400000000000000000000027531253341257200350470ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-extensions/lib/elasticsearch/extensions/version.rb000066400000000000000000000001121253341257200321620ustar00rootroot00000000000000module Elasticsearch module Extensions VERSION = "0.0.18" end end elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/000077500000000000000000000000001253341257200233565ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/ansi/000077500000000000000000000000001253341257200243105ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/ansi/unit/000077500000000000000000000000001253341257200252675ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/ansi/unit/ansi_test.rb000066400000000000000000000034571253341257200276160ustar00rootroot00000000000000require 'test_helper' require 'elasticsearch/extensions/ansi' class Elasticsearch::Extensions::AnsiTest < Test::Unit::TestCase 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.indices.get_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.indices.get_aliases assert_equal '{"index-1"=>{"aliases"=>{}}}', response.to_ansi end end end elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/backup/000077500000000000000000000000001253341257200246235ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/backup/unit/000077500000000000000000000000001253341257200256025ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-extensions/test/backup/unit/backup_test.rb000066400000000000000000000053621253341257200304410ustar00rootroot00000000000000require '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 < Test::Unit::TestCase 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-1.0.12/elasticsearch-extensions/test/test_helper.rb000066400000000000000000000015271253341257200262260ustar00rootroot00000000000000RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' JRUBY = defined?(JRUBY_VERSION) if RUBY_1_8 puts "Tests for '#{File.expand_path('../..', __FILE__).split('/').last}' not supported on Ruby #{RUBY_VERSION}" exit(0) 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_|ansi" } 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 'elasticsearch/extensions' module Elasticsearch module Test class IntegrationTestCase < ::Test::Unit::TestCase end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/000077500000000000000000000000001253341257200222345ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/.gitignore000066400000000000000000000002321253341257200242210ustar00rootroot00000000000000*.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-1.0.12/elasticsearch-transport/Gemfile000066400000000000000000000013151253341257200235270ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-transport.gemspec gemspec if File.exists? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch/elasticsearch.gemspec", __FILE__) gem 'elasticsearch', :path => File.expand_path("../../elasticsearch", __FILE__), :require => false end elasticsearch-ruby-1.0.12/elasticsearch-transport/LICENSE.txt000066400000000000000000000010561253341257200240610ustar00rootroot00000000000000Copyright (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-1.0.12/elasticsearch-transport/README.md000066400000000000000000000413301253341257200235140ustar00rootroot00000000000000# 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.8.7 or higher and with Elasticsearch 0.90 and 1.0. Features overview: * Pluggable logging and tracing * Plugabble 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 } ] 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 ### 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 configure the _Faraday_ instance, pass a configuration block to the transport constructor: 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 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 } } 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 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 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-1.0.12/elasticsearch-transport/Rakefile000066400000000000000000000046271253341257200237120ustar00rootroot00000000000000require "bundler/gem_tasks" desc "Run unit tests" task :default => 'test:unit' task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' namespace :test do task :ci_reporter do ENV['CI_REPORTS'] ||= 'tmp/reports' if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' require 'ci/reporter/rake/test_unit' Rake::Task['ci:setup:testunit'].invoke else require 'ci/reporter/rake/minitest' Rake::Task['ci:setup:minitest'].invoke end end Rake::TestTask.new(:unit) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] # test.verbose = true # test.warning = true end Rake::TestTask.new(:integration) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/**/*_test.rb"] end Rake::TestTask.new(:all) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb", "test/integration/**/*_test.rb"] end Rake::TestTask.new(:profile) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] 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-1.0.12/elasticsearch-transport/elasticsearch-transport.gemspec000066400000000000000000000053421253341257200304510ustar00rootroot00000000000000# 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" 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.add_dependency "multi_json" s.add_dependency "faraday" if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' s.add_dependency "system_timer" end s.add_development_dependency "bundler", "> 1" s.add_development_dependency "rake" 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" s.add_development_dependency "ci_reporter", "~> 1.9" # 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 "manticore", '~> 0.3.5' 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" 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-1.0.12/elasticsearch-transport/lib/000077500000000000000000000000001253341257200230025ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch-transport.rb000066400000000000000000000000421253341257200301670ustar00rootroot00000000000000require 'elasticsearch/transport' elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/000077500000000000000000000000001253341257200256145ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport.rb000066400000000000000000000016521253341257200302010ustar00rootroot00000000000000require "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/version" module Elasticsearch module Client # A convenience wrapper for {::Elasticsearch::Transport::Client#initialize}. # def new(arguments={}) Elasticsearch::Transport::Client.new(arguments) end extend self end end elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/000077500000000000000000000000001253341257200276505ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/client.rb000066400000000000000000000171431253341257200314610ustar00rootroot00000000000000module 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 # 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 [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) # def initialize(arguments={}) hosts = arguments[:hosts] || \ arguments[:host] || \ arguments[:url] || \ arguments[:urls] || \ ENV.fetch('ELASTICSEARCH_URL', 'localhost:9200') 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[:transport_options].update(:request => { :timeout => arguments[:request_timeout] } ) if arguments[:request_timeout] @send_get_body_as = arguments[:send_get_body_as] || 'GET' transport_class = arguments[:transport_class] || DEFAULT_TRANSPORT_CLASS @transport = arguments[:transport] || begin if transport_class == Transport::HTTP::Faraday transport_class.new(:hosts => __extract_hosts(hosts, arguments), :options => arguments) do |faraday| faraday.adapter(arguments[:adapter] || __auto_detect_adapter) end else transport_class.new(:hosts => __extract_hosts(hosts, arguments), :options => arguments) end end end # Performs a request through delegation to {#transport}. # def perform_request(method, path, params={}, body=nil) method = @send_get_body_as if 'GET' == method && body transport.perform_request method, path, params, body end # 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, options={}) if hosts_config.is_a?(Hash) hosts = [ hosts_config ] else if hosts_config.is_a?(String) && hosts_config.include?(',') hosts = hosts_config.split(/\s*,\s*/) else hosts = Array(hosts_config) end end result = hosts.map do |host| 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.to_s } 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.to_s } when Hash host else raise ArgumentError, "Please pass host as a String, URI or Hash -- #{host.class} given." end end result.shuffle! if options[:randomize_hosts] result 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-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/000077500000000000000000000000001253341257200317045ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/base.rb000066400000000000000000000251721253341257200331520ustar00rootroot00000000000000module 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 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) @hosts = arguments[:hosts] || [] @options = arguments[:options] || {} @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 @last_request_at = Time.now @reload_connections = options[:reload_connections] @reload_after = options[:reload_connections].is_a?(Fixnum) ? options[:reload_connections] : DEFAULT_RELOAD_AFTER @resurrect_after = options[:resurrect_after] || DEFAULT_RESURRECT_AFTER @max_retries = options[:retry_on_failure].is_a?(Fixnum) ? options[:retry_on_failure] : DEFAULT_MAX_RETRIES 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 connection = connections.get_connection(options) @counter += 1 reload_connections! if reload_connections && counter % reload_after == 0 connection 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 # Replaces the connections collection. # # @api private # def __rebuild_connections(arguments={}) @hosts = arguments[:hosts] || [] @options = arguments[:options] || {} @connections = __build_connections end # Log request and response information. # # @api private # def __log(method, path, params, body, url, response, json, took, duration) logger.info "#{method.to_s.upcase} #{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, 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)}'" : '' tracer.info "curl -X #{method.to_s.upcase} '#{trace_url}'#{trace_body}\n" 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 += "#{host[:user]}:#{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 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, &block) raise NoMethodError, "Implement this method in your transport class" unless block_given? start = Time.now if logger || tracer tries = 0 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 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 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, body, url, response, nil, 'N/A', duration if tracer __log_failed response if logger __raise_transport_error response end json = serializer.load(response.body) if 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 __trace method, path, params, 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 # @abstract A transport implementation must implement this method. # See {HTTP::Faraday#__build_connections} for an example. # # @return [Connections::Collection] # @api private def __build_connections raise NoMethodError, "Implement this method in your class" end end end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/connections/000077500000000000000000000000001253341257200342265ustar00rootroot00000000000000collection.rb000066400000000000000000000051541253341257200366340ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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 end end end end end connection.rb000066400000000000000000000075651253341257200366500ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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] @connection = arguments[:connection] @options = arguments[:options] || {} @options[:resurrect_timeout] ||= DEFAULT_RESURRECT_TIMEOUT @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 += "#{host[:user]}:#{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! @dead = true @failures += 1 @dead_since = Time.now self end # Marks this connection as alive, ie. it is eligible to be returned from the pool by the selector. # # @return [self] # def alive! @dead = false self end # Marks this connection as healthy, ie. a request has been successfully performed with it. # # @return [self] # def healthy! @dead = false @failures = 0 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? Time.now > @dead_since + ( @options[:resurrect_timeout] * 2 ** (@failures-1) ) 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.rb000066400000000000000000000035431253341257200363210ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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 = @current.nil? ? 0 : @current+1 @current = 0 if @current >= connections.size connections[@current] end end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/errors.rb000066400000000000000000000037501253341257200335520ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/http/000077500000000000000000000000001253341257200326635ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/http/curb.rb000066400000000000000000000054641253341257200341540ustar00rootroot00000000000000module 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) super do |connection,url| connection.connection.url = url case method when 'HEAD' when 'GET', 'POST', 'PUT', 'DELETE' connection.connection.put_data = __convert_to_json(body) if body else raise ArgumentError, "Unsupported HTTP method: #{method}" end connection.connection.http(method.to_sym) headers = {} headers['content-type'] = 'application/json' if connection.connection.header_str =~ /\/json/ Response.new connection.connection.response_code, connection.connection.body_str, headers end end # Builds and returns a collection of connections. # # @return [Connections::Collection] # def __build_connections Connections::Collection.new \ :connections => hosts.map { |host| host[:protocol] = host[:scheme] || DEFAULT_PROTOCOL host[:port] ||= DEFAULT_PORT client = ::Curl::Easy.new client.headers = {'User-Agent' => "Curb #{Curl::CURB_VERSION}"} 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 }, :selector_class => options[:selector_class], :selector => options[:selector] 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.rb000066400000000000000000000037221253341257200345440ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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) super do |connection, url| response = connection.connection.run_request \ method.downcase.to_sym, url, ( body ? __convert_to_json(body) : nil ), {} Response.new response.status, response.body, response.headers end end # Builds and returns a collection of connections. # # @return [Connections::Collection] # def __build_connections Connections::Collection.new \ :connections => hosts.map { |host| host[:protocol] = host[:scheme] || DEFAULT_PROTOCOL host[:port] ||= DEFAULT_PORT url = __full_url(host) Connections::Connection.new \ :host => host, :connection => ::Faraday::Connection.new(url, (options[:transport_options] || {}), &@block ) }, :selector_class => options[:selector_class], :selector => options[:selector] 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.rb000066400000000000000000000104041253341257200351110ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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 # 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) super do |connection, url| params[:body] = __convert_to_json(body) if body 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.key?(:headers) @request_options[:headers] = options[:headers] end client_options = options[:transport_options] || {} client_options[:ssl] = options[:ssl] || {} 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 url = __full_url(host) Connections::Connection.new \ :host => host, :connection => ::Manticore::Client.new(client_options) }, :selector_class => options[:selector_class], :selector => options[:selector] 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-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/response.rb000066400000000000000000000010761253341257200340730ustar00rootroot00000000000000module 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-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/serializer/000077500000000000000000000000001253341257200340555ustar00rootroot00000000000000multi_json.rb000066400000000000000000000016041253341257200365070ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/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-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/transport/sniffer.rb000066400000000000000000000031111253341257200336610ustar00rootroot00000000000000module Elasticsearch module Transport module Transport # Handles node discovery ("sniffing"). # class Sniffer RE_URL = /\/([^:]*):([0-9]+)\]/ # Use named groups on Ruby 1.9: /\/(?[^:]*):(?[0-9]+)\]/ 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 matches = info["#{transport.protocol}_address"].to_s.match(RE_URL) # TODO: Implement lightweight "indifferent access" here info.merge :host => matches[1], :port => matches[2], :id => id end end.compact hosts.shuffle! if transport.options[:randomize_hosts] hosts end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/lib/elasticsearch/transport/version.rb000066400000000000000000000001111253341257200316530ustar00rootroot00000000000000module Elasticsearch module Transport VERSION = "1.0.12" end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/000077500000000000000000000000001253341257200232135ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/test/integration/000077500000000000000000000000001253341257200255365ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/test/integration/client_test.rb000066400000000000000000000117771253341257200304150ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::ClientIntegrationTest < Elasticsearch::Test::IntegrationTestCase startup do Elasticsearch::Extensions::Test::Cluster.start(nodes: 2) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end context "Elasticsearch client" do teardown do begin; Object.send(:remove_const, :Typhoeus); rescue NameError; end begin; Object.send(:remove_const, :Patron); rescue NameError; end end setup do @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i system "curl -X DELETE http://localhost:#{@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: "localhost:#{@port}" end should "connect to the cluster" do assert_nothing_raised do response = @client.perform_request 'GET', '_cluster/health' assert_equal 2, response.body['number_of_nodes'] end end should "handle paths and URL parameters" do @client.perform_request 'PUT', 'myindex/mydoc/1', {routing: 'XYZ'}, {foo: 'bar'} @client.perform_request 'GET', '_cluster/health?wait_for_status=green', {} response = @client.perform_request 'GET', 'myindex/mydoc/1?routing=XYZ' assert_equal 200, response.status assert_equal 'bar', response.body['_source']['foo'] assert_raise Elasticsearch::Transport::Transport::Errors::NotFound do @client.perform_request 'GET', 'myindex/mydoc/1?routing=ABC' end end should "pass options to the transport" do @client = Elasticsearch::Client.new \ host: "localhost:#{@port}", logger: (ENV['QUIET'] ? nil : @logger), transport_options: { headers: { content_type: 'application/yaml' } } response = @client.perform_request 'GET', '_cluster/health' assert_match /---\ncluster_name:/, response.body.to_s end context "with round robin selector" do setup do @client = Elasticsearch::Client.new \ hosts: ["localhost:#{@port}", "localhost:#{@port+1}" ], logger: (ENV['QUIET'] ? nil : @logger) end should "rotate nodes" do # Hit node 1 response = @client.perform_request 'GET', '_nodes/_local' assert_equal 'node-1', response.body['nodes'].to_a[0][1]['name'] # Hit node 2 response = @client.perform_request 'GET', '_nodes/_local' assert_equal 'node-2', response.body['nodes'].to_a[0][1]['name'] # Hit node 1 response = @client.perform_request 'GET', '_nodes/_local' assert_equal 'node-1', response.body['nodes'].to_a[0][1]['name'] end end context "with a sick node and retry on failure" do setup do @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i @client = Elasticsearch::Client.new \ hosts: ["localhost:#{@port}", "foobar1"], logger: (ENV['QUIET'] ? nil : @logger), retry_on_failure: true end should "retry the request with next server" do assert_nothing_raised do 5.times { @client.perform_request 'GET', '_nodes/_local' } end end should "raise exception when it cannot get any healthy server" do @client = Elasticsearch::Client.new \ hosts: ["localhost:#{@port}", "foobar1", "foobar2", "foobar3"], logger: (ENV['QUIET'] ? nil : @logger), retry_on_failure: 1 assert_nothing_raised do # First hit is OK @client.perform_request 'GET', '_nodes/_local' end assert_raise Faraday::Error::ConnectionFailed do # Second hit fails @client.perform_request 'GET', '_nodes/_local' end end end context "with a sick node and reloading on failure" do setup do @client = Elasticsearch::Client.new \ hosts: ["localhost:#{@port}", "foobar1", "foobar2"], logger: (ENV['QUIET'] ? nil : @logger), reload_on_failure: true end should "reload the connections" do assert_equal 3, @client.transport.connections.size assert_nothing_raised do 5.times { @client.perform_request 'GET', '_nodes/_local' } end assert_equal 2, @client.transport.connections.size end end context "with Faraday adapters" do should "automatically use the Patron client when loaded" do require 'patron' client = Elasticsearch::Transport::Client.new host: "localhost:#{@port}" response = @client.perform_request 'GET', '_cluster/health' assert_equal 200, response.status end unless JRUBY end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/integration/transport_test.rb000066400000000000000000000051451253341257200311630ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::ClientIntegrationTest < Elasticsearch::Test::IntegrationTestCase startup do Elasticsearch::Extensions::Test::Cluster.start(nodes: 2) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end context "Transport" do setup do @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i 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 => 'localhost', :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 => 'localhost', :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 => 'localhost', :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 => 'localhost', :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-1.0.12/elasticsearch-transport/test/profile/000077500000000000000000000000001253341257200246535ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/test/profile/client_benchmark_test.rb000066400000000000000000000106711253341257200315340ustar00rootroot00000000000000require '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 'POST', '/ruby_test_benchmark/', {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/' client.perform_request 'DELETE', '/ruby_test_benchmark_search/' 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 'POST', '/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 'POST', '/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 'POST', '/ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end context "with a single-node cluster and the Typhoeus client" do require 'typhoeus' require 'typhoeus/adapters/faraday' setup do transport = Elasticsearch::Transport::Transport::HTTP::Faraday.new \ :hosts => [ { :host => 'localhost', :port => @port } ] do |f| f.adapter :typhoeus end @client = Elasticsearch::Client.new transport: transport 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 'POST', '/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 'POST', '/ruby_test_benchmark_search/test/_search', {}, {query: {match: {foo: 'bar'}}} end end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/test_helper.rb000066400000000000000000000044001253341257200260540ustar00rootroot00000000000000RUBY_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 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-1.0.12/elasticsearch-transport/test/unit/000077500000000000000000000000001253341257200241725ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-transport/test/unit/client_test.rb000066400000000000000000000217701253341257200270430ustar00rootroot00000000000000require 'test_helper' class Elasticsearch::Transport::ClientTest < Test::Unit::TestCase class DummyTransport def initialize(*); end end context "Client" do setup do Elasticsearch::Transport::Client::DEFAULT_TRANSPORT_CLASS.any_instance.stubs(:__build_connections) @client = Elasticsearch::Transport::Client.new end should "be aliased as Elasticsearch::Client" do assert_nothing_raised do assert_instance_of(Elasticsearch::Transport::Client, Elasticsearch::Client.new) end end should "have default transport" do assert_instance_of Elasticsearch::Transport::Client::DEFAULT_TRANSPORT_CLASS, @client.transport end should "instantiate custom transport class" do client = Elasticsearch::Transport::Client.new :transport_class => DummyTransport assert_instance_of DummyTransport, client.transport end should "take custom transport instance" do client = Elasticsearch::Transport::Client.new :transport => DummyTransport.new assert_instance_of DummyTransport, client.transport end should "delegate performing requests to transport" do assert_respond_to @client, :perform_request @client.transport.expects(:perform_request) @client.perform_request 'GET', '/' end should "send GET request as POST with the send_get_body_as option" do transport = DummyTransport.new client = Elasticsearch::Transport::Client.new :transport => transport, :send_get_body_as => 'POST' transport.expects(:perform_request).with 'POST', '/', {}, '{"foo":"bar"}' client.perform_request 'GET', '/', {}, '{"foo":"bar"}' end should "have default logger for transport" do client = Elasticsearch::Transport::Client.new :log => true assert_respond_to client.transport.logger, :info end should "have default tracer for transport" do client = Elasticsearch::Transport::Client.new :trace => true assert_respond_to client.transport.tracer, :info end should "initialize the default transport class" do Elasticsearch::Transport::Client::DEFAULT_TRANSPORT_CLASS.any_instance. unstub(:__build_connections) client = Elasticsearch::Client.new assert_match /Faraday/, client.transport.connections.first.connection.headers['User-Agent'] end should "pass options to the transport" do client = Elasticsearch::Transport::Client.new :transport_options => { :foo => 'bar' } assert_equal 'bar', client.transport.options[:transport_options][:foo] end should "merge request_timeout to the transport options" do client = Elasticsearch::Transport::Client.new :request_timeout => 120 assert_equal 120, client.transport.options[:transport_options][:request][:timeout] end context "when passed hosts" do should "have localhost by default" do c = Elasticsearch::Transport::Client.new assert_equal 'localhost', c.transport.hosts.first[:host] end should "take :hosts, :host, :url or :urls" do c1 = Elasticsearch::Transport::Client.new :hosts => ['foobar'] c2 = Elasticsearch::Transport::Client.new :host => 'foobar' c3 = Elasticsearch::Transport::Client.new :url => 'foobar' c4 = Elasticsearch::Transport::Client.new :urls => 'foo,bar' assert_equal 'foobar', c1.transport.hosts[0][:host] assert_equal 'foobar', c2.transport.hosts[0][:host] assert_equal 'foobar', c3.transport.hosts[0][:host] assert_equal 'foo', c4.transport.hosts[0][:host] assert_equal 'bar', c4.transport.hosts[1][:host] end end context "when the URL is set in the environment variable" do setup { ENV['ELASTICSEARCH_URL'] = 'foobar' } teardown { ENV.delete('ELASTICSEARCH_URL') } should "use a single host" do c = Elasticsearch::Transport::Client.new assert_equal 1, c.transport.hosts.size assert_equal 'foobar', c.transport.hosts.first[:host] end should "use multiple hosts" do ENV['ELASTICSEARCH_URL'] = 'foo, bar' c = Elasticsearch::Transport::Client.new assert_equal 2, c.transport.hosts.size assert_equal 'foo', c.transport.hosts[0][:host] assert_equal 'bar', c.transport.hosts[1][:host] end end context "extracting hosts" do should "extract from string" do hosts = @client.__extract_hosts 'myhost' assert_equal 'myhost', hosts[0][:host] assert_nil hosts[0][:port] end should "extract from hash" do hosts = @client.__extract_hosts( { :host => 'myhost', :scheme => 'https' } ) assert_equal 'myhost', hosts[0][:host] assert_equal 'https', hosts[0][:scheme] end should "extract from Hashie::Mash" do hosts = @client.__extract_hosts( Hashie::Mash.new(:host => 'myhost', :scheme => 'https') ) assert_equal 'myhost', hosts[0][:host] assert_equal 'https', hosts[0][:scheme] end should "extract from array" do hosts = @client.__extract_hosts ['myhost'] assert_equal 'myhost', hosts[0][:host] end should "extract from array with multiple hosts" do hosts = @client.__extract_hosts ['host1', 'host2'] assert_equal 'host1', hosts[0][:host] assert_equal 'host2', hosts[1][:host] end should "extract from array with ports" do hosts = @client.__extract_hosts ['host1:1000', 'host2:2000'] assert_equal 2, hosts.size assert_equal 'host1', hosts[0][:host] assert_equal '1000', hosts[0][:port] assert_equal 'host2', hosts[1][:host] assert_equal '2000', hosts[1][:port] end should "extract path" do hosts = @client.__extract_hosts 'https://myhost:8080/api' assert_equal '/api', hosts[0][:path] end should "extract scheme (protocol)" do hosts = @client.__extract_hosts 'https://myhost:8080' assert_equal 'https', hosts[0][:scheme] assert_equal 'myhost', hosts[0][:host] assert_equal '8080', hosts[0][:port] end should "extract credentials" do hosts = @client.__extract_hosts 'http://USERNAME:PASSWORD@myhost:8080' assert_equal 'http', hosts[0][:scheme] assert_equal 'USERNAME', hosts[0][:user] assert_equal 'PASSWORD', hosts[0][:password] assert_equal 'myhost', hosts[0][:host] assert_equal '8080', hosts[0][:port] end should "pass hashes over" do hosts = @client.__extract_hosts [{:host => 'myhost', :port => '1000', :foo => 'bar'}] assert_equal 'myhost', hosts[0][:host] assert_equal '1000', hosts[0][:port] assert_equal 'bar', hosts[0][:foo] end should "use URL instance" do require 'uri' hosts = @client.__extract_hosts URI.parse('https://USERNAME:PASSWORD@myhost:4430') assert_equal 'https', hosts[0][:scheme] assert_equal 'USERNAME', hosts[0][:user] assert_equal 'PASSWORD', hosts[0][:password] assert_equal 'myhost', hosts[0][:host] assert_equal '4430', hosts[0][:port] end should "split comma-separated URLs" do hosts = @client.__extract_hosts 'foo, bar' assert_equal 2, hosts.size assert_equal 'foo', hosts[0][:host] assert_equal 'bar', hosts[1][:host] end should "raise error for incompatible argument" do assert_raise ArgumentError do @client.__extract_hosts 123 end end should "randomize hosts" do hosts = [ {:host => 'host1'}, {:host => 'host2'}, {:host => 'host3'}, {:host => 'host4'}, {:host => 'host5'}] Array.any_instance.expects(:shuffle!).twice @client.__extract_hosts(hosts, :randomize_hosts => true) assert_same_elements hosts, @client.__extract_hosts(hosts, :randomize_hosts => true) end end context "detecting adapter for Faraday" do setup do Elasticsearch::Transport::Client::DEFAULT_TRANSPORT_CLASS.any_instance.unstub(:__build_connections) begin; Object.send(:remove_const, :Typhoeus); rescue NameError; end begin; Object.send(:remove_const, :Patron); rescue NameError; end end should "use the default adapter" do c = Elasticsearch::Transport::Client.new handlers = c.transport.connections.all.first.connection.builder.handlers assert_includes handlers, Faraday::Adapter::NetHttp end should "use the adapter from arguments" do c = Elasticsearch::Transport::Client.new :adapter => :typhoeus handlers = c.transport.connections.all.first.connection.builder.handlers assert_includes handlers, Faraday::Adapter::Typhoeus end should "detect the adapter" do require 'patron'; load 'patron.rb' c = Elasticsearch::Transport::Client.new handlers = c.transport.connections.all.first.connection.builder.handlers assert_includes handlers, Faraday::Adapter::Patron end unless JRUBY end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/unit/connection_collection_test.rb000066400000000000000000000055151253341257200321360ustar00rootroot00000000000000require '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 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 => 'foo').dead!.dead! c2 = Connection.new(:host => 'bar').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-1.0.12/elasticsearch-transport/test/unit/connection_selector_test.rb000066400000000000000000000036271253341257200316250ustar00rootroot00000000000000require '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-1.0.12/elasticsearch-transport/test/unit/connection_test.rb000066400000000000000000000057521253341257200277260ustar00rootroot00000000000000require '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 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 end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/unit/response_test.rb000066400000000000000000000007061253341257200274170ustar00rootroot00000000000000require '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-1.0.12/elasticsearch-transport/test/unit/serializer_test.rb000066400000000000000000000006411253341257200277300ustar00rootroot00000000000000require '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-1.0.12/elasticsearch-transport/test/unit/sniffer_test.rb000066400000000000000000000106541253341257200272200ustar00rootroot00000000000000require '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 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 <<-JSON { "ok" : true, "cluster_name" : "elasticsearch_test", "nodes" : { "N1" : { "name" : "Node 1", "transport_address" : "inet[/192.168.1.23:9300]", "hostname" : "testhost1", "version" : "0.20.6", "http_address" : "inet[/192.168.1.23:9200]", "thrift_address" : "/192.168.1.23:9500", "memcached_address" : "inet[/192.168.1.23:11211]" } } } JSON hosts = @sniffer.hosts assert_equal 1, hosts.size assert_equal '192.168.1.23', hosts.first[:host] assert_equal '9200', hosts.first[:port] assert_equal 'Node 1', hosts.first['name'] end should "skip hosts without a matching transport protocol" do @transport = DummyTransport.new :options => { :protocol => 'memcached' } @sniffer = Elasticsearch::Transport::Transport::Sniffer.new @transport @transport.expects(:perform_request).returns __nodes_info <<-JSON { "ok" : true, "cluster_name" : "elasticsearch_test", "nodes" : { "N1" : { "name" : "Memcached Node", "http_address" : "inet[/192.168.1.23:9200]", "memcached_address" : "inet[/192.168.1.23:11211]" }, "N2" : { "name" : "HTTP Node", "http_address" : "inet[/192.168.1.23:9200]" } } } JSON hosts = @sniffer.hosts assert_equal 1, hosts.size assert_equal '192.168.1.23', hosts.first[:host] assert_equal '11211', hosts.first[:port] assert_equal 'Memcached Node', hosts.first['name'] 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-1.0.12/elasticsearch-transport/test/unit/transport_base_test.rb000066400000000000000000000406711253341257200306140ustar00rootroot00000000000000require '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_connections; hosts; 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_connections" do assert_raise NoMethodError do EmptyTransport.new.__build_connections 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 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 "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 "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 "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 "log 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(:__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 "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 end context "rebuilding connections" do setup do @transport = DummyTransport.new end should "should replace the connections" do assert_equal [], @transport.connections @transport.__rebuild_connections :hosts => ['foo', 'bar'] assert_equal ['foo', 'bar'], @transport.connections 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-1.0.12/elasticsearch-transport/test/unit/transport_curb_test.rb000066400000000000000000000101611253341257200306240ustar00rootroot00000000000000require '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 "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 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 "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 end end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/unit/transport_faraday_test.rb000066400000000000000000000140651253341257200313070ustar00rootroot00000000000000require '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| :post == method && '{"foo":"bar"}' == body end.returns(stub_everything) @transport.perform_request 'POST', '/', {}, {:foo => 'bar'} 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 end end elasticsearch-ruby-1.0.12/elasticsearch-transport/test/unit/transport_manticore_test.rb000066400000000000000000000114531253341257200316570ustar00rootroot00000000000000require '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 "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 "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 "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-1.0.12/elasticsearch-watcher/000077500000000000000000000000001253341257200216355ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/.gitignore000066400000000000000000000002711253341257200236250ustar00rootroot00000000000000*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp *.bundle *.so *.o *.a mkmf.log elasticsearch-ruby-1.0.12/elasticsearch-watcher/Gemfile000066400000000000000000000001521253341257200231260ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch-watcher.gemspec gemspec elasticsearch-ruby-1.0.12/elasticsearch-watcher/LICENSE.txt000066400000000000000000000010561253341257200234620ustar00rootroot00000000000000Copyright (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-1.0.12/elasticsearch-watcher/README.md000066400000000000000000000125561253341257200231250ustar00rootroot00000000000000# Elasticsearch::Watcher This library provides Ruby API for the [_Watcher_](https://www.elastic.co/products/watcher) plugin. Please refer to the [_Watcher_ documentation](http://www.elastic.co/guide/en/watcher/current/index.html) for information about the plugin. ## Installation Install the package from [Rubygems](https://rubygems.org): gem install elasticsearch-watcher To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://gembundler.com): gem 'elasticsearch-watcher', 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-watcher bundle install rake install ## Usage The documentation for the Ruby API methods is available at . A comprehensive example of registering a watch, triggering the actions, and getting information about the watch execution is quoted below. ```ruby require 'elasticsearch' require 'elasticsearch/watcher' client = Elasticsearch::Client.new url: 'http://localhost:9200', log: true client.transport.logger.formatter = proc do |severity, datetime, progname, msg| "\e[2m#{msg}\e[0m\n" end # Delete the Watcher and test indices # client.indices.delete index: ['alerts', 'test', '.watches', '.watch_history*'], ignore: 404 # Print information about the Watcher plugin # puts "Watcher #{client.watcher.info['version']['number']}" # Register a new watch # client.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: { script: { inline: 'ctx.payload.hits.total > 3' } }, # Throttle the watch execution for 30 seconds # throttle_period: '30s', # The search request to execute # input: { search: { request: { indices: ['test'], body: { query: { filtered: { query: { match: { status: 500 } }, filter: { range: { timestamp: { from: '{{ctx.trigger.scheduled_time}}||-5m', to: '{{ctx.trigger.triggered_time}}' } } } } }, # Return statistics about different hosts # aggregations: { hosts: { terms: { field: 'host' } } } }}}}, # The actions to perform # actions: { send_email: { transform: { # Transform the data for the template # script: 'return [ total: ctx.payload.hits.total, hosts: ctx.payload.aggregations.hosts.buckets.collect { [ host: it.key, errors: it.doc_count ] }, errors: ctx.payload.hits.hits.collect { it._source } ];' }, email: { to: 'alerts@example.com', subject: '[ALERT] {{ctx.watch_id}}', body: "Received {{ctx.payload.total}} error documents in the last 5 minutes.\n\nHosts:\n\n{{#ctx.payload.hosts}}* {{host}} ({{errors}})\n{{/ctx.payload.hosts}}", attach_data: true } }, index_payload: { # Transform the data to be stored # transform: { script: 'return [ watch_id: ctx.watch_id, payload: ctx.payload ]' }, index: { index: 'alerts', doc_type: 'alert' } }, ping_webhook: { webhook: { method: 'POST', host: 'localhost', port: 4567, path: '/', body: %q|{"watch_id" : "{{ctx.watch_id}}", "payload" : "{{ctx.payload}}"}| } } } } # Index documents to trigger the watch # 5.times do client.index index: 'test', type: 'd', body: { timestamp: Time.now.utc.iso8601, status: 500, 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 # puts '='*80, "" client.search(index: '.watch_history*', q: 'watch_id:error_500', sort: 'trigger_event.schedule.triggered_time:asc')['hits']['hits'].each do |r| puts "#{r['_id']} : #{r['_source']['state']}" end # Delete the watch # puts "Deleting the watch..." client.watcher.delete_watch id: 'error_500', master_timeout: '30s', force: true ``` You can run a simple [Sinatra](https://github.com/sinatra/sinatra/) server to test the `webhook` action with the following Ruby code: ```bash ruby -r sinatra -r json -e 'post("/") { json = JSON.parse(request.body.read); puts %Q~Received #{json["watch_id"]} with payload: #{json["payload"]}~ }' ``` ## 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-1.0.12/elasticsearch-watcher/Rakefile000066400000000000000000000064621253341257200233120ustar00rootroot00000000000000require 'pathname' require 'bundler/gem_tasks' __current__ = Pathname( File.expand_path('..', __FILE__) ) task(:default) { system "rake --tasks" } 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 = true # test.warning = true end desc "Run integration tests" task :integration do unless ENV['TEST_REST_API_SPEC'] puts "[!] Please export the TEST_REST_API_SPEC variable with a path to the Watcher YAML tests" exit(1) end # Define the task t = Rake::TestTask.new(:integration) do |test| test.libs << 'lib' << 'test' test.test_files = FileList["../elasticsearch-api/test/integration/yaml_test_runner.rb", "test/integration/**/*_test.rb"] 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 end desc "Run unit and integration tests" task :all do Rake::Task['test:ci_reporter'].invoke if ENV['CI'] Rake::Task['test:unit'].invoke Rake::Task['test:integration'].invoke end desc "Initialize or update the repository with integration tests" task :update do sh "git --git-dir=#{__current__.join('tmp/elasticsearch-watcher/.git')} --work-tree=#{__current__.join('tmp/elasticsearch-watcher')} fetch origin --verbose" begin puts %x[git --git-dir=#{__current__.join('tmp/elasticsearch-watcher/.git')} --work-tree=#{__current__.join('tmp/elasticsearch-watcher')} pull --verbose] 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__.join('tmp/elasticsearch-watcher/.git')} --work-tree=#{__current__.join('tmp/elasticsearch-watcher')} log --oneline ORIG_HEAD..HEAD | cat", :verbose => false 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 elasticsearch-ruby-1.0.12/elasticsearch-watcher/elasticsearch-watcher.gemspec000066400000000000000000000026771253341257200274630ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/watcher/version' Gem::Specification.new do |s| s.name = "elasticsearch-watcher" s.version = Elasticsearch::Watcher::VERSION s.authors = ["Karel Minarik"] s.email = ["karel.minarik@elasticsearch.org"] s.description = %q{Ruby Integrations for Elasticsearch Watcher plugin (WIP)} s.summary = s.description s.homepage = "" s.license = "Apache 2" 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 "elasticsearch-api" s.add_development_dependency "bundler", "~> 1.3" s.add_development_dependency "rake" s.add_development_dependency "elasticsearch" s.add_development_dependency "elasticsearch-extensions" s.add_development_dependency 'shoulda-context' s.add_development_dependency 'activesupport' s.add_development_dependency 'turn' s.add_development_dependency 'mocha' s.add_development_dependency 'minitest', '~> 4.0' s.add_development_dependency 'minitest-reporters' s.add_development_dependency 'simplecov' s.add_development_dependency 'simplecov-rcov' s.add_development_dependency 'yard' s.add_development_dependency 'cane' s.add_development_dependency 'pry' end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/000077500000000000000000000000001253341257200224035ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch-watcher.rb000066400000000000000000000000401253341257200271670ustar00rootroot00000000000000require 'elasticsearch/watcher' elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/000077500000000000000000000000001253341257200252155ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher.rb000066400000000000000000000020241253341257200271750ustar00rootroot00000000000000require "elasticsearch/watcher/version" Dir[ File.expand_path('../watcher/api/actions/**/*.rb', __FILE__) ].each { |f| require f } module Elasticsearch module Watcher def self.included(base) base.__send__ :include, Elasticsearch::API::Watcher end end end module Elasticsearch module API module Watcher module Actions; end # Client for the "watcher" namespace (includes the {Watcher::Actions} methods) # class WatcherClient include Elasticsearch::API::Common::Client, Elasticsearch::API::Common::Client::Base, Elasticsearch::API::Watcher::Actions end # Proxy method for {WatcherClient}, available in the receiving object # def watcher @watcher ||= WatcherClient.new(self) end end end end Elasticsearch::API.__send__ :include, Elasticsearch::API::Watcher Elasticsearch::Transport::Client.__send__ :include, Elasticsearch::API::Watcher if defined?(Elasticsearch::Transport::Client) elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/000077500000000000000000000000001253341257200266525ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/000077500000000000000000000000001253341257200274235ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/000077500000000000000000000000001253341257200310635ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/ack_watch.rb000066400000000000000000000013461253341257200333400ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Throttle the execution of the watch by acknowledging it # # @option arguments [String] :id Watch ID (*Required*) # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-ack-watch.html # def ack_watch(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ :master_timeout ] method = 'PUT' path = "_watcher/watch/#{arguments[:id]}/_ack" params = {} body = nil perform_request(method, path, params, body).body end end end end end delete_watch.rb000066400000000000000000000015011253341257200337560ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actionsmodule Elasticsearch module API module Watcher module Actions # Delete a specific watch # # @option arguments [String] :id Watch ID (*Required*) # @option arguments [Boolean] :force Ignore any locks on the watch and force the execution # # @see http://www.elastic.co/guide/en/watcher/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 = 'DELETE' path = "_watcher/watch/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end end end end end execute_watch.rb000066400000000000000000000014441253341257200341640ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actionsmodule Elasticsearch module API module Watcher module Actions # Force the execution of the watch actions (eg. for testing) # # @option arguments [String] :id Watch ID (*Required*) # @option arguments [Hash] :body Execution control # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-execute-watch.html # def execute_watch(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ ] method = 'PUT' path = "_watcher/watch/#{arguments[:id]}/_execute" params = {} body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/get_watch.rb000066400000000000000000000016551253341257200333640ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Get a specific watch # # @option arguments [String] :id Watch ID (*Required*) # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-get-watch.html # def get_watch(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ ] method = 'GET' path = "_watcher/watch/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body rescue Exception => e # NOTE: Use exception name, not full class in Elasticsearch::Client to allow client plugability if Array(arguments[:ignore]).include?(404) && e.class.to_s =~ /NotFound/; false else raise(e) end end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/info.rb000066400000000000000000000010071253341257200323410ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Return information about the installed Watcher plugin # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-info.html # def info(arguments={}) valid_params = [ ] method = 'GET' path = "/_watcher/" params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/put_watch.rb000066400000000000000000000017541253341257200334150ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Create a new watch or update an existing one # # @option arguments [String] :id Watch ID (*Required*) # @option arguments [Hash] :body The watch (*Required*) # @option arguments [Boolean] :pretty Pretty the output # # @see http://www.elastic.co/guide/en/watcher/current/appendix-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 ] method = 'PUT' path = "_watcher/watch/#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/restart.rb000066400000000000000000000010051253341257200330700ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Restart the watcher service # # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-service.html # def restart(arguments={}) valid_params = [ ] method = 'PUT' path = "/_watcher/_restart" params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/start.rb000066400000000000000000000007651253341257200325550ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Start the watcher service # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-service.html # def start(arguments={}) valid_params = [ ] method = 'PUT' path = "/_watcher/_start" params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/stats.rb000066400000000000000000000010211253341257200325400ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Return statistical information about the watcher service # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-stats.html # def stats(arguments={}) valid_params = [ ] method = 'GET' path = "/_watcher/stats" params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/api/actions/stop.rb000066400000000000000000000007621253341257200324020ustar00rootroot00000000000000module Elasticsearch module API module Watcher module Actions # Stop the watcher service # # @see http://www.elastic.co/guide/en/watcher/current/appendix-api-service.html # def stop(arguments={}) valid_params = [ ] method = 'PUT' path = "/_watcher/_stop" params = {} body = nil perform_request(method, path, params, body).body end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/lib/elasticsearch/watcher/version.rb000066400000000000000000000001061253341257200306610ustar00rootroot00000000000000module Elasticsearch module Watcher VERSION = "0.0.1" end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/000077500000000000000000000000001253341257200226145ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/test_helper.rb000066400000000000000000000043241253341257200254620ustar00rootroot00000000000000JRUBY = defined?(JRUBY_VERSION) if ENV['COVERAGE'] || ENV['CI'] require 'simplecov' SimpleCov.start { add_filter "/test|test_" } end at_exit { Elasticsearch::Test::IntegrationTestCase.__run_at_exit_hooks } require 'test/unit' require 'shoulda-context' require 'mocha/setup' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require 'elasticsearch' require 'elasticsearch/extensions/test/cluster' require 'elasticsearch/extensions/test/startup_shutdown' require 'elasticsearch/watcher' module Elasticsearch module Test class IntegrationTestCase < ::Test::Unit::TestCase include Elasticsearch::Extensions::Test extend StartupShutdown startup do Cluster.start(nodes: 1) if ENV['SERVER'] \ && ! Elasticsearch::Extensions::Test::Cluster.running? end shutdown do Cluster.stop if ENV['SERVER'] \ && started? \ && Elasticsearch::Extensions::Test::Cluster.running? end def setup @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i @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: "localhost:#{@port}", logger: @logger end def teardown @client.indices.delete index: '_all' end end end end module Elasticsearch module Test class FakeClient include Elasticsearch::API::Watcher 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-1.0.12/elasticsearch-watcher/test/unit/000077500000000000000000000000001253341257200235735ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/ack_watch_test.rb000066400000000000000000000011611253341257200271020ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherAckWatchTest < ::Test::Unit::TestCase context "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 '_watcher/watch/foo/_ack', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.ack_watch id: 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/delete_watch_test.rb000066400000000000000000000011701253341257200276060ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherDeleteWatchTest < ::Test::Unit::TestCase context "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 "_watcher/watch/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.delete_watch id: 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/execute_watch_test.rb000066400000000000000000000012251253341257200300070ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherExecuteWatchTest < ::Test::Unit::TestCase context "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 "_watcher/watch/foo/_execute", url assert_equal Hash.new, params assert_equal Hash.new, body true end.returns(FakeResponse.new) subject.watcher.execute_watch id: 'foo', body: {} end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/get_watch_test.rb000066400000000000000000000011541253341257200271250ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherGetWatchTest < ::Test::Unit::TestCase context "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 "_watcher/watch/foo", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.get_watch id: 'foo' end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/info_test.rb000066400000000000000000000011141253341257200261070ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherInfoTest < ::Test::Unit::TestCase context "Watcher: 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 '/_watcher/', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.info end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/put_watch_test.rb000066400000000000000000000012211253341257200271510ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherPutWatchTest < ::Test::Unit::TestCase context "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 "_watcher/watch/foo", url assert_equal Hash.new, params assert_equal({foo: 'bar'}, body) true end.returns(FakeResponse.new) subject.watcher.put_watch id: 'foo', body: { foo: 'bar' } end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/restart_test.rb000066400000000000000000000011351253341257200266430ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherRestartTest < ::Test::Unit::TestCase context "Watcher: Restart" 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 "/_watcher/_restart", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.restart end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/start_test.rb000066400000000000000000000011251253341257200263130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherStartTest < ::Test::Unit::TestCase context "Watcher: Start" 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 "/_watcher/_start", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.start end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/stats_test.rb000066400000000000000000000011241253341257200263130ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherStatsTest < ::Test::Unit::TestCase context "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 "/_watcher/stats", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.stats end end end end end elasticsearch-ruby-1.0.12/elasticsearch-watcher/test/unit/stop_test.rb000066400000000000000000000011211253341257200261370ustar00rootroot00000000000000require 'test_helper' module Elasticsearch module Test class WatcherStopTest < ::Test::Unit::TestCase context "Watcher: Stop" 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 "/_watcher/_stop", url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.watcher.stop end end end end end elasticsearch-ruby-1.0.12/elasticsearch/000077500000000000000000000000001253341257200202025ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch/.gitignore000066400000000000000000000002321253341257200221670ustar00rootroot00000000000000*.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-1.0.12/elasticsearch/Gemfile000066400000000000000000000013521253341257200214760ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in elasticsearch.gemspec gemspec if File.exists? File.expand_path("../../elasticsearch-api/elasticsearch-api.gemspec", __FILE__) gem 'elasticsearch-api', :path => File.expand_path("../../elasticsearch-api", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-transport/elasticsearch-transport.gemspec", __FILE__) gem 'elasticsearch-transport', :path => File.expand_path("../../elasticsearch-transport", __FILE__), :require => false end if File.exists? File.expand_path("../../elasticsearch-extensions", __FILE__) gem 'elasticsearch-extensions', :path => File.expand_path("../../elasticsearch-extensions", __FILE__), :require => true end elasticsearch-ruby-1.0.12/elasticsearch/LICENSE.txt000066400000000000000000000011101253341257200220160ustar00rootroot00000000000000 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-1.0.12/elasticsearch/README.md000066400000000000000000000070541253341257200214670ustar00rootroot00000000000000# Elasticsearch The `elasticsearch` library provides a Ruby client and API for [Elasticsearch](http://elasticsearch.org). Features overview: * Pluggable logging and tracing * Plugabble 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 library is compatible with Ruby 1.8.7 and higher. The library is compatible with Elasticsearch 0.90 and 1.0 -- you have to install and use a matching version, though. The 1.x versions and the master branch are compatible with **Elasticsearch 1.0** API. To use the **Elasticsearch 0.90** API, install the **0.4.x** gem version or use the corresponding [`0.4`](https://github.com/elasticsearch/elasticsearch-ruby/tree/0.4) branch. ## 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-1.0.12/elasticsearch/Rakefile000066400000000000000000000025531253341257200216540ustar00rootroot00000000000000require "bundler/gem_tasks" desc "Run unit tests" task :test => 'test:unit' # ----- Test tasks ------------------------------------------------------------ require 'rake/testtask' namespace :test do task :ci_reporter do ENV['CI_REPORTS'] ||= 'tmp/reports' if defined?(RUBY_VERSION) && RUBY_VERSION < '1.9' require 'ci/reporter/rake/test_unit' Rake::Task['ci:setup:testunit'].invoke else require 'ci/reporter/rake/minitest' Rake::Task['ci:setup:minitest'].invoke end end Rake::TestTask.new(:unit) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb"] # test.verbose = true # test.warning = true end Rake::TestTask.new(:integration) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/integration/**/*_test.rb"] end Rake::TestTask.new(:all) do |test| Rake::Task['test:ci_reporter'].invoke if ENV['CI'] test.libs << 'lib' << 'test' test.test_files = FileList["test/unit/**/*_test.rb", "test/integration/**/*_test.rb"] end end # ----- Documentation tasks --------------------------------------------------- require 'yard' YARD::Rake::YardocTask.new(:doc) do |t| t.options = %w| --embed-mixins --markup=markdown | end elasticsearch-ruby-1.0.12/elasticsearch/elasticsearch.gemspec000066400000000000000000000043751253341257200243720ustar00rootroot00000000000000# 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" 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.add_dependency "elasticsearch-transport", '1.0.12' s.add_dependency "elasticsearch-api", '1.0.12' s.add_development_dependency "bundler", "> 1" s.add_development_dependency "rake" 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" s.add_development_dependency "ci_reporter", "~> 1.9" # 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" 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-1.0.12/elasticsearch/lib/000077500000000000000000000000001253341257200207505ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch/lib/elasticsearch-ruby.rb000066400000000000000000000000301253341257200250570ustar00rootroot00000000000000require 'elasticsearch' elasticsearch-ruby-1.0.12/elasticsearch/lib/elasticsearch.rb000066400000000000000000000003141253341257200241050ustar00rootroot00000000000000require "elasticsearch/version" require 'elasticsearch/transport' require 'elasticsearch/api' module Elasticsearch module Transport class Client include Elasticsearch::API end end end elasticsearch-ruby-1.0.12/elasticsearch/lib/elasticsearch/000077500000000000000000000000001253341257200235625ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch/lib/elasticsearch/version.rb000066400000000000000000000000561253341257200255750ustar00rootroot00000000000000module Elasticsearch VERSION = "1.0.12" end elasticsearch-ruby-1.0.12/elasticsearch/test/000077500000000000000000000000001253341257200211615ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch/test/integration/000077500000000000000000000000001253341257200235045ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch/test/integration/client_integration_test.rb000066400000000000000000000034501253341257200307530ustar00rootroot00000000000000require 'test_helper' require 'logger' module Elasticsearch module Test class ClientIntegrationTest < Elasticsearch::Test::IntegrationTestCase startup do Elasticsearch::Extensions::Test::Cluster.start(nodes: 2) if ENV['SERVER'] and not Elasticsearch::Extensions::Test::Cluster.running? end context "Elasticsearch client" do setup do @port = (ENV['TEST_CLUSTER_PORT'] || 9250).to_i system "curl -X DELETE http://localhost:#{@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: "localhost:#{@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-1.0.12/elasticsearch/test/test_helper.rb000066400000000000000000000041261253341257200240270ustar00rootroot00000000000000RUBY_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 # 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-1.0.12/elasticsearch/test/unit/000077500000000000000000000000001253341257200221405ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/elasticsearch/test/unit/wrapper_gem_test.rb000066400000000000000000000010701253341257200260320ustar00rootroot00000000000000require '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-1.0.12/examples/000077500000000000000000000000001253341257200172065ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/examples/rabbitmq/000077500000000000000000000000001253341257200210075ustar00rootroot00000000000000elasticsearch-ruby-1.0.12/examples/rabbitmq/Gemfile000066400000000000000000000001331253341257200222770ustar00rootroot00000000000000source 'https://rubygems.org' gem 'elasticsearch' gem 'bunny' gem 'multi_json' gem 'oj' elasticsearch-ruby-1.0.12/examples/rabbitmq/consumer-publisher.rb000066400000000000000000000021221253341257200251570ustar00rootroot00000000000000# 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