diff --git a/.github/workflows/2.5.yml b/.github/workflows/2.5.yml deleted file mode 100644 index 68f8294fe..000000000 --- a/.github/workflows/2.5.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: Ruby 2.5 -on: - push: - branches: - - main - pull_request: - branches: - - main - workflow_dispatch: - branches: - - '*' -jobs: - tests: - env: - TEST_ES_SERVER: http://localhost:9200 - RAILS_VERSIONS: '5.0,6.0' - strategy: - fail-fast: false - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Increase system limits - run: | - sudo swapoff -a - sudo sysctl -w vm.swappiness=1 - sudo sysctl -w fs.file-max=262144 - sudo sysctl -w vm.max_map_count=262144 - - uses: elastic/elastic-github-actions/elasticsearch@master - with: - stack-version: 7.x-SNAPSHOT - - uses: ruby/setup-ruby@v1 - with: - ruby-version: 2.5 - - name: Bundle - run: | - sudo apt-get install libsqlite3-dev - gem install bundler - bundle install - bundle exec rake bundle:clean - bundle exec rake bundle:install - - name: Test elasticsearch-rails - run: cd elasticsearch-rails && bundle exec rake test:all - - name: Test elasticsearch-persistence - run: cd elasticsearch-persistence && bundle exec rake test:all - - name: Test elasticsearch-model - run: cd elasticsearch-model && bundle exec rake test:all - diff --git a/.github/workflows/2.6.yml b/.github/workflows/2.6.yml deleted file mode 100644 index c003a58e5..000000000 --- a/.github/workflows/2.6.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Ruby 2.6 -on: - push: - branches: - - main - pull_request: - branches: - - main - workflow_dispatch: - branches: - - '*' -jobs: - tests: - env: - TEST_ES_SERVER: http://localhost:9200 - RAILS_VERSIONS: '5.0,6.0' - strategy: - fail-fast: false - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Increase system limits - run: | - sudo swapoff -a - sudo sysctl -w vm.swappiness=1 - sudo sysctl -w fs.file-max=262144 - sudo sysctl -w vm.max_map_count=262144 - - uses: elastic/elastic-github-actions/elasticsearch@master - with: - stack-version: 7.x-SNAPSHOT - - uses: ruby/setup-ruby@v1 - with: - ruby-version: 2.6 - - name: Bundle - run: | - sudo apt-get install libsqlite3-dev - gem install bundler - bundle install - bundle exec rake bundle:clean - bundle exec rake bundle:install - - name: Test elasticsearch-rails - run: cd elasticsearch-rails && bundle exec rake test:all - - name: Test elasticsearch-persistence - run: cd elasticsearch-persistence && bundle exec rake test:all - - name: Test elasticsearch-model - run: cd elasticsearch-model && bundle exec rake test:all diff --git a/.github/workflows/2.7.yml b/.github/workflows/2.7.yml index 8bfd9b66f..d5da70cfe 100644 --- a/.github/workflows/2.7.yml +++ b/.github/workflows/2.7.yml @@ -13,7 +13,7 @@ jobs: tests: env: TEST_ES_SERVER: http://localhost:9200 - RAILS_VERSIONS: '5.0,6.0' + RAILS_VERSIONS: '6.1,7.1' strategy: fail-fast: false runs-on: ubuntu-latest @@ -25,22 +25,22 @@ jobs: sudo sysctl -w vm.swappiness=1 sudo sysctl -w fs.file-max=262144 sudo sysctl -w vm.max_map_count=262144 - - uses: elastic/elastic-github-actions/elasticsearch@master + - uses: opensearch-project/opensearch-ruby/.github/actions/opensearch@main with: - stack-version: 7.x-SNAPSHOT + cluster-version: 2 - uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 - name: Bundle run: | sudo apt-get install libsqlite3-dev - gem install bundler + gem install bundler -v 2.4.22 bundle install bundle exec rake bundle:clean bundle exec rake bundle:install - - name: Test elasticsearch-rails - run: cd elasticsearch-rails && bundle exec rake test:all - - name: Test elasticsearch-persistence - run: cd elasticsearch-persistence && bundle exec rake test:all - - name: Test elasticsearch-model - run: cd elasticsearch-model && bundle exec rake test:all + - name: Test opensearch-rails + run: cd opensearch-rails && bundle exec rake test:all + - name: Test opensearch-persistence + run: cd opensearch-persistence && bundle exec rake test:all + - name: Test opensearch-model + run: cd opensearch-model && bundle exec rake test:all diff --git a/.github/workflows/2.4.yml b/.github/workflows/3.2.yml similarity index 61% rename from .github/workflows/2.4.yml rename to .github/workflows/3.2.yml index 890c78613..8bae5452d 100644 --- a/.github/workflows/2.4.yml +++ b/.github/workflows/3.2.yml @@ -1,4 +1,4 @@ -name: Ruby 2.4 +name: Ruby 3.2 on: push: branches: @@ -13,7 +13,7 @@ jobs: tests: env: TEST_ES_SERVER: http://localhost:9200 - RAILS_VERSIONS: '5.0' + RAILS_VERSIONS: '7.1' strategy: fail-fast: false runs-on: ubuntu-latest @@ -25,12 +25,12 @@ jobs: sudo sysctl -w vm.swappiness=1 sudo sysctl -w fs.file-max=262144 sudo sysctl -w vm.max_map_count=262144 - - uses: elastic/elastic-github-actions/elasticsearch@master + - uses: opensearch-project/opensearch-ruby/.github/actions/opensearch@main with: - stack-version: 7.x-SNAPSHOT + cluster-version: 2 - uses: ruby/setup-ruby@v1 with: - ruby-version: 2.4 + ruby-version: 3.2 - name: Bundle run: | sudo apt-get install libsqlite3-dev @@ -38,9 +38,9 @@ jobs: bundle install bundle exec rake bundle:clean bundle exec rake bundle:install - - name: Test elasticsearch-rails - run: cd elasticsearch-rails && bundle exec rake test:all - - name: Test elasticsearch-persistence - run: cd elasticsearch-persistence && bundle exec rake test:all - - name: Test elasticsearch-model - run: cd elasticsearch-model && bundle exec rake test:all + - name: Test opensearch-rails + run: cd opensearch-rails && bundle exec rake test:all + - name: Test opensearch-persistence + run: cd opensearch-persistence && bundle exec rake test:all + - name: Test opensearch-model + run: cd opensearch-model && bundle exec rake test:all diff --git a/.github/workflows/jruby.yml b/.github/workflows/jruby.yml index 7a3ec1be7..67f14f548 100644 --- a/.github/workflows/jruby.yml +++ b/.github/workflows/jruby.yml @@ -25,9 +25,9 @@ jobs: sudo sysctl -w vm.swappiness=1 sudo sysctl -w fs.file-max=262144 sudo sysctl -w vm.max_map_count=262144 - - uses: elastic/elastic-github-actions/elasticsearch@master + - uses: opensearch-project/opensearch-ruby/.github/actions/opensearch@main with: - stack-version: 7.x-SNAPSHOT + cluster-version: 2 - uses: ruby/setup-ruby@v1 with: ruby-version: jruby-9.3 @@ -38,7 +38,7 @@ jobs: bundle install bundle exec rake bundle:clean bundle exec rake bundle:install - - name: Test elasticsearch-rails - run: cd elasticsearch-rails && bundle exec rake test:all - - name: Test elasticsearch-persistence - run: cd elasticsearch-persistence && bundle exec rake test:all + - name: Test opensearch-rails + run: cd opensearch-rails && bundle exec rake test:all + - name: Test opensearch-persistence + run: cd opensearch-persistence && bundle exec rake test:all diff --git a/CHANGELOG.md b/CHANGELOG.md index c3405dea7..e5d2f641f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,234 +1,16 @@ -## 7.2.1 +## 1.0.0 -* The default git branch `master` has been renamed to `main` -* Adds compatibility with Ruby 3 [Pull Request](https://github.com/elastic/elasticsearch-rails/pull/992) +* Support OpenSearch 2 by removing deprecated type and include_type_name parameters -## 7.2.0 +## 0.1.1 -* Updates specs and dependency to use with `elasticsearch` v7.14.0. -* Update README, remove Virtus (unmaintained) -* Updates `Bundler.with_clean_dev` (deprecated) to `with_unbundled_env` [commit](https://github.com/elastic/elasticsearch-rails/commit/e4545e4fe2a1ce80009206c831d5740360bad6c2) -* Deal with `nil` document types in Multimodel [commit](https://github.com/elastic/elasticsearch-rails/commit/cd9c309b78de443d2e37760998418616ba34276d) -* Update dependency to explicitly support version 7 [commit](https://github.com/elastic/elasticsearch-rails/commit/65942e3da9cabad2f6965e69c8ef6a0994da9408) -* Stop emitting FATAL log when checking existence of indices [commit](https://github.com/elastic/elasticsearch-rails/commit/5db9207ca398c5d77f671109360ca7f63e3f2112) -* Remove unnecessary exception test on index checking [commit](https://github.com/elastic/elasticsearch-rails/commit/ce57cc17e304b0a4af123c1599f37fb892a5d93a) -* Removes dependency on extensions [commit](https://github.com/elastic/elasticsearch-rails/commit/ed070b8329ca48b4cb12b513ac81ed78c88acc61) -* Fixes basic template elasticsearch dependency [commit](https://github.com/elastic/elasticsearch-rails/commit/a4ec07b2d097545ca41c13686c9cbfc9eab9e639) +* Pin opensearch-ruby to '~> 1.1' because OpenSearch 2 is not supported yet -### ActiveModel +## 0.1.0 -* Fixes indexing to use right logger in client -* Updates ES client spec for client 7.14.0 -* Updates transport references +* Fork [elasticsearch-rails v7.2.1](https://github.com/elastic/elasticsearch-rails/tree/v7.2.1) +* Replace elasticsearch-ruby by opensearch-ruby +* Change Elasticsearch module name to OpenSearch +* Rename ELASTICSEARCH_URL environment variable to OPENSEARCH_URL +* Rename __elasticsearch__ method to __opensearch__ -## 7.1.1 - -* Fix: Ruby 2.7 deprecation warning on `find_in_batches` -* Updates README for generating app with template. Related: #938 - -### ActiveModel - -* Do not override existing methods (#936) - -## 7.1.0 - -* Tested with elasticsearch Ruby client version 7.6.0 -* Updates rake version -* Adds pipeline to bulk params [commit](https://github.com/elastic/elasticsearch-rails/commit/63c24c9fe48a74d00c65145cc55c32f4c6907448) - -## 7.0.0 - -* Update test tasks and travis (#840) -* `respond_to_missing?` to silence Ruby 2.4 warnings (#838) -* Update README.md to link to migration blog post (#857) -* Add license headers, LICENSE and NOTICE files (#861) -* Only execute update if document attributes is not empty (#862) -* Remove bundler version requirement in gemspec files -* 7.0 support (#875) - -### ActiveModel - -* Fix import when preprocess returns empty collection (#720) -* Add test for not importing when ActiveRecord query is empty -* with 0 -* Port basic response tests to rspec (#833) -* Add newlines at the end of files that are missing it -* Port adapter tests to rspec (#834) -* Ensure that specified ActiveRecord order is not overwritten by Elasticsearch search results order (#835) -* Port remainder of Elasticsearch::Model unit tests to rspec (#836) -* Port all integration tests to rspec (#837) -* Avoid executing search twice; Reuse response in Response#raw_response (#850) -* Update example to account for deprecation of _suggest endpoint in favor of _search -* Handle total hits as an object in search response -* Use logger to log index not found message (#868) -* Test against Rails 6.0.rc1 - -### Persistence - -* Ensure that arguments are passed to super (#853) -* Index name option is handled by super, no need to pass options expicitly -* Handle total hits as an object in search response - -### Ruby on Rails - -* Convert tests to rspec (#842) -* Fix seeds file to stop using outdated YAML method (#843) -* Fixed 03-expert.rb set tracer only in dev env (#621) - -## 6.0.0 - -* Update to test against Elasticsearch 6.4 -* Fix sort order on ActiveRecord >= 5. re issue #546 (#831) - -### ActiveModel - -* Inherit from HashWrapper for disabling warnings -* Fix import method to pass index name on refresh (#692) -* Use default scope on ActiveRecord model when importing (#827) -* Support scope, query and preprocess importing options in Mongoid Adapter in 6.x (#829) -* Address performance of HashWrapper in Response objects (#825) - -### Persistence - -* Address performance of HashWrapper in Response objects (#825) -* Minor refactor in Repository::Search -* Remove example music app that demonstrates the AR pattern -* Update Sinatra app -* Update README -* Change document type references to _doc - -## 6.0.0.pre - -* Added the "Compatibility" chapter to the READMEs -* Updated the Bundler instructions and Github URLs in the READMEs -* Updated the version on the `master` branch to `6.0.0.alpha1` -* Update versions to 6.0.0.beta -* minor: Fix spacing -* Update various gemspecs to conditionally depend on gems incompatible with JRuby (#810) -* Update versions -* Use local as source for gem dependencies when possible -* Only require 'oj' gem if not using JRuby -* Update versions to .pre - -### ActiveModel - -* Added an example with a custom "pattern" analyzer -* Added a "trigram" custom analyzer to the example -* Fix README typo (s/situation/situations) -* Fix reference to @ids in example and README -* Add Callbacks to the example datamapper adapter -* Fix `Asynchronous Callbacks` example -* Fixed a typo in the README -* Improved the custom analyzer example -* Removed left-overs from previous implementation in the "completion suggester" example -* Updated the `changes` method name in `Indexing` to `changes_to_save` for compatibility with Rails 5.1 -* Fixed the handling of changed attributes in `Indexing` to work with older Rails versions -* Update child-parent integration test to use single index type for ES 6.3 (#805) -* Use default doc type: _doc (#814) -* Avoid making an update when no attributes are changed (#762) - -### Persistence - -* Updated the failing integration tests for Elasticsearch 5.x -* Updated the dependency for "elasticsearch" and "elasticsearch-model" to `5.x` -* Documentation for Model should include Model and not Repository -* Depend on version >= 6 of elasticsearch gems -* Undo last commit; depend on version 5 of elasticsearch gems -* Reduce repeated string instantiation (#813) -* Make default doc type '_doc' in preparation for deprecation of mapping types (#816) -* Remove Elasticsearch::Persistence::Model (ActiveRecord persistence pattern) (#812) -* Deprecate _all field in ES 6.x (#820) -* Remove development dependency on virtus, include explicitly in Gemfile for integration test -* Refactor Repository as mixin (#824) -* Add missing Repository::Response::Results spec -* Update README for Repository mixin refactor -* Minor typo in README -* Add #inspect method for Repository -* Update references to Elasticsearch::Client - -### Ruby on Rails - -* Fixed typo in README -* Fix typo in rake import task -* Updated the templates for example Rails applications -* Add 'oj' back as a development dependency in gemspec - -## 6.0.0.alpha1 - -* Updated the Rake dependency to 11.1 -* Reduced verbosity of `rake test:unit` and `rake test:integration` -* Removed the "CI Reporter" integration from test Rake tasks -* Added the "Compatibility" chapter to the READMEs -* Updated the Bundler instructions and Github URLs in the READMEs - -### ActiveModel - -* Fixed a problem where `Hashie::Mash#min` and `#max` returned unexpected values -* Added information about `elasticsearch-dsl` to the README -* Added support for inherited index names and doc types -* Added a `Elasticsearch::Model.settings` method -* Changed the naming inheritance logic to use `Elasticsearch::Model.settings` -* Added information about the `settings` method and the `inheritance_enabled` setting into the README -* Disable "verbose" and "warnings" in integration tests -* Added code for establishing ActiveRecord connections to test classes -* Reorganized the class definitions in the integration tests -* Moved `require` within unit test to the top of the file -* Added ActiveRecord 5 support to integration test configuration -* Fixed records sorting with ActiveRecord 5.x -* Added, that `add_index` for ActiveRecord models is only called when it doesn't exist already -* Use `records.__send__ :load` instead of `records.load` in the ActiveRecord adapter -* Call `Kaminari::Hooks.init` only when available -* Fixed the deprecation messages for `raise_in_transactional_callbacks` -* Fixed the deprecation messages for `timestamps` in migrations in integration tests -* Fixed the naming for the indexing integration tests -* Fixed the failing integration tests for ActiveRecord associations -* Fixed integration tests for ActiveRecord pagination -* Added the `rake bundle:install` Rake task to install dependencies for all gemfiles -* Run unit tests against all Gemfiles -* Updated dependencies in gemspec -* Relaxed the dependency on the "elasticsearch" gem -* Fixed the completion example for ActiveRecord for Elasticsearch 5 -* Added an example with Edge NGram mapping for auto-completion -* Expanded the example for indexing and searching ActiveRecord associations -* Added an example for source filtering to the ActiveRecord associations example -* Fixed a typo in the README -* Changed the default mapping type to `text` -* Added a `HashWrapper` class to wrap Hash structures instead of raw `Hashie::Mash` -* Call `Hashie.disable_warnings` method in Response wrappers -* Added, that `HashWrapper`, a sub-class of `Hashie::Mash` is used -* Updated the configuration for required routing in the integration test -* Fixed incorrect name for the parent/child integration test -* Fixed incorrect mapping configuration in the integration tests -* Allow passing the index settings and mappings as arguments to `create_index!` -* Added instructions about creating the index into the README -* Updated the "completion suggester" example - -### Persistence - -* Updated dependencies in gemspec -* Updated dependencies in gemspec -* Relaxed the dependency on the "elasticsearch" gem -* Use `text` instead of `string` for the data types -* Changed the default mapping type to `text` -* Removed the `search_type=scan` in the `find_in_batches` method -* Updated the `count` method in the "repository" module -* Updated the "update by script" integration test for Elasticsearch 5 -* Added, that `HashWrapper`, a sub-class of `Hashie::Mash` is used -* Updated the "Notes" example application for Elasticsearch 5.x -* Updated the "Music" example application for Elasticsearch 5.x -* Updated the URLs in the "Music" application template -* Updated the Git URLs in the "Notes" example application - -### Ruby on Rails - -* Updated the application templates to support Rails 5 & Elasticsearch 5 -* Updated the `03-expert` application template to work with Rails 5 -* Updated the application templates to work with README.md instead of README.rdoc -* Updated the installation process in the "01-basic" application template -* Fixed typo in README -* Fix typo in rake import task - -## 0.1.9 - -The last version for the old versioning scheme -- please see the Git commit log -at https://github.com/elastic/elasticsearch-rails/commits/v0.1.9 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 161dff67d..11a3c797b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,11 +1,8 @@ -The process for contributing to any of the [Elasticsearch](https://github.com/elasticsearch) repositories is similar: +The process for contributing is: 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. -3. **Sign the contributor license agreement.** -Please make sure you have signed the [Contributor License Agreement](https://www.elastic.co/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. +3. 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″. diff --git a/Gemfile b/Gemfile index 255f70850..59b32a716 100644 --- a/Gemfile +++ b/Gemfile @@ -18,7 +18,7 @@ source 'https://rubygems.org' gem "rake", "~> 12" -gem "elasticsearch" +gem "opensearch-ruby", '~> 2.0' gem "pry" gem "ansi" gem "cane" diff --git a/README.md b/README.md index 615c7a01e..cb37f94ba 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ -# Elasticsearch +# OpenSearch -[![Ruby 2.7](https://github.com/elastic/elasticsearch-rails/workflows/Ruby%202.7/badge.svg)](https://github.com/elastic/elasticsearch-rails/actions) -[![Ruby 2.6](https://github.com/elastic/elasticsearch-rails/workflows/Ruby%202.6/badge.svg)](https://github.com/elastic/elasticsearch-rails/actions) -[![Ruby 2.5](https://github.com/elastic/elasticsearch-rails/workflows/Ruby%202.5/badge.svg)](https://github.com/elastic/elasticsearch-rails/actions) -[![Ruby 2.4](https://github.com/elastic/elasticsearch-rails/workflows/Ruby%202.4/badge.svg)](https://github.com/elastic/elasticsearch-rails/actions) -[![JRuby](https://github.com/elastic/elasticsearch-rails/workflows/JRuby/badge.svg)](https://github.com/elastic/elasticsearch-rails/actions) -[![Code Climate](https://codeclimate.com/github/elastic/elasticsearch-rails/badges/gpa.svg)](https://codeclimate.com/github/elastic/elasticsearch-rails) +[![Ruby 2.7](https://github.com/compliance-innovations/opensearch-rails/workflows/Ruby%202.7/badge.svg)](https://github.com/compliance-innovations/opensearch-rails/actions) +[![Ruby 2.6](https://github.com/compliance-innovations/opensearch-rails/workflows/Ruby%202.6/badge.svg)](https://github.com/compliance-innovations/opensearch-rails/actions) +[![Ruby 2.5](https://github.com/compliance-innovations/opensearch-rails/workflows/Ruby%202.5/badge.svg)](https://github.com/compliance-innovations/opensearch-rails/actions) +[![Ruby 2.4](https://github.com/compliance-innovations/opensearch-rails/workflows/Ruby%202.4/badge.svg)](https://github.com/compliance-innovations/opensearch-rails/actions) +[![JRuby](https://github.com/compliance-innovations/opensearch-rails/workflows/JRuby/badge.svg)](https://github.com/compliance-innovations/opensearch-rails/actions) -This repository contains various Ruby and Rails integrations for [Elasticsearch](http://elasticsearch.org): +This repository contains various Ruby and Rails integrations for [OpenSearch](https://opensearch.org/). This is a fork +of [elasticsearch-rails v7.2.1](https://github.com/elastic/elasticsearch-rails/tree/v7.2.1). +Functionalities include: * ActiveModel integration with adapters for ActiveRecord and Mongoid * _Repository pattern_ based persistence layer for Ruby objects * Enumerable-based wrapper for search results @@ -19,21 +20,21 @@ This repository contains various Ruby and Rails integrations for [Elasticsearch] * Integration with Rails' instrumentation framework * Templates for generating example Rails application -Elasticsearch client and Ruby API is provided by the -**[elasticsearch-ruby](https://github.com/elastic/elasticsearch-ruby)** project. +OpenSearch client and Ruby API is provided by the +**[opensearch-ruby](https://github.com/opensearch-project/opensearch-ruby)** project. ## Installation -Install each library from [Rubygems](https://rubygems.org/gems/elasticsearch): +Install each library from [Rubygems](https://rubygems.org/gems/opensearch): - gem install elasticsearch-model - gem install elasticsearch-rails + gem install opensearch-model + gem install opensearch-rails To use an unreleased version, add it to your `Gemfile` for [Bundler](http://bundler.io): ```ruby -gem 'elasticsearch-model', github: 'elastic/elasticsearch-rails', branch: '5.x' -gem 'elasticsearch-rails', github: 'elastic/elasticsearch-rails', branch: '5.x' +gem 'opensearch-model', github: 'compliance-innovations/opensearch-rails', branch: '5.x' +gem 'opensearch-rails', github: 'compliance-innovations/opensearch-rails', branch: '5.x' ``` ## Compatibility @@ -42,79 +43,73 @@ The libraries are compatible with Ruby 2.4 and higher. We follow Ruby’s own maintenance policy and officially support all currently maintained versions per [Ruby Maintenance Branches](https://www.ruby-lang.org/en/downloads/branches/). -The version numbers follow the Elasticsearch major versions. Currently the `main` branch is compatible with version `7.x` of the Elasticsearch stack. **We haven't tested and updated the code for Elasticsearch `8.0` yet**. +The version numbers follow the OpenSearch major versions. Currently the `main` branch is compatible with version `2.x` of the OpenSearch stack. -| Rubygem | | Elasticsearch | +| Rubygem | | OpenSearch | |:-------------:|:-:| :-----------: | -| 0.1 | → | 1.x | -| 2.x | → | 2.x | -| 5.x | → | 5.x | -| 6.x | → | 6.x | -| main | → | 7.x | - -Check out [Elastic product end of life dates](https://www.elastic.co/support/eol) to learn which releases are still actively supported and tested. +| main | → | 2.x | ## Usage This project is split into three separate gems: -* [**`elasticsearch-model`**](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-model), +* [**`opensearch-model`**](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-model), which contains search integration for Ruby/Rails models such as ActiveRecord::Base and Mongoid, -* [**`elasticsearch-persistence`**](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-persistence), +* [**`opensearch-persistence`**](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-persistence), which provides a standalone persistence layer for Ruby/Rails objects and models -* [**`elasticsearch-rails`**](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-rails), +* [**`opensearch-rails`**](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-rails), which contains various features for Ruby on Rails applications Example of a basic integration into an ActiveRecord-based model: ```ruby -require 'elasticsearch/model' +require 'opensearch/model' class Article < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks end # Index creation right at import time is not encouraged. # Typically, you would call create_index! asynchronously (e.g. in a cron job) # However, we are adding it here so that this usage example can run correctly. -Article.__elasticsearch__.create_index! +Article.__opensearch__.create_index! Article.import @articles = Article.search('foobar').records ``` You can generate a simple Ruby on Rails application with a single command -(see the [other available templates](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-rails#rails-application-templates)). You'll need to have an Elasticsearch cluster running on your system before generating the app. The easiest way of getting this set up is by running it with Docker with this command: +(see the [other available templates](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-rails#rails-application-templates)). You'll need to have an OpenSearch cluster running on your system before generating the app. The easiest way of getting this set up is by running it with Docker with this command: ```bash docker run \ - --name elasticsearch-rails-searchapp \ + --name opensearch-rails-searchapp \ --publish 9200:9200 \ --env "discovery.type=single-node" \ - --env "cluster.name=elasticsearch-rails" \ + --env "cluster.name=opensearch-rails" \ --env "cluster.routing.allocation.disk.threshold_enabled=false" \ --rm \ - docker.elastic.co/elasticsearch/elasticsearch-oss:7.6.0 + opensearchproject/opensearch:1.3.0 ``` -Once Elasticsearch is running, you can generate the simple app with this command: +Once OpenSearch is running, you can generate the simple app with this command: ```bash -rails new searchapp --skip --skip-bundle --template https://raw.github.com/elasticsearch/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/01-basic.rb +rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/01-basic.rb ``` -Example of using Elasticsearch as a repository for a Ruby domain object: +Example of using OpenSearch as a repository for a Ruby domain object: ```ruby class Article attr_accessor :title end -require 'elasticsearch/persistence' -repository = Elasticsearch::Persistence::Repository.new +require 'opensearch/persistence' +repository = OpenSearch::Persistence::Repository.new repository.save Article.new(title: 'Test') # POST http://localhost:9200/repository/article @@ -125,29 +120,29 @@ repository.save Article.new(title: 'Test') ### Model -* [[README]](https://github.com/elastic/elasticsearch-rails/blob/main/elasticsearch-model/README.md) -* [[Documentation]](http://rubydoc.info/gems/elasticsearch-model/) -* [[Test Suite]](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-model/spec/elasticsearch/model) +* [[README]](https://github.com/compliance-innovations/opensearch-rails/blob/main/opensearch-model/README.md) +* [[Documentation]](http://rubydoc.info/gems/opensearch-model/) +* [[Test Suite]](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-model/spec/opensearch/model) ### Persistence -* [[README]](https://github.com/elastic/elasticsearch-rails/blob/main/elasticsearch-persistence/README.md) -* [[Documentation]](http://rubydoc.info/gems/elasticsearch-persistence/) -* [[Test Suite]](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-persistence/spec) +* [[README]](https://github.com/compliance-innovations/opensearch-rails/blob/main/opensearch-persistence/README.md) +* [[Documentation]](http://rubydoc.info/gems/opensearch-persistence/) +* [[Test Suite]](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-persistence/spec) ### Rails -* [[README]](https://github.com/elastic/elasticsearch-rails/blob/main/elasticsearch-rails/README.md) -* [[Documentation]](http://rubydoc.info/gems/elasticsearch-rails) -* [[Test Suite]](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-rails/spec) +* [[README]](https://github.com/compliance-innovations/opensearch-rails/blob/main/opensearch-rails/README.md) +* [[Documentation]](http://rubydoc.info/gems/opensearch-rails) +* [[Test Suite]](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-rails/spec) ## Development To work on the code, clone the repository and install all dependencies first: ``` -git clone https://github.com/elastic/elasticsearch-rails.git -cd elasticsearch-rails/ +git clone https://github.com/compliance-innovations/opensearch-rails.git +cd opensearch-rails/ bundle install rake bundle:install ``` @@ -160,7 +155,7 @@ You can also unit, integration, or both tests for all sub-projects from the top- rake test:all -The test suite expects an Elasticsearch cluster running on port 9250, and **will delete all the data**. +The test suite expects an OpenSearch cluster running on port 9250, and **will delete all the data**. ## License diff --git a/Rakefile b/Rakefile index 9b3347f86..d36de2aa8 100644 --- a/Rakefile +++ b/Rakefile @@ -16,10 +16,10 @@ # under the License. require 'pathname' -require 'elasticsearch' +require 'opensearch-ruby' -subprojects = ['elasticsearch-rails', 'elasticsearch-persistence'] -subprojects << 'elasticsearch-model' unless defined?(JRUBY_VERSION) +subprojects = ['opensearch-rails', 'opensearch-persistence'] +subprojects << 'opensearch-model' unless defined?(JRUBY_VERSION) __current__ = Pathname(File.expand_path(__dir__)) @@ -28,7 +28,7 @@ def admin_client transport_options = {} test_suite = ENV['TEST_SUITE'].freeze - if hosts = ENV['TEST_ES_SERVER'] || ENV['ELASTICSEARCH_HOSTS'] + if hosts = ENV['TEST_ES_SERVER'] || ENV['OPENSEARCH_HOSTS'] split_hosts = hosts.split(',').map do |host| /(http\:\/\/)?(\S+)/.match(host)[2] end @@ -46,7 +46,7 @@ def admin_client else url = "http://#{host || 'localhost'}:#{port || 9200}" end - Elasticsearch::Client.new(host: url, transport_options: transport_options) + OpenSearch::Client.new(host: url, transport_options: transport_options) end end @@ -82,7 +82,7 @@ namespace :bundle do subprojects.each do |project| sh "rm -f #{__current__.join(project)}/Gemfile.lock" end - sh "rm -f #{__current__.join('elasticsearch-model/gemfiles')}/*.lock" + sh "rm -f #{__current__.join('opensearch-model/gemfiles')}/*.lock" end sh "rm -f Gemfile.lock" end @@ -115,26 +115,26 @@ namespace :test do end desc "Run integration tests in all subprojects" - task integration: :setup_elasticsearch do - # 1/ elasticsearch-model + task integration: :setup_opensearch do + # 1/ opensearch-model # puts '-'*80 - sh "cd #{__current__.join('elasticsearch-model')} && unset BUNDLE_GEMFILE &&" + + sh "cd #{__current__.join('opensearch-model')} && unset BUNDLE_GEMFILE &&" + %Q| #{ ENV['TEST_BUNDLE_GEMFILE'] ? "BUNDLE_GEMFILE='#{ENV['TEST_BUNDLE_GEMFILE']}'" : '' }| + " bundle exec rake test:integration" puts "\n" - # 2/ elasticsearch-persistence + # 2/ opensearch-persistence # puts '-'*80 - sh "cd #{__current__.join('elasticsearch-persistence')} && unset BUNDLE_GEMFILE &&" + + sh "cd #{__current__.join('opensearch-persistence')} && unset BUNDLE_GEMFILE &&" + " bundle exec rake test:integration" puts "\n" - # 3/ elasticsearch-rails + # 3/ opensearch-rails # puts '-'*80 - sh "cd #{__current__.join('elasticsearch-rails')} && unset BUNDLE_GEMFILE &&" + + sh "cd #{__current__.join('opensearch-rails')} && unset BUNDLE_GEMFILE &&" + " bundle exec rake test:integration" puts "\n" end @@ -151,9 +151,9 @@ namespace :test do end end -desc "Wait for elasticsearch cluster to be in green state" +desc "Wait for opensearch cluster to be in green state" task :wait_for_green do - require 'elasticsearch' + require 'opensearch-ruby' ready = nil 5.times do |i| @@ -163,15 +163,15 @@ task :wait_for_green do ready = true break end - rescue Elasticsearch::Transport::Transport::Errors::RequestTimeout => ex + rescue OpenSearch::Transport::Transport::Errors::RequestTimeout => ex puts "Couldn't confirm green status.\n#{ex.inspect}." rescue Faraday::ConnectionFailed => ex - puts "Couldn't connect to Elasticsearch.\n#{ex.inspect}." + puts "Couldn't connect to OpenSearch.\n#{ex.inspect}." sleep(30) end end unless ready - puts "Couldn't connect to Elasticsearch, aborting program." + puts "Couldn't connect to OpenSearch, aborting program." exit(1) end end @@ -232,7 +232,7 @@ task :update_version, :old, :new do |_, args| puts "\n\n", "= CHANGELOG ".ansi(:faint) + ('='*88).ansi(:faint), "\n" - log = `git --no-pager log --reverse --no-color --pretty='* %s' HEAD --not v#{args[:old]} elasticsearch-*`.split("\n") + log = `git --no-pager log --reverse --no-color --pretty='* %s' HEAD --not v#{args[:old]} opensearch-*`.split("\n") puts log.join("\n") @@ -288,7 +288,7 @@ task :update_version, :old, :new do |_, args| puts "\n\n", "= DIFF ".ansi(:faint) + ('='*93).ansi(:faint) - diff = `git --no-pager diff --patch --word-diff=color --minimal elasticsearch-*`.split("\n") + diff = `git --no-pager diff --patch --word-diff=color --minimal opensearch-*`.split("\n") puts diff .reject { |l| l =~ /^\e\[1mdiff \-\-git/ } @@ -300,7 +300,7 @@ task :update_version, :old, :new do |_, args| puts "\n\n", "= COMMIT ".ansi(:faint) + ('='*91).ansi(:faint), "\n" - puts 'git add CHANGELOG.md elasticsearch-*', + puts 'git add CHANGELOG.md opensearch-*', "git commit --verbose --message='Release #{args[:new]}' --edit", 'rake release' "\n" diff --git a/elasticsearch-model/CHANGELOG.md b/elasticsearch-model/CHANGELOG.md deleted file mode 100644 index 1b2803383..000000000 --- a/elasticsearch-model/CHANGELOG.md +++ /dev/null @@ -1,74 +0,0 @@ -## 0.1.9 - -* Added a `suggest` method to wrap the suggestions in response -* Added the `:includes` option to Adapter::ActiveRecord::Records for eagerly loading associated models -* Delegated `max_pages` method properly for Kaminari's `next_page` -* Fixed `#dup` behaviour for Elasticsearch::Model -* Fixed typos in the README and examples - -## 0.1.8 - -* Added "default per page" methods for pagination with multi model searches -* Added a convenience accessor for the `aggregations` part of response -* Added a full example with mapping for the completion suggester -* Added an integration test for paginating multiple models -* Added proper support for the new "multi_fields" in the mapping DSL -* Added the `no_timeout` option for `__find_in_batches` in the Mongoid adapter -* Added, that index settings can be loaded from any object that responds to `:read` -* Added, that index settings/mappings can be loaded from a YAML or JSON file -* Added, that String pagination parameters are converted to numbers -* Added, that empty block is not required for setting mapping options -* Added, that on MyModel#import, an exception is raised if the index does not exists -* Changed the Elasticsearch port in the Mongoid example to 9200 -* Cleaned up the tests for multiple fields/properties in mapping DSL -* Fixed a bug where continuous `#save` calls emptied the `@__changed_attributes` variable -* Fixed a buggy test introduced in #335 -* Fixed incorrect deserialization of records in the Multiple adapter -* Fixed incorrect examples and documentation -* Fixed unreliable order of returned results/records in the integration test for the multiple adapter -* Fixed, that `param_name` is used when paginating with WillPaginate -* Fixed the problem where `document_type` configuration was not propagated to mapping [6 months ago by Miguel Ferna -* Refactored the code in `__find_in_batches` to use Enumerable#each_slice -* Refactored the string queries in multiple_models_test.rb to avoid quote escaping - -## 0.1.7 - -* Improved examples and instructions in README and code annotations -* Prevented index methods to swallow all exceptions -* Added the `:validate` option to the `save` method for models -* Added support for searching across multiple models (elastic/elasticsearch-rails#345), - including documentation, examples and tests - -## 0.1.6 - -* Improved documentation -* Added dynamic getter/setter (block/proc) for `MyModel.index_name` -* Added the `update_document_attributes` method -* Added, that records to import can be limited by the `query` option - -## 0.1.5 - -* Improved documentation -* Fixes and improvements to the "will_paginate" integration -* Added a `:preprocess` option to the `import` method -* Changed, that attributes are fetched from `as_indexed_json` in the `update_document` method -* Added an option to the import method to return an array of error messages instead of just count -* Fixed many problems with dependency hell -* Fixed tests so they run on Ruby 2.2 - -## 0.1.2 - -* Properly delegate existence methods like `result.foo?` to `result._source.foo` -* Exception is raised when `type` is not passed to Mappings#new -* Allow passing an ActiveRecord scope to the `import` method -* Added, that `each_with_hit` and `map_with_hit` in `Elasticsearch::Model::Response::Records` call `to_a` -* Added support for [`will_paginate`](https://github.com/mislav/will_paginate) pagination library -* Added the ability to transform models during indexing -* Added explicit `type` and `id` methods to Response::Result, aliasing `_type` and `_id` - -## 0.1.1 - -* Improved documentation and tests -* Fixed Kaminari implementation bugs and inconsistencies - -## 0.1.0 (Initial Version) diff --git a/elasticsearch-model/gemfiles/3.0.gemfile b/elasticsearch-model/gemfiles/3.0.gemfile deleted file mode 100644 index 1641023d7..000000000 --- a/elasticsearch-model/gemfiles/3.0.gemfile +++ /dev/null @@ -1,35 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# Usage: -# -# $ BUNDLE_GEMFILE=./gemfiles/3.0.gemfile bundle install -# $ BUNDLE_GEMFILE=./gemfiles/3.0.gemfile bundle exec rake test:integration - -source 'https://rubygems.org' - -gemspec path: '../' - -gem 'activemodel', '>= 3.0' -gem 'activerecord', '~> 3.2' -gem 'mongoid', '>= 3.0' -gem 'sqlite3', '> 1.3', '< 1.4' unless defined?(JRUBY_VERSION) - -group :development, :testing do - gem 'rspec' - gem 'pry-nav' -end \ No newline at end of file diff --git a/elasticsearch-model/gemfiles/4.0.gemfile b/elasticsearch-model/gemfiles/4.0.gemfile deleted file mode 100644 index 944568fce..000000000 --- a/elasticsearch-model/gemfiles/4.0.gemfile +++ /dev/null @@ -1,36 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# Usage: -# -# $ BUNDLE_GEMFILE=./gemfiles/4.0.gemfile bundle install -# $ BUNDLE_GEMFILE=./gemfiles/4.0.gemfile bundle exec rake test:integration - -source 'https://rubygems.org' - -gemspec path: '../' - -gem 'activemodel', '~> 4' -gem 'activerecord', '~> 4' -gem 'mongoid', '~> 5' -gem 'sqlite3', '> 1.3', '< 1.4' unless defined?(JRUBY_VERSION) - -group :development, :testing do - gem 'bigdecimal', '~> 1' - gem 'pry-nav' - gem 'rspec' -end diff --git a/elasticsearch-persistence/CHANGELOG.md b/elasticsearch-persistence/CHANGELOG.md deleted file mode 100644 index 7d25720bb..000000000 --- a/elasticsearch-persistence/CHANGELOG.md +++ /dev/null @@ -1,43 +0,0 @@ -## 0.1.9 - -* Added, that raw `_source` is accessible from a model instance - -## 0.1.8 - -* Added `cluster.health wait_for_status: 'yellow'` to Repository integration test -* Fixed tests for the updates to the `update` method for Persistence::Model -* Fixed timestamp tests -* Fixed typos and broken links in documentation, fixed examples -* Fixed, that `MyModel#save` does in fact persist `updated_at` attribute -* Fixed, that `options` have not been passed to gateway in MyModel#update -* Short-circuit the operation and return `false` when the model is not valid -* Fixed the problem where `document_type` configuration was not propagated to mapping - - -## 0.1.7 - -* Added an integration test for the `MyModel.all` method -* Improved the "music" example application - -## 0.1.6 - -* Improved documentation -* Refactored the Rails' forms date conversions into a module method -* Changed, that search requests are executed through a `SearchRequest` class - -## 0.1.5 - -* Improved documentation -* Added `@mymodel.id=` setter method - -## 0.1.4 - -* Added the Elasticsearch::Persistence::Model feature - -## 0.1.3 - -* Released the "elasticsearch-persistence" Rubygem - -## 0.0.1 - -* Initial infrastructure for the gem diff --git a/elasticsearch-persistence/spec/repository/search_spec.rb b/elasticsearch-persistence/spec/repository/search_spec.rb deleted file mode 100644 index 8e94ecc1d..000000000 --- a/elasticsearch-persistence/spec/repository/search_spec.rb +++ /dev/null @@ -1,198 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -require 'spec_helper' - -describe Elasticsearch::Persistence::Repository::Search do - - after do - begin; repository.delete_index!; rescue; end - end - - describe '#search' do - - let(:repository) do - DEFAULT_REPOSITORY - end - - context 'when the repository does not have a type set' do - - before do - repository.save({ name: 'user' }, refresh: true) - end - - context 'when a query definition is provided as a hash' do - - it 'uses the default document type' do - expect(repository.search({ query: { match: { name: 'user' } } }).first).to eq('name' => 'user') - end - end - - context 'when a query definition is provided as a string' do - - it 'uses the default document type' do - expect(repository.search('user').first).to eq('name' => 'user') - end - end - - context 'when the query definition is neither a String nor a Hash' do - - it 'raises an ArgumentError' do - expect { - repository.search(1) - }.to raise_exception(ArgumentError) - end - end - - context 'when options are provided' do - - context 'when a query definition is provided as a hash' do - - it 'uses the default document type' do - expect(repository.search({ query: { match: { name: 'user' } } }, type: 'other').first).to be_nil - end - end - - context 'when a query definition is provided as a string' do - - it 'uses the default document type' do - expect(repository.search('user', type: 'other').first).to be_nil - end - end - - context 'when the query definition is neither a String nor a Hash' do - - it 'raises an ArgumentError' do - expect { - repository.search(1) - }.to raise_exception(ArgumentError) - end - end - end - end - - context 'when the repository does have a type set' do - - let(:repository) do - MyTestRepository.new(document_type: 'other_note') - end - - before do - repository.save({ name: 'user' }, refresh: true) - end - - context 'when options are provided' do - - context 'when a query definition is provided as a hash' do - - it 'uses the options' do - expect(repository.search({ query: { match: { name: 'user' } } }, type: 'other').first).to be_nil - end - end - - context 'when a query definition is provided as a string' do - - it 'uses the options' do - expect(repository.search('user', type: 'other').first).to be_nil - end - end - - context 'when the query definition is neither a String nor a Hash' do - - it 'raises an ArgumentError' do - expect { - repository.search(1) - }.to raise_exception(ArgumentError) - end - end - end - end - end - - describe '#count' do - - context 'when the repository does not have a type set' do - - let(:repository) do - DEFAULT_REPOSITORY - end - - before do - repository.save({ name: 'user' }, refresh: true) - end - - context 'when a query definition is provided as a hash' do - - it 'uses the default document type' do - expect(repository.count({ query: { match: { name: 'user' } } })).to eq(1) - end - end - - context 'when a query definition is provided as a string' do - - it 'uses the default document type' do - expect(repository.count('user')).to eq(1) - end - end - - context 'when options are provided' do - - context 'when a query definition is provided as a hash' do - - it 'uses the options' do - expect(repository.count({ query: { match: { name: 'user' } } }, type: 'other')).to eq(0) - end - end - - context 'when a query definition is provided as a string' do - - it 'uses the options' do - expect(repository.count('user', type: 'other')).to eq(0) - end - end - end - end - - context 'when the repository does have a type set' do - - let(:repository) do - MyTestRepository.new(document_type: 'other_note') - end - - before do - repository.save({ name: 'user' }, refresh: true) - end - - context 'when options are provided' do - - context 'when a query definition is provided as a hash' do - - it 'uses the options' do - expect(repository.count({ query: { match: { name: 'user' } } }, type: 'other')).to eq(0) - end - end - - context 'when a query definition is provided as a string' do - - it 'uses the options' do - expect(repository.count('user', type: 'other')).to eq(0) - end - end - end - end - end -end diff --git a/elasticsearch-rails/CHANGELOG.md b/elasticsearch-rails/CHANGELOG.md deleted file mode 100644 index 5bb4e13bd..000000000 --- a/elasticsearch-rails/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -## 0.1.9 - -* Added checks for proper launch order and other updates to the example application templates -* Updated the example application to work with Elasticsearch 2.x -* Used the `suggest` method instead of `response['suggest']` in the application template - -## 0.1.8 - -* Added an example application template that loads settings from a file -* Added missing require in the seeds.rb file for the expert template -* Fixed double include of the aliased method (execute_without_instrumentation) -* Fixed the error when getting the search_controller_test.rb asset in `03-expert.rb` template -* Updated URLs for getting raw assets from Github in the `03-expert.rb` template - -## 0.1.7 - -* Updated dependencies for the gem and example applications -* Fixed various small errors in the `01-basic.rb` template -* Fixed error when inserting the Kaminari gem into Gemfile in the 02-pretty.rb template -* Fixed incorrect regex for adding Rails instrumentation into the application.rb in the `02-pretty.rb` template -* Fixed other small errors in the `02-pretty.rb` template -* Improved and added tests for the generated application from the `02-pretty.rb` template -* Added the `04-dsl.rb` template which uses the `elasticsearch-dsl` gem to build the search definition - -## 0.1.6 - -* Fixed errors in templates for the Rails example applications -* Fixed errors in the importing Rake task -* Refactored and updated the instrumentation support to allow integration with `Persistence::Model` - -## 0.1.5 - -* Fixed an exception when no suggestions were returned in the `03-expert` example application template - -## 0.1.2 - -* Allow passing an ActiveRecord scope to the importing Rake task - -## 0.1.1 - -* Improved the Rake tasks -* Improved the example application templates - -## 0.1.0 (Initial Version) diff --git a/elasticsearch-model/.gitignore b/opensearch-model/.gitignore similarity index 100% rename from elasticsearch-model/.gitignore rename to opensearch-model/.gitignore diff --git a/opensearch-model/CHANGELOG.md b/opensearch-model/CHANGELOG.md new file mode 100644 index 000000000..4e3adb6d2 --- /dev/null +++ b/opensearch-model/CHANGELOG.md @@ -0,0 +1 @@ +## 0.1.0 (Initial Version) diff --git a/elasticsearch-model/Gemfile b/opensearch-model/Gemfile similarity index 91% rename from elasticsearch-model/Gemfile rename to opensearch-model/Gemfile index 5a31c3095..0ff7d5846 100644 --- a/elasticsearch-model/Gemfile +++ b/opensearch-model/Gemfile @@ -17,10 +17,11 @@ source 'https://rubygems.org' -# Specify your gem's dependencies in elasticsearch-model.gemspec +# Specify your gem's dependencies in opensearch-model.gemspec gemspec group :development, :testing do gem 'pry-nav' gem 'rspec' + gem 'byebug' end diff --git a/elasticsearch-model/LICENSE.txt b/opensearch-model/LICENSE.txt similarity index 100% rename from elasticsearch-model/LICENSE.txt rename to opensearch-model/LICENSE.txt diff --git a/elasticsearch-model/README.md b/opensearch-model/README.md similarity index 72% rename from elasticsearch-model/README.md rename to opensearch-model/README.md index a5345b4b9..cb8e99e75 100644 --- a/elasticsearch-model/README.md +++ b/opensearch-model/README.md @@ -1,37 +1,33 @@ -# Elasticsearch::Model +# OpenSearch::Model -The `elasticsearch-model` library builds on top of the the [`elasticsearch`](https://github.com/elastic/elasticsearch-ruby) library. +The `opensearch-model` library builds on top of the the [`opensearch`](https://github.com/compliance-innovations/opensearch-ruby) library. -It aims to simplify integration of Ruby classes ("models"), commonly found e.g. in [Ruby on Rails](http://rubyonrails.org) applications, with the [Elasticsearch](https://www.elastic.co) search and analytics engine. +It aims to simplify integration of Ruby classes ("models"), commonly found e.g. in [Ruby on Rails](http://rubyonrails.org) applications, with the [OpenSearch](https://opensearch.org/) search and analytics engine. ## Compatibility This library is compatible with Ruby 2.4 and higher. -The library version numbers follow the Elasticsearch major versions. The `main` branch is compatible with the latest Elasticsearch stack stable release. +The library version numbers follow the OpenSearch major versions. The `main` branch is compatible with the latest OpenSearch stack stable release. -| Rubygem | | Elasticsearch | +| Rubygem | | OpenSearch | |:-------------:|:-:| :-----------: | -| 0.1 | → | 1.x | -| 2.x | → | 2.x | -| 5.x | → | 5.x | -| 6.x | → | 6.x | -| main | → | 7.x | +| main | → | 2.x | ## Installation Install the package from [Rubygems](https://rubygems.org): - gem install elasticsearch-model + gem install opensearch-model To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://bundler.io): - gem 'elasticsearch-model', git: 'git://github.com/elastic/elasticsearch-rails.git', branch: '5.x' + gem 'opensearch-model', git: 'git://github.com/compliance-innovations/opensearch-rails.git', branch: '5.x' or install it from a source code checkout: - git clone https://github.com/elastic/elasticsearch-rails.git - cd elasticsearch-rails/elasticsearch-model + git clone https://github.com/compliance-innovations/opensearch-rails.git + cd opensearch-rails/opensearch-model bundle install rake install @@ -54,22 +50,22 @@ Article.create title: 'Swift green frogs' ### Setup -To add the Elasticsearch integration for this model, require `elasticsearch/model` +To add the OpenSearch integration for this model, require `opensearch/model` and include the main module in your class: ```ruby -require 'elasticsearch/model' +require 'opensearch/model' class Article < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model end ``` -This will extend the model with functionality related to Elasticsearch. +This will extend the model with functionality related to OpenSearch. #### Feature Extraction Pattern -Instead of including the `Elasticsearch::Model` module directly in your model, you can include it in a "concern" or "trait" module, which is quite common pattern in Rails applications, using e.g. `ActiveSupport::Concern` as the instrumentation: +Instead of including the `OpenSearch::Model` module directly in your model, you can include it in a "concern" or "trait" module, which is quite common pattern in Rails applications, using e.g. `ActiveSupport::Concern` as the instrumentation: ```ruby # In: app/models/concerns/searchable.rb @@ -78,7 +74,7 @@ module Searchable extend ActiveSupport::Concern included do - include Elasticsearch::Model + include OpenSearch::Model mapping do # ... @@ -97,51 +93,51 @@ class Article end ``` -#### The `__elasticsearch__` Proxy +#### The `__opensearch__` Proxy -The `Elasticsearch::Model` module contains a big amount of class and instance methods to provide +The `OpenSearch::Model` module contains a big amount of class and instance methods to provide all its functionality. To prevent polluting your model namespace, this functionality is primarily -available via the `__elasticsearch__` class and instance level proxy methods; -see the `Elasticsearch::Model::Proxy` class documentation for technical information. +available via the `__opensearch__` class and instance level proxy methods; +see the `OpenSearch::Model::Proxy` class documentation for technical information. The module will include important methods, such as `search`, into the class or module only when they haven't been defined already. Following two calls are thus functionally equivalent: ```ruby -Article.__elasticsearch__.search 'fox' +Article.__opensearch__.search 'fox' Article.search 'fox' ``` -See the `Elasticsearch::Model` module documentation for technical information. +See the `OpenSearch::Model` module documentation for technical information. -### The Elasticsearch client +### The OpenSearch client -The module will set up a [client](https://github.com/elastic/elasticsearch-ruby/tree/main/elasticsearch), -connected to `localhost:9200`, by default. You can access and use it as any other `Elasticsearch::Client`: +The module will set up a [client](https://github.com/opensearch-project/opensearch-ruby/tree/main/opensearch), +connected to `localhost:9200`, by default. You can access and use it as any other `OpenSearch::Client`: ```ruby -Article.__elasticsearch__.client.cluster.health -# => { "cluster_name"=>"elasticsearch", "status"=>"yellow", ... } +Article.__opensearch__.client.cluster.health +# => { "cluster_name"=>"opensearch", "status"=>"yellow", ... } ``` To use a client with different configuration, just set up a client for the model: ```ruby -Article.__elasticsearch__.client = Elasticsearch::Client.new host: 'api.server.org' +Article.__opensearch__.client = OpenSearch::Client.new host: 'api.server.org' ``` Or configure the client for all models: ```ruby -Elasticsearch::Model.client = Elasticsearch::Client.new log: true +OpenSearch::Model.client = OpenSearch::Client.new log: true ``` You might want to do this during your application bootstrap process, e.g. in a Rails initializer. Please refer to the -[`elasticsearch-transport`](https://github.com/elastic/elasticsearch-ruby/tree/main/elasticsearch-transport) +[`opensearch-transport`](https://github.com/opensearch-project/opensearch-ruby/tree/main/opensearch-transport) library documentation for all the configuration options, and to the -[`elasticsearch-api`](http://rubydoc.info/gems/elasticsearch-api) library documentation +[`opensearch-api`](https://github.com/opensearch-project/opensearch-ruby/tree/main/opensearch-api) library documentation for information about the Ruby client API. ### Importing the data @@ -181,7 +177,7 @@ response.results.first._source.title #### Search results -The returned `response` object is a rich wrapper around the JSON returned from Elasticsearch, +The returned `response` object is a rich wrapper around the JSON returned from OpenSearch, providing access to response metadata and the actual results ("hits"). Each "hit" is wrapped in the `Result` class, and provides method access @@ -194,7 +190,7 @@ response.results.map { |r| r._source.title } # => ["Quick brown fox", "Fast black dogs"] response.results.select { |r| r.title =~ /^Q/ } -# => [#{"title"=>"Quick brown fox"}}>] +# => [#{"title"=>"Quick brown fox"}}>] ``` In fact, the `response` object will delegate `Enumerable` methods to `results`: @@ -213,7 +209,7 @@ response.to_a.last.title #### Search results as database records -Instead of returning documents from Elasticsearch, the `records` method will return a collection +Instead of returning documents from OpenSearch, the `records` method will return a collection of model instances, fetched from the primary database, ordered by score: ```ruby @@ -247,8 +243,8 @@ response.records.order(:title).to_a The `records` method returns the real instances of your model, which is useful when you want to access your model methods -- at the expense of slowing down your application, of course. -In most cases, working with `results` coming from Elasticsearch is sufficient, and much faster. See the -[`elasticsearch-rails`](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-rails) +In most cases, working with `results` coming from OpenSearch is sufficient, and much faster. See the +[`opensearch-rails`](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-rails) library for more information about compatibility with the Ruby on Rails framework. When you want to access both the database `records` and search `results`, use the `each_with_hit` @@ -265,19 +261,19 @@ response.records.each_with_hit { |record, hit| puts "* #{record.title}: #{hit._s It is possible to search across multiple models with the module method: ```ruby -Elasticsearch::Model.search('fox', [Article, Comment]).results.to_a.map(&:to_hash) +OpenSearch::Model.search('fox', [Article, Comment]).results.to_a.map(&:to_hash) # => [ # {"_index"=>"articles", "_type"=>"article", "_id"=>"1", "_score"=>0.35136628, "_source"=>...}, # {"_index"=>"comments", "_type"=>"comment", "_id"=>"1", "_score"=>0.35136628, "_source"=>...} # ] -Elasticsearch::Model.search('fox', [Article, Comment]).records.to_a +OpenSearch::Model.search('fox', [Article, Comment]).records.to_a # Article Load (0.3ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" IN (1) # Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" IN (1,5) # => [#
, #, ...] ``` -By default, all models which include the `Elasticsearch::Model` module are searched. +By default, all models which include the `OpenSearch::Model` module are searched. NOTE: It is _not_ possible to chain other methods on top of the `records` object, since it is a heterogenous collection, with models potentially backed by different databases. @@ -285,7 +281,7 @@ NOTE: It is _not_ possible to chain other methods on top of the `records` object #### Pagination You can implement pagination with the `from` and `size` search parameters. However, search results can be automatically paginated with the [`kaminari`](http://rubygems.org/gems/kaminari) or [`will_paginate`](https://github.com/mislav/will_paginate) gems. -(The pagination gems must be added before the Elasticsearch gems in your Gemfile, or loaded first in your application.) +(The pagination gems must be added before the OpenSearch gems in your Gemfile, or loaded first in your application.) If Kaminari or WillPaginate is loaded, use the familiar paging methods: @@ -308,12 +304,12 @@ To initialize and include the Kaminari pagination support manually: ```ruby Kaminari::Hooks.init if defined?(Kaminari::Hooks) -Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::Kaminari +OpenSearch::Model::Response::Response.__send__ :include, OpenSearch::Model::Response::Pagination::Kaminari ``` -#### The Elasticsearch DSL +#### The OpenSearch DSL -In most situations, you'll want to pass the search definition in the Elasticsearch [domain-specific language](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html) to the client: +In most situations, you'll want to pass the search definition in the OpenSearch [domain-specific language](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html) to the client: ```ruby response = Article.search query: { match: { title: "Fox Dogs" } }, @@ -343,12 +339,12 @@ response.results.first.title # => "Quick brown fox" ``` -Also, you can use the [**`elasticsearch-dsl`**](https://github.com/elastic/elasticsearch-ruby/tree/main/elasticsearch-dsl) library, which provides a specialized Ruby API for the Elasticsearch Query DSL: +Also, you can use the [**`opensearch-dsl`**](https://github.com/opensearch-project/opensearch-ruby/tree/main/opensearch-dsl) library, which provides a specialized Ruby API for the OpenSearch Query DSL: ```ruby -require 'elasticsearch/dsl' +require 'opensearch/dsl' -query = Elasticsearch::DSL::Search.search do +query = OpenSearch::DSL::Search.search do query do match :title do query 'fox dogs' @@ -364,9 +360,9 @@ response.results.first.title ### Index Configuration For proper search engine function, it's often necessary to configure the index properly. -The `Elasticsearch::Model` integration provides class methods to set up index settings and mappings. +The `OpenSearch::Model` integration provides class methods to set up index settings and mappings. -**NOTE**: Elasticsearch will automatically create an index when a document is indexed, +**NOTE**: OpenSearch will automatically create an index when a document is indexed, with default settings and mappings. Create the index in advance with the `create_index!` method, so your index configuration is respected. @@ -400,8 +396,8 @@ Article.settings.to_hash You can use the defined settings and mappings to create an index with desired configuration: ```ruby -Article.__elasticsearch__.client.indices.delete index: Article.index_name rescue nil -Article.__elasticsearch__.client.indices.create \ +Article.__opensearch__.client.indices.delete index: Article.index_name rescue nil +Article.__opensearch__.client.indices.create \ index: Article.index_name, body: { settings: Article.settings.to_hash, mappings: Article.mappings.to_hash } ``` @@ -409,8 +405,8 @@ Article.__elasticsearch__.client.indices.create \ There's a shortcut available for this common operation (convenient e.g. in tests): ```ruby -Article.__elasticsearch__.create_index! force: true -Article.__elasticsearch__.refresh_index! +Article.__opensearch__.create_index! force: true +Article.__opensearch__.refresh_index! ``` By default, index name and document type will be inferred from your class name, @@ -425,23 +421,23 @@ end ### Updating the Documents in the Index -Usually, we need to update the Elasticsearch index when records in the database are created, updated or deleted; +Usually, we need to update the OpenSearch index when records in the database are created, updated or deleted; use the `index_document`, `update_document` and `delete_document` methods, respectively: ```ruby -Article.first.__elasticsearch__.index_document +Article.first.__opensearch__.index_document # => {"ok"=>true, ... "_version"=>2} ``` #### Automatic Callbacks You can automatically update the index whenever the record changes, by including -the `Elasticsearch::Model::Callbacks` module in your model: +the `OpenSearch::Model::Callbacks` module in your model: ```ruby class Article - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks end Article.first.update_attribute :title, 'Updated!' @@ -454,7 +450,7 @@ The automatic callback on record update keeps track of changes in your model (via [`ActiveModel::Dirty`](http://api.rubyonrails.org/classes/ActiveModel/Dirty.html)-compliant implementation), and performs a _partial update_ when this support is available. -The automatic callbacks are implemented in database adapters coming with `Elasticsearch::Model`. You can easily +The automatic callbacks are implemented in database adapters coming with `OpenSearch::Model`. You can easily implement your own adapter: please see the relevant chapter below. #### Custom Callbacks @@ -464,7 +460,7 @@ by hooking into `after_create`, `after_save`, `after_update` or `after_destroy` ```ruby class Article - include Elasticsearch::Model + include OpenSearch::Model after_save { logger.debug ["Updating document... ", index_document ].join } after_destroy { logger.debug ["Deleting document... ", delete_document].join } @@ -476,22 +472,22 @@ your data against inconsistencies caused by transaction rollbacks: ```ruby class Article < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model after_commit on: [:create] do - __elasticsearch__.index_document if self.published? + __opensearch__.index_document if self.published? end after_commit on: [:update] do if self.published? - __elasticsearch__.update_document + __opensearch__.update_document else - __elasticsearch__.delete_document + __opensearch__.delete_document end end after_commit on: [:destroy] do - __elasticsearch__.delete_document if self.published? + __opensearch__.delete_document if self.published? end end ``` @@ -504,7 +500,7 @@ with a tool like [_Resque_](https://github.com/resque/resque) or [_Sidekiq_](htt ```ruby class Article - include Elasticsearch::Model + include OpenSearch::Model after_save { Indexer.perform_async(:index, self.id) } after_destroy { Indexer.perform_async(:delete, self.id) } @@ -516,10 +512,10 @@ An example implementation of the `Indexer` worker class could look like this: ```ruby class Indexer include Sidekiq::Worker - sidekiq_options queue: 'elasticsearch', retry: false + sidekiq_options queue: 'opensearch', retry: false Logger = Sidekiq.logger.level == Logger::DEBUG ? Sidekiq.logger : nil - Client = Elasticsearch::Client.new host: 'localhost:9200', logger: Logger + Client = OpenSearch::Client.new host: 'localhost:9200', logger: Logger def perform(operation, record_id) logger.debug [operation, "ID: #{record_id}"] @@ -527,11 +523,11 @@ class Indexer case operation.to_s when /index/ record = Article.find(record_id) - Client.index index: 'articles', type: 'article', id: record.id, body: record.__elasticsearch__.as_indexed_json + Client.index index: 'articles', id: record.id, body: record.__opensearch__.as_indexed_json when /delete/ begin - Client.delete index: 'articles', type: 'article', id: record_id - rescue Elasticsearch::Transport::Transport::Errors::NotFound + Client.delete index: 'articles', id: record_id + rescue OpenSearch::Transport::Transport::Errors::NotFound logger.debug "Article not found, ID: #{record_id}" end else raise ArgumentError, "Unknown operation '#{operation}'" @@ -540,7 +536,7 @@ class Indexer end ``` -Start the _Sidekiq_ workers with `bundle exec sidekiq --queue elasticsearch --verbose` and +Start the _Sidekiq_ workers with `bundle exec sidekiq --queue opensearch --verbose` and update a model: ```ruby @@ -560,10 +556,10 @@ Indexer JID-eb7e2daf389a1e5e83697128 INFO: done: 0.006 sec ### Model Serialization By default, the model instance will be serialized to JSON using the `as_indexed_json` method, -which is defined automatically by the `Elasticsearch::Model::Serializing` module: +which is defined automatically by the `OpenSearch::Model::Serializing` module: ```ruby -Article.first.__elasticsearch__.as_indexed_json +Article.first.__opensearch__.as_indexed_json # => {"id"=>1, "title"=>"Quick brown fox"} ``` @@ -572,7 +568,7 @@ for instance with the [`as_json`](http://api.rubyonrails.org/classes/ActiveModel ```ruby class Article - include Elasticsearch::Model + include OpenSearch::Model def as_indexed_json(options={}) as_json(only: 'title') @@ -619,7 +615,7 @@ _ActiveRecord_ callbacks -- please see the full example in `examples/activerecor ### Other ActiveModel Frameworks -The `Elasticsearch::Model` module is fully compatible with any ActiveModel-compatible model, such as _Mongoid_: +The `OpenSearch::Model` module is fully compatible with any ActiveModel-compatible model, such as _Mongoid_: ```ruby require 'mongoid' @@ -634,7 +630,7 @@ class Article attr_accessible :id, :title, :published_at - include Elasticsearch::Model + include OpenSearch::Model def as_indexed_json(options={}) as_json(except: [:id, :_id]) @@ -655,7 +651,7 @@ Full examples for CouchBase, DataMapper, Mongoid, Ohm and Riak models can be fou ### Adapters To support various "OxM" (object-relational- or object-document-mapper) implementations and frameworks, -the `Elasticsearch::Model` integration supports an "adapter" concept. +the `OpenSearch::Model` integration supports an "adapter" concept. An adapter provides implementations for common behaviour, such as fetching records from the database, hooking into model callbacks for automatic index updates, or efficient bulk loading from the database. @@ -680,20 +676,20 @@ end # Register the adapter # -Elasticsearch::Model::Adapter.register( +OpenSearch::Model::Adapter.register( DataMapperAdapter, lambda { |klass| defined?(::DataMapper::Resource) and klass.ancestors.include?(::DataMapper::Resource) } ) ``` -Require the adapter and include `Elasticsearch::Model` in the class: +Require the adapter and include `OpenSearch::Model` in the class: ```ruby require 'datamapper_adapter' class Article include DataMapper::Resource - include Elasticsearch::Model + include OpenSearch::Model property :id, Serial property :title, String @@ -714,7 +710,7 @@ response.records.records.class # => DataMapper::Collection ``` -More examples can be found in the `examples` folder. Please see the `Elasticsearch::Model::Adapter` +More examples can be found in the `examples` folder. Please see the `OpenSearch::Model::Adapter` module and its submodules for technical information. ### Settings @@ -733,24 +729,13 @@ Bug fixes and features must be covered by unit tests. Github's pull requests and issues are used to communicate, send bug reports and code contributions. -To run all tests against a test Elasticsearch cluster, use a command like this: +To run all tests against a test OpenSearch cluster, use a command like this: ```bash -curl -# https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.0.0.RC1.tar.gz | tar xz -C tmp/ -SERVER=start TEST_CLUSTER_COMMAND=$PWD/tmp/elasticsearch-1.0.0.RC1/bin/elasticsearch bundle exec rake test:all +curl -# https://artifacts.opensearch.org/releases/bundle/opensearch/1.3.0/opensearch-1.3.0-linux-x64.tar.gz | tar xz -C tmp/ +SERVER=start TEST_CLUSTER_COMMAND=$PWD/tmp/opensearch-1.3.0/bin/opensearch bundle exec rake test:all ``` -### Single Table Inheritance support - -Versions < 7.0.0 of this gem supported inheritance-- more specifically, `Single Table Inheritance`. With this feature, -elasticsearch settings (index mappings, etc) on a parent model could be inherited by a child model leading to different -model documents being indexed into the same Elasticsearch index. This feature depended on the ability to set a `type` -for a document in Elasticsearch. The Elasticsearch team has deprecated support for `types`, as is described -[here.](https://www.elastic.co/guide/en/elasticsearch/reference/current/removal-of-types.html) -This gem will also remove support for types and `Single Table Inheritance` in version 7.0 as it enables an anti-pattern. -Please save different model documents in separate indices. If you want to use STI, you can include an artificial -`type` field manually in each document and use it in other operations. - ## License This software is licensed under the Apache 2 license, quoted below. diff --git a/elasticsearch-model/Rakefile b/opensearch-model/Rakefile similarity index 94% rename from elasticsearch-model/Rakefile rename to opensearch-model/Rakefile index ab1d6cab7..8dc789c72 100644 --- a/elasticsearch-model/Rakefile +++ b/opensearch-model/Rakefile @@ -21,8 +21,10 @@ desc 'Run unit tests' task default: 'test:all' task test: 'test:all' -gemfiles = ['5.0.gemfile', '6.0.gemfile'] -gemfiles << '4.0.gemfile' if RUBY_VERSION < '2.7' +gemfiles = [] +gemfiles << '6.1.gemfile' if RUBY_VERSION <= '3.0' +gemfiles << '7.1.gemfile' if RUBY_VERSION >= '3.0' + GEMFILES = gemfiles.freeze namespace :bundle do @@ -53,7 +55,7 @@ namespace :test do gemfiles.each do |gemfile| puts "GEMFILE: #{gemfile}" sh "BUNDLE_GEMFILE='#{File.expand_path("../gemfiles/#{gemfile}", __FILE__)}' " + - " bundle exec rspec" + " bundle exec rspec -b" puts '-' * 80 end end diff --git a/elasticsearch-model/examples/activerecord_article.rb b/opensearch-model/examples/activerecord_article.rb similarity index 83% rename from elasticsearch-model/examples/activerecord_article.rb rename to opensearch-model/examples/activerecord_article.rb index 1e584fd2c..dd3f096d0 100644 --- a/elasticsearch-model/examples/activerecord_article.rb +++ b/opensearch-model/examples/activerecord_article.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# ActiveRecord and Elasticsearch +# ActiveRecord and OpenSearch # ============================== # # https://github.com/rails/rails/tree/master/activerecord @@ -23,14 +23,14 @@ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pry' -Pry.config.history.file = File.expand_path('../../tmp/elasticsearch_development.pry', __FILE__) +Pry.config.history.file = File.expand_path('../../tmp/opensearch_development.pry', __FILE__) require 'logger' require 'ansi/core' require 'active_record' require 'kaminari' -require 'elasticsearch/model' +require 'opensearch/model' ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" ) @@ -57,21 +57,20 @@ class Article < ActiveRecord::Base # Index data # -client = Elasticsearch::Client.new log:true +client = OpenSearch::Client.new log:true # client.indices.delete index: 'articles' rescue nil # client.indices.create index: 'articles', body: { mappings: { article: { dynamic: 'strict' }, properties: {} } } client.indices.delete index: 'articles' rescue nil client.bulk index: 'articles', - type: 'article', body: Article.all.as_json.map { |a| { index: { _id: a.delete('id'), data: a } } }, refresh: true -# Extend the model with Elasticsearch support +# Extend the model with OpenSearch support # -Article.__send__ :include, Elasticsearch::Model -# Article.__send__ :include, Elasticsearch::Model::Callbacks +Article.__send__ :include, OpenSearch::Model +# Article.__send__ :include, OpenSearch::Model::Callbacks # ActiveRecord::Base.logger.silence do # 10_000.times do |i| @@ -81,7 +80,7 @@ class Article < ActiveRecord::Base puts '', '-'*Pry::Terminal.width! -Elasticsearch::Model.client = Elasticsearch::Client.new log: true +OpenSearch::Model.client = OpenSearch::Client.new log: true response = Article.search 'foo'; diff --git a/elasticsearch-model/examples/activerecord_associations.rb b/opensearch-model/examples/activerecord_associations.rb similarity index 84% rename from elasticsearch-model/examples/activerecord_associations.rb rename to opensearch-model/examples/activerecord_associations.rb index 17d521cbf..c3be599e3 100644 --- a/elasticsearch-model/examples/activerecord_associations.rb +++ b/opensearch-model/examples/activerecord_associations.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# ActiveRecord associations and Elasticsearch +# ActiveRecord associations and OpenSearch # =========================================== # # https://github.com/rails/rails/tree/master/activerecord @@ -35,7 +35,7 @@ require 'active_record' require 'json' -require 'elasticsearch/model' +require 'opensearch/model' ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" ) @@ -80,8 +80,8 @@ # ----- Elasticsearch client setup ---------------------------------------------------------------- -Elasticsearch::Model.client = Elasticsearch::Client.new log: true -Elasticsearch::Model.client.transport.transport.logger.formatter = proc { |s, d, p, m| "\e[2m#{m}\n\e[0m" } +OpenSearch::Model.client = OpenSearch::Client.new log: true +OpenSearch::Model.client.transport.transport.logger.formatter = proc { |s, d, p, m| "\e[2m#{m}\n\e[0m" } # ----- Search integration ------------------------------------------------------------------------ @@ -89,11 +89,11 @@ module Searchable extend ActiveSupport::Concern included do - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks include Indexing - after_touch() { __elasticsearch__.index_document } + after_touch() { __opensearch__.index_document } end module Indexing @@ -109,12 +109,12 @@ module Indexing indexes :department end indexes :comments, type: :object do - indexes :text + indexes :text end end end - - # Customize the JSON serialization for Elasticsearch + + # Customize the JSON serialization for OpenSearch def as_indexed_json(options={}) self.as_json( include: { categories: { only: :title}, @@ -128,8 +128,8 @@ def as_indexed_json(options={}) # ----- Model definitions ------------------------------------------------------------------------- class Category < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks has_and_belongs_to_many :articles end @@ -152,16 +152,16 @@ class Authorship < ActiveRecord::Base class Article < ActiveRecord::Base include Searchable - has_and_belongs_to_many :categories, after_add: [ lambda { |a,c| a.__elasticsearch__.index_document } ], - after_remove: [ lambda { |a,c| a.__elasticsearch__.index_document } ] + has_and_belongs_to_many :categories, after_add: [ lambda { |a,c| a.__opensearch__.index_document } ], + after_remove: [ lambda { |a,c| a.__opensearch__.index_document } ] has_many :authorships has_many :authors, through: :authorships has_many :comments end class Comment < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks belongs_to :article, touch: true end @@ -193,7 +193,7 @@ class Comment < ActiveRecord::Base article.comments.create text: 'First comment for article One' article.comments.create text: 'Second comment for article One' -Elasticsearch::Model.client.indices.refresh index: Elasticsearch::Model::Registry.all.map(&:index_name) +OpenSearch::Model.client.indices.refresh index: OpenSearch::Model::Registry.all.map(&:index_name) # Search for a term and return records # @@ -204,7 +204,7 @@ class Comment < ActiveRecord::Base puts "", "All Models containing 'one':".ansi(:bold), - Elasticsearch::Model.search('one').records.to_a.map(&:inspect), + OpenSearch::Model.search('one').records.to_a.map(&:inspect), "" # Difference between `records` and `results` @@ -221,7 +221,7 @@ class Comment < ActiveRecord::Base "" puts "", - "Access the Elasticsearch documents with the `#results` method (without touching the database):".ansi(:bold), + "Access the OpenSearch documents with the `#results` method (without touching the database):".ansi(:bold), response.results.map { |r| "* #{r.title} | Authors: #{r.authors.map(&:full_name) } | Comment count: #{r.comments.size}" }.join("\n"), "" @@ -230,12 +230,12 @@ class Comment < ActiveRecord::Base JSON.pretty_generate(response.results.first._source.to_hash), "" -# Retrieve only selected fields from Elasticsearch +# Retrieve only selected fields from OpenSearch # response = Article.search query: { match: { title: 'first' } }, _source: ['title', 'authors.full_name'] puts "", - "Retrieve only selected fields from Elasticsearch:".ansi(:bold), + "Retrieve only selected fields from OpenSearch:".ansi(:bold), JSON.pretty_generate(response.results.first._source.to_hash), "" diff --git a/elasticsearch-model/examples/activerecord_custom_analyzer.rb b/opensearch-model/examples/activerecord_custom_analyzer.rb similarity index 89% rename from elasticsearch-model/examples/activerecord_custom_analyzer.rb rename to opensearch-model/examples/activerecord_custom_analyzer.rb index d16ddbd11..4bf6b971a 100644 --- a/elasticsearch-model/examples/activerecord_custom_analyzer.rb +++ b/opensearch-model/examples/activerecord_custom_analyzer.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# Custom Analyzer for ActiveRecord integration with Elasticsearch +# Custom Analyzer for ActiveRecord integration with OpenSearch # =============================================================== $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) @@ -24,7 +24,7 @@ require 'logger' require 'active_record' -require 'elasticsearch/model' +require 'opensearch/model' ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" ) @@ -37,11 +37,11 @@ end end -Elasticsearch::Model.client.transport.transport.logger = ActiveSupport::Logger.new(STDOUT) -Elasticsearch::Model.client.transport.transport.logger.formatter = lambda { |s, d, p, m| "#{m.ansi(:faint)}\n" } +OpenSearch::Model.client.transport.transport.logger = ActiveSupport::Logger.new(STDOUT) +OpenSearch::Model.client.transport.transport.logger.formatter = lambda { |s, d, p, m| "#{m.ansi(:faint)}\n" } class Article < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model settings index: { number_of_shards: 1, @@ -93,28 +93,28 @@ class Article < ActiveRecord::Base puts "English analyzer [Foo_Bar_1_Bazooka]".ansi(:bold), "Tokens: " + - Article.__elasticsearch__.client.indices + Article.__opensearch__.client.indices .analyze(index: Article.index_name, body: { field: 'title', text: 'Foo_Bar_1_Bazooka' })['tokens'] .map { |d| "[#{d['token']}]" }.join(' '), "\n" puts "Keyword analyzer [Foo_Bar_1_Bazooka]".ansi(:bold), "Tokens: " + - Article.__elasticsearch__.client.indices + Article.__opensearch__.client.indices .analyze(index: Article.index_name, body: { field: 'title.keyword', text: 'Foo_Bar_1_Bazooka' })['tokens'] .map { |d| "[#{d['token']}]" }.join(' '), "\n" puts "Pattern analyzer [Foo_Bar_1_Bazooka]".ansi(:bold), "Tokens: " + - Article.__elasticsearch__.client.indices + Article.__opensearch__.client.indices .analyze(index: Article.index_name, body: { field: 'title.pattern', text: 'Foo_Bar_1_Bazooka' })['tokens'] .map { |d| "[#{d['token']}]" }.join(' '), "\n" puts "Trigram analyzer [Foo_Bar_1_Bazooka]".ansi(:bold), "Tokens: " + - Article.__elasticsearch__.client.indices + Article.__opensearch__.client.indices .analyze(index: Article.index_name, body: { field: 'title.trigram', text: 'Foo_Bar_1_Bazooka' })['tokens'] .map { |d| "[#{d['token']}]" }.join(' '), "\n" diff --git a/elasticsearch-model/examples/activerecord_mapping_completion.rb b/opensearch-model/examples/activerecord_mapping_completion.rb similarity index 88% rename from elasticsearch-model/examples/activerecord_mapping_completion.rb rename to opensearch-model/examples/activerecord_mapping_completion.rb index 264746180..40edcb918 100644 --- a/elasticsearch-model/examples/activerecord_mapping_completion.rb +++ b/opensearch-model/examples/activerecord_mapping_completion.rb @@ -17,7 +17,7 @@ require 'ansi' require 'active_record' -require 'elasticsearch/model' +require 'opensearch/model' ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" ) @@ -31,8 +31,8 @@ end class Article < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks mapping do indexes :title, type: 'text' do @@ -46,11 +46,11 @@ def as_indexed_json(options={}) end end -Article.__elasticsearch__.client = Elasticsearch::Client.new log: true +Article.__opensearch__.client = OpenSearch::Client.new log: true # Create index -Article.__elasticsearch__.create_index! force: true +Article.__opensearch__.create_index! force: true # Store data @@ -58,7 +58,7 @@ def as_indexed_json(options={}) Article.create title: 'Foo' Article.create title: 'Bar' Article.create title: 'Foo Foo' -Article.__elasticsearch__.refresh_index! +Article.__opensearch__.refresh_index! # Search and suggest diff --git a/elasticsearch-model/examples/activerecord_mapping_edge_ngram.rb b/opensearch-model/examples/activerecord_mapping_edge_ngram.rb similarity index 86% rename from elasticsearch-model/examples/activerecord_mapping_edge_ngram.rb rename to opensearch-model/examples/activerecord_mapping_edge_ngram.rb index c1a714f80..4672a45d4 100644 --- a/elasticsearch-model/examples/activerecord_mapping_edge_ngram.rb +++ b/opensearch-model/examples/activerecord_mapping_edge_ngram.rb @@ -18,7 +18,7 @@ require 'ansi' require 'sqlite3' require 'active_record' -require 'elasticsearch/model' +require 'opensearch/model' ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" ) @@ -32,8 +32,8 @@ end class Article < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks article_es_settings = { index: { @@ -68,11 +68,11 @@ def as_indexed_json(options={}) end end -Article.__elasticsearch__.client = Elasticsearch::Client.new log: true +Article.__opensearch__.client = OpenSearch::Client.new log: true # Create index -Article.__elasticsearch__.create_index! force: true +Article.__opensearch__.create_index! force: true # Store data @@ -80,7 +80,7 @@ def as_indexed_json(options={}) Article.create title: 'Foo' Article.create title: 'Bar' Article.create title: 'Foo Foo' -Article.__elasticsearch__.refresh_index! +Article.__opensearch__.refresh_index! # Search and suggest fulltext_search_response = Article.search(query: { match: { title: 'foo'} } ) @@ -102,15 +102,15 @@ def as_indexed_json(options={}) "" puts "", "Text 'Foo Bar' analyzed with the default analyzer:".ansi(:bold), - Article.__elasticsearch__.client.indices.analyze( - index: Article.__elasticsearch__.index_name, + Article.__opensearch__.client.indices.analyze( + index: Article.__opensearch__.index_name, field: 'title', text: 'Foo Bar')['tokens'].map { |t| t['token'] }.inspect.ansi(:bold, :yellow), "" puts "", "Text 'Foo Bar' analyzed with the autocomplete filter:".ansi(:bold), - Article.__elasticsearch__.client.indices.analyze( - index: Article.__elasticsearch__.index_name, + Article.__opensearch__.client.indices.analyze( + index: Article.__opensearch__.index_name, field: 'suggestable_title', text: 'Foo Bar')['tokens'].map { |t| t['token'] }.inspect.ansi(:bold, :yellow), "" diff --git a/elasticsearch-model/examples/couchbase_article.rb b/opensearch-model/examples/couchbase_article.rb similarity index 78% rename from elasticsearch-model/examples/couchbase_article.rb rename to opensearch-model/examples/couchbase_article.rb index cfbab22d2..3f57081a6 100644 --- a/elasticsearch-model/examples/couchbase_article.rb +++ b/opensearch-model/examples/couchbase_article.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# Couchbase and Elasticsearch +# Couchbase and OpenSearch # =========================== # # https://github.com/couchbase/couchbase-ruby-model @@ -23,12 +23,12 @@ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pry' -Pry.config.history.file = File.expand_path('../../tmp/elasticsearch_development.pry', __FILE__) +Pry.config.history.file = File.expand_path('../../tmp/opensearch_development.pry', __FILE__) require 'logger' require 'couchbase/model' -require 'elasticsearch/model' +require 'opensearch/model' # Documents are stored as JSON objects in Riak but have rich # semantics, including validations and associations. @@ -52,11 +52,11 @@ class Article < Couchbase::Model end -# Extend the model with Elasticsearch support +# Extend the model with OpenSearch support # -Article.__send__ :extend, Elasticsearch::Model::Client::ClassMethods -Article.__send__ :extend, Elasticsearch::Model::Searching::ClassMethods -Article.__send__ :extend, Elasticsearch::Model::Naming::ClassMethods +Article.__send__ :extend, OpenSearch::Model::Client::ClassMethods +Article.__send__ :extend, OpenSearch::Model::Searching::ClassMethods +Article.__send__ :extend, OpenSearch::Model::Naming::ClassMethods # Create documents in Riak # @@ -64,19 +64,18 @@ class Article < Couchbase::Model Article.create id: '2', title: 'Bar' rescue nil Article.create id: '3', title: 'Foo Foo' rescue nil -# Index data into Elasticsearch +# Index data into OpenSearch # -client = Elasticsearch::Client.new log:true +client = OpenSearch::Client.new log:true client.indices.delete index: 'articles' rescue nil client.bulk index: 'articles', - type: 'article', body: Article.find(['1', '2', '3']).map { |a| { index: { _id: a.id, data: a.attributes } } }, refresh: true -response = Article.search 'foo', index: 'articles', type: 'article'; +response = Article.search 'foo', index: 'articles'; Pry.start(binding, prompt: lambda { |obj, nest_level, _| '> ' }, input: StringIO.new('response.records.to_a'), diff --git a/elasticsearch-model/examples/datamapper_article.rb b/opensearch-model/examples/datamapper_article.rb similarity index 81% rename from elasticsearch-model/examples/datamapper_article.rb rename to opensearch-model/examples/datamapper_article.rb index d29460966..2647495e8 100644 --- a/elasticsearch-model/examples/datamapper_article.rb +++ b/opensearch-model/examples/datamapper_article.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# DataMapper and Elasticsearch +# DataMapper and OpenSearch # ============================ # # https://github.com/datamapper/dm-core @@ -25,7 +25,7 @@ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pry' -Pry.config.history.file = File.expand_path('../../tmp/elasticsearch_development.pry', __FILE__) +Pry.config.history.file = File.expand_path('../../tmp/opensearch_development.pry', __FILE__) require 'logger' require 'ansi/core' @@ -35,7 +35,7 @@ require 'active_support/all' -require 'elasticsearch/model' +require 'opensearch/model' DataMapper::Logger.new(STDOUT, :debug) DataMapper.setup(:default, 'sqlite::memory:') @@ -55,9 +55,9 @@ class Article Article.create title: 'Bar' Article.create title: 'Foo Foo' -# Extend the model with Elasticsearch support +# Extend the model with OpenSearch support # -Article.__send__ :include, Elasticsearch::Model +Article.__send__ :include, OpenSearch::Model # The DataMapper adapter # @@ -76,9 +76,9 @@ def records module Callbacks def self.included(model) model.class_eval do - after(:create) { __elasticsearch__.index_document } - after(:save) { __elasticsearch__.update_document } - after(:destroy) { __elasticsearch__.delete_document } + after(:create) { __opensearch__.index_document } + after(:save) { __opensearch__.update_document } + after(:destroy) { __opensearch__.delete_document } end end end @@ -86,7 +86,7 @@ def self.included(model) # Register the adapter # -Elasticsearch::Model::Adapter.register( +OpenSearch::Model::Adapter.register( DataMapperAdapter, lambda { |klass| defined?(::DataMapper::Resource) and klass.ancestors.include?(::DataMapper::Resource) } ) diff --git a/elasticsearch-model/examples/mongoid_article.rb b/opensearch-model/examples/mongoid_article.rb similarity index 79% rename from elasticsearch-model/examples/mongoid_article.rb rename to opensearch-model/examples/mongoid_article.rb index e2f3ae464..0e846841e 100644 --- a/elasticsearch-model/examples/mongoid_article.rb +++ b/opensearch-model/examples/mongoid_article.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# Mongoid and Elasticsearch +# Mongoid and OpenSearch # ========================= # # http://mongoid.org/en/mongoid/index.html @@ -23,22 +23,22 @@ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pry' -Pry.config.history.file = File.expand_path('../../tmp/elasticsearch_development.pry', __FILE__) +Pry.config.history.file = File.expand_path('../../tmp/opensearch_development.pry', __FILE__) require 'benchmark' require 'logger' require 'ansi/core' require 'mongoid' -require 'elasticsearch/model' -require 'elasticsearch/model/callbacks' +require 'opensearch/model' +require 'opensearch/model/callbacks' Mongoid.logger.level = Logger::DEBUG Moped.logger.level = Logger::DEBUG Mongoid.connect_to 'articles' -Elasticsearch::Model.client = Elasticsearch::Client.new host: 'localhost:9200', log: true +OpenSearch::Model.client = OpenSearch::Client.new host: 'localhost:9200', log: true class Article include Mongoid::Document @@ -52,10 +52,10 @@ def as_indexed_json(options={}) end end -# Extend the model with Elasticsearch support +# Extend the model with OpenSearch support # -Article.__send__ :include, Elasticsearch::Model -# Article.__send__ :include, Elasticsearch::Model::Callbacks +Article.__send__ :include, OpenSearch::Model +# Article.__send__ :include, OpenSearch::Model::Callbacks # Store data # @@ -66,11 +66,10 @@ def as_indexed_json(options={}) # Index data # -client = Elasticsearch::Client.new host:'localhost:9200', log:true +client = OpenSearch::Client.new host:'localhost:9200', log:true client.indices.delete index: 'articles' rescue nil client.bulk index: 'articles', - type: 'article', body: Article.all.map { |a| { index: { _id: a.id, data: a.attributes } } }, refresh: true diff --git a/elasticsearch-model/examples/ohm_article.rb b/opensearch-model/examples/ohm_article.rb similarity index 78% rename from elasticsearch-model/examples/ohm_article.rb rename to opensearch-model/examples/ohm_article.rb index 1c50877f8..387aa25fc 100644 --- a/elasticsearch-model/examples/ohm_article.rb +++ b/opensearch-model/examples/ohm_article.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# Ohm for Redis and Elasticsearch +# Ohm for Redis and OpenSearch # =============================== # # https://github.com/soveran/ohm#example @@ -23,14 +23,14 @@ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pry' -Pry.config.history.file = File.expand_path('../../tmp/elasticsearch_development.pry', __FILE__) +Pry.config.history.file = File.expand_path('../../tmp/opensearch_development.pry', __FILE__) require 'logger' require 'ansi/core' require 'active_model' require 'ohm' -require 'elasticsearch/model' +require 'opensearch/model' class Article < Ohm::Model # Include JSON serialization from ActiveModel @@ -40,13 +40,13 @@ class Article < Ohm::Model attribute :published_at end -# Extend the model with Elasticsearch support +# Extend the model with OpenSearch support # -Article.__send__ :include, Elasticsearch::Model +Article.__send__ :include, OpenSearch::Model # Register a custom adapter # -module Elasticsearch +module OpenSearch module Model module Adapter module Ohm @@ -62,9 +62,9 @@ def records end end -# Configure the Elasticsearch client to log operations +# Configure the OpenSearch client to log operations # -Elasticsearch::Model.client = Elasticsearch::Client.new log: true +OpenSearch::Model.client = OpenSearch::Client.new log: true puts '', '-'*Pry::Terminal.width! @@ -73,9 +73,8 @@ def records Article.create id: '2', title: 'Bar' Article.create id: '3', title: 'Foo Foo' -Article.__elasticsearch__.client.indices.delete index: 'articles' rescue nil -Article.__elasticsearch__.client.bulk index: 'articles', - type: 'article', +Article.__opensearch__.client.indices.delete index: 'articles' rescue nil +Article.__opensearch__.client.bulk index: 'articles', body: Article.all.map { |a| { index: { _id: a.id, data: a.attributes } } }, refresh: true diff --git a/elasticsearch-model/examples/riak_article.rb b/opensearch-model/examples/riak_article.rb similarity index 84% rename from elasticsearch-model/examples/riak_article.rb rename to opensearch-model/examples/riak_article.rb index 8fd024e41..b70eec628 100644 --- a/elasticsearch-model/examples/riak_article.rb +++ b/opensearch-model/examples/riak_article.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# Riak and Elasticsearch +# Riak and OpenSearch # ====================== # # https://github.com/basho-labs/ripple @@ -23,12 +23,12 @@ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'pry' -Pry.config.history.file = File.expand_path('../../tmp/elasticsearch_development.pry', __FILE__) +Pry.config.history.file = File.expand_path('../../tmp/opensearch_development.pry', __FILE__) require 'logger' require 'ripple' -require 'elasticsearch/model' +require 'opensearch/model' # Documents are stored as JSON objects in Riak but have rich # semantics, including validations and associations. @@ -39,9 +39,9 @@ class Article property :published_at, Time, :default => proc { Time.now } end -# Extend the model with Elasticsearch support +# Extend the model with OpenSearch support # -Article.__send__ :include, Elasticsearch::Model +Article.__send__ :include, OpenSearch::Model # Create documents in Riak # @@ -50,13 +50,12 @@ class Article Article.create id: '2', title: 'Bar' Article.create id: '3', title: 'Foo Foo' -# Index data into Elasticsearch +# Index data into OpenSearch # -client = Elasticsearch::Client.new log:true +client = OpenSearch::Client.new log:true client.indices.delete index: 'articles' rescue nil client.bulk index: 'articles', - type: 'article', body: Article.all.map { |a| { index: { _id: a.key, data: JSON.parse(a.robject.raw_data) } } }.as_json, diff --git a/elasticsearch-model/gemfiles/6.0.gemfile b/opensearch-model/gemfiles/6.1.gemfile similarity index 95% rename from elasticsearch-model/gemfiles/6.0.gemfile rename to opensearch-model/gemfiles/6.1.gemfile index dd859f68b..1f6dfb5fc 100644 --- a/elasticsearch-model/gemfiles/6.0.gemfile +++ b/opensearch-model/gemfiles/6.1.gemfile @@ -25,8 +25,8 @@ source 'https://rubygems.org' gemspec path: '../' -gem 'activemodel', '6.0.0' -gem 'activerecord', '6.0.0' +gem 'activemodel', '>~ 6.1' +gem 'activerecord', '>~ 6.1' gem 'sqlite3' unless defined?(JRUBY_VERSION) #gem 'mongoid', '~> 6' diff --git a/elasticsearch-model/gemfiles/5.0.gemfile b/opensearch-model/gemfiles/7.1.gemfile similarity index 81% rename from elasticsearch-model/gemfiles/5.0.gemfile rename to opensearch-model/gemfiles/7.1.gemfile index 8b1930961..48bf9273a 100644 --- a/elasticsearch-model/gemfiles/5.0.gemfile +++ b/opensearch-model/gemfiles/7.1.gemfile @@ -17,19 +17,21 @@ # Usage: # -# $ BUNDLE_GEMFILE=./gemfiles/5.0.gemfile bundle install -# $ BUNDLE_GEMFILE=./gemfiles/5.0.gemfile bundle exec rake test:integration +# $ BUNDLE_GEMFILE=./gemfiles/6.0.gemfile bundle install +# $ BUNDLE_GEMFILE=./gemfiles/6.0.gemfile bundle exec rake test:integration + source 'https://rubygems.org' gemspec path: '../' -gem 'activemodel', '~> 5' -gem 'activerecord', '~> 5' +gem 'activemodel', '~> 7.1' +gem 'activerecord', '~> 7.1' gem 'sqlite3' unless defined?(JRUBY_VERSION) -gem 'mongoid', '~> 6' +#gem 'mongoid', '~> 6' group :development, :testing do gem 'rspec' gem 'pry-nav' + gem 'byebug' end diff --git a/elasticsearch-model/lib/elasticsearch/model.rb b/opensearch-model/lib/opensearch/model.rb similarity index 50% rename from elasticsearch-model/lib/elasticsearch/model.rb rename to opensearch-model/lib/opensearch/model.rb index af2f34cb6..2bc40ce72 100644 --- a/elasticsearch-model/lib/elasticsearch/model.rb +++ b/opensearch-model/lib/opensearch/model.rb @@ -19,77 +19,77 @@ require 'active_support/core_ext/module/delegation' -require 'elasticsearch' +require 'opensearch-ruby' -require 'elasticsearch/model/version' +require 'opensearch/model/version' -require 'elasticsearch/model/hash_wrapper' -require 'elasticsearch/model/client' +require 'opensearch/model/hash_wrapper' +require 'opensearch/model/client' -require 'elasticsearch/model/multimodel' +require 'opensearch/model/multimodel' -require 'elasticsearch/model/adapter' -require 'elasticsearch/model/adapters/default' -require 'elasticsearch/model/adapters/active_record' -require 'elasticsearch/model/adapters/mongoid' -require 'elasticsearch/model/adapters/multiple' +require 'opensearch/model/adapter' +require 'opensearch/model/adapters/default' +require 'opensearch/model/adapters/active_record' +require 'opensearch/model/adapters/mongoid' +require 'opensearch/model/adapters/multiple' -require 'elasticsearch/model/importing' -require 'elasticsearch/model/indexing' -require 'elasticsearch/model/naming' -require 'elasticsearch/model/serializing' -require 'elasticsearch/model/searching' -require 'elasticsearch/model/callbacks' +require 'opensearch/model/importing' +require 'opensearch/model/indexing' +require 'opensearch/model/naming' +require 'opensearch/model/serializing' +require 'opensearch/model/searching' +require 'opensearch/model/callbacks' -require 'elasticsearch/model/proxy' +require 'opensearch/model/proxy' -require 'elasticsearch/model/response' -require 'elasticsearch/model/response/base' -require 'elasticsearch/model/response/result' -require 'elasticsearch/model/response/results' -require 'elasticsearch/model/response/records' -require 'elasticsearch/model/response/pagination' -require 'elasticsearch/model/response/aggregations' -require 'elasticsearch/model/response/suggestions' +require 'opensearch/model/response' +require 'opensearch/model/response/base' +require 'opensearch/model/response/result' +require 'opensearch/model/response/results' +require 'opensearch/model/response/records' +require 'opensearch/model/response/pagination' +require 'opensearch/model/response/aggregations' +require 'opensearch/model/response/suggestions' -require 'elasticsearch/model/ext/active_record' +require 'opensearch/model/ext/active_record' case when defined?(::Kaminari) - Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::Kaminari + OpenSearch::Model::Response::Response.__send__ :include, OpenSearch::Model::Response::Pagination::Kaminari when defined?(::WillPaginate) - Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::WillPaginate + OpenSearch::Model::Response::Response.__send__ :include, OpenSearch::Model::Response::Pagination::WillPaginate end -module Elasticsearch +module OpenSearch - # Elasticsearch integration for Ruby models + # OpenSearch integration for Ruby models # ========================================= # - # `Elasticsearch::Model` contains modules for integrating the Elasticsearch search and analytical engine + # `OpenSearch::Model` contains modules for integrating the OpenSearch search and analytical engine # with ActiveModel-based classes, or models, for the Ruby programming language. # # It facilitates importing your data into an index, automatically updating it when a record changes, # searching the specific index, setting up the index mapping or the model JSON serialization. # - # When the `Elasticsearch::Model` module is included in your class, it automatically extends it - # with the functionality; see {Elasticsearch::Model.included}. Most methods are available via - # the `__elasticsearch__` class and instance method proxies. + # When the `OpenSearch::Model` module is included in your class, it automatically extends it + # with the functionality; see {OpenSearch::Model.included}. Most methods are available via + # the `__opensearch__` class and instance method proxies. # # It is possible to include/extend the model with the corresponding # modules directly, if that is desired: # - # MyModel.__send__ :extend, Elasticsearch::Model::Client::ClassMethods - # MyModel.__send__ :include, Elasticsearch::Model::Client::InstanceMethods - # MyModel.__send__ :extend, Elasticsearch::Model::Searching::ClassMethods + # MyModel.__send__ :extend, OpenSearch::Model::Client::ClassMethods + # MyModel.__send__ :include, OpenSearch::Model::Client::InstanceMethods + # MyModel.__send__ :extend, OpenSearch::Model::Searching::ClassMethods # # ... # module Model METHODS = [:search, :mapping, :mappings, :settings, :index_name, :document_type, :import] - # Adds the `Elasticsearch::Model` functionality to the including class. + # Adds the `OpenSearch::Model` functionality to the including class. # - # * Creates the `__elasticsearch__` class and instance method. These methods return a proxy object with + # * Creates the `__opensearch__` class and instance method. These methods return a proxy object with # other common methods defined on them. # * The module includes other modules with further functionality. # * Sets up delegation for common methods such as `import` and `search`. @@ -97,22 +97,22 @@ module Model # @example Include the module in the `Article` model definition # # class Article < ActiveRecord::Base - # include Elasticsearch::Model + # include OpenSearch::Model # end # # @example Inject the module into the `Article` model during run time # - # Article.__send__ :include, Elasticsearch::Model + # Article.__send__ :include, OpenSearch::Model # # def self.included(base) base.class_eval do - include Elasticsearch::Model::Proxy + include OpenSearch::Model::Proxy - # Delegate common methods to the `__elasticsearch__` ClassMethodsProxy, unless they are defined already + # Delegate common methods to the `__opensearch__` ClassMethodsProxy, unless they are defined already class << self METHODS.each do |method| - delegate method, to: :__elasticsearch__ unless self.public_instance_methods.include?(method) + delegate method, to: :__opensearch__ unless self.public_instance_methods.include?(method) end end end @@ -126,22 +126,22 @@ module ClassMethods # # @example Get the client # - # Elasticsearch::Model.client - # => # + # OpenSearch::Model.client + # => # # def client - @client ||= Elasticsearch::Client.new + @client ||= OpenSearch::Client.new end # Set the client for all models # # @example Configure (set) the client for all models # - # Elasticsearch::Model.client = Elasticsearch::Client.new host: 'http://localhost:9200', tracer: true - # => # + # OpenSearch::Model.client = OpenSearch::Client.new host: 'http://localhost:9200', tracer: true + # => # # - # @note You have to set the client before you call Elasticsearch methods on the model, - # or set it directly on the model; see {Elasticsearch::Model::Client::ClassMethods#client} + # @note You have to set the client before you call OpenSearch methods on the model, + # or set it directly on the model; see {OpenSearch::Model::Client::ClassMethods#client} # def client=(client) @client = client @@ -149,22 +149,22 @@ def client=(client) # Search across multiple models # - # By default, all models which include the `Elasticsearch::Model` module are searched + # By default, all models which include the `OpenSearch::Model` module are searched # # @param query_or_payload [String,Hash,Object] The search request definition # (string, JSON, Hash, or object responding to `to_hash`) # @param models [Array] The Array of Model objects to search - # @param options [Hash] Optional parameters to be passed to the Elasticsearch client + # @param options [Hash] Optional parameters to be passed to the OpenSearch client # - # @return [Elasticsearch::Model::Response::Response] + # @return [OpenSearch::Model::Response::Response] # # @example Search across specific models # - # Elasticsearch::Model.search('foo', [Author, Article]) + # OpenSearch::Model.search('foo', [Author, Article]) # - # @example Search across all models which include the `Elasticsearch::Model` module + # @example Search across all models which include the `OpenSearch::Model` module # - # Elasticsearch::Model.search('foo') + # OpenSearch::Model.search('foo') # def search(query_or_payload, models=[], options={}) models = Multimodel.new(models) diff --git a/elasticsearch-model/lib/elasticsearch/model/adapter.rb b/opensearch-model/lib/opensearch/model/adapter.rb similarity index 84% rename from elasticsearch-model/lib/elasticsearch/model/adapter.rb rename to opensearch-model/lib/opensearch/model/adapter.rb index cdb0c7d0e..cf0ed98db 100644 --- a/elasticsearch-model/lib/elasticsearch/model/adapter.rb +++ b/opensearch-model/lib/opensearch/model/adapter.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Contains an adapter which provides OxM-specific implementations for common behaviour: @@ -24,9 +24,9 @@ module Model # * {Adapter::Adapter#callbacks_mixin Model callbacks for automatic index updates} # * {Adapter::Adapter#importing_mixin Efficient bulk loading from the database} # - # @see Elasticsearch::Model::Adapter::Default - # @see Elasticsearch::Model::Adapter::ActiveRecord - # @see Elasticsearch::Model::Adapter::Mongoid + # @see OpenSearch::Model::Adapter::Default + # @see OpenSearch::Model::Adapter::ActiveRecord + # @see OpenSearch::Model::Adapter::Mongoid # module Adapter @@ -36,9 +36,9 @@ module Adapter # # class Article < ActiveRecord::Base; end # - # myadapter = Elasticsearch::Model::Adapter.from_class(Article) + # myadapter = OpenSearch::Model::Adapter.from_class(Article) # myadapter.adapter - # # => Elasticsearch::Model::Adapter::ActiveRecord + # # => OpenSearch::Model::Adapter::ActiveRecord # # @see Adapter.adapters The list of included adapters # @see Adapter.register Register a custom adapter @@ -49,7 +49,7 @@ def from_class(klass) # Returns registered adapters # - # @see ::Elasticsearch::Model::Adapter::Adapter.adapters + # @see ::OpenSearch::Model::Adapter::Adapter.adapters # def adapters Adapter.adapters @@ -57,7 +57,7 @@ def adapters # Registers an adapter # - # @see ::Elasticsearch::Model::Adapter::Adapter.register + # @see ::OpenSearch::Model::Adapter::Adapter.register # def register(name, condition) Adapter.register(name, condition) @@ -94,7 +94,7 @@ def initialize(klass) # # # Register the adapter # # - # Elasticsearch::Model::Adapter.register( + # OpenSearch::Model::Adapter.register( # DataMapperAdapter, # lambda { |klass| # defined?(::DataMapper::Resource) and klass.ancestors.include?(::DataMapper::Resource) @@ -109,10 +109,10 @@ def self.register(name, condition) # # @example Return the currently registered adapters # - # Elasticsearch::Model::Adapter.adapters + # OpenSearch::Model::Adapter.adapters # # => { - # # Elasticsearch::Model::Adapter::ActiveRecord => #, - # # Elasticsearch::Model::Adapter::Mongoid => #, + # # OpenSearch::Model::Adapter::ActiveRecord => #, + # # OpenSearch::Model::Adapter::Mongoid => #, # # } # # @return [Hash] The collection of adapters @@ -152,7 +152,7 @@ def importing_mixin def adapter @adapter ||= begin self.class.adapters.find( lambda {[]} ) { |name, condition| condition.call(klass) }.first \ - || Elasticsearch::Model::Adapter::Default + || OpenSearch::Model::Adapter::Default end end diff --git a/elasticsearch-model/lib/elasticsearch/model/adapters/active_record.rb b/opensearch-model/lib/opensearch/model/adapters/active_record.rb similarity index 90% rename from elasticsearch-model/lib/elasticsearch/model/adapters/active_record.rb rename to opensearch-model/lib/opensearch/model/adapters/active_record.rb index 64e0277d8..58d9e9768 100644 --- a/elasticsearch-model/lib/elasticsearch/model/adapters/active_record.rb +++ b/opensearch-model/lib/opensearch/model/adapters/active_record.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Adapter @@ -39,7 +39,7 @@ def records sql_records = klass.where(klass.primary_key => ids) sql_records = sql_records.includes(self.options[:includes]) if self.options[:includes] - # Re-order records based on the order from Elasticsearch hits + # Re-order records based on the order from OpenSearch hits # by redefining `to_a`, unless the user has called `order()` # sql_records.instance_exec(response.response['hits']['hits']) do |hits| @@ -79,9 +79,9 @@ module Callbacks # def self.included(base) base.class_eval do - after_commit lambda { __elasticsearch__.index_document }, on: :create - after_commit lambda { __elasticsearch__.update_document }, on: :update - after_commit lambda { __elasticsearch__.delete_document }, on: :destroy + after_commit lambda { __opensearch__.index_document }, on: :create + after_commit lambda { __opensearch__.update_document }, on: :update + after_commit lambda { __opensearch__.delete_document }, on: :destroy end end end @@ -109,7 +109,7 @@ def __find_in_batches(options={}, &block) end def __transform - lambda { |model| { index: { _id: model.id, data: model.__elasticsearch__.as_indexed_json } } } + lambda { |model| { index: { _id: model.id, data: model.__opensearch__.as_indexed_json } } } end end end diff --git a/elasticsearch-model/lib/elasticsearch/model/adapters/default.rb b/opensearch-model/lib/opensearch/model/adapters/default.rb similarity index 99% rename from elasticsearch-model/lib/elasticsearch/model/adapters/default.rb rename to opensearch-model/lib/opensearch/model/adapters/default.rb index 9891b5d64..4f450877d 100644 --- a/elasticsearch-model/lib/elasticsearch/model/adapters/default.rb +++ b/opensearch-model/lib/opensearch/model/adapters/default.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Adapter diff --git a/elasticsearch-model/lib/elasticsearch/model/adapters/mongoid.rb b/opensearch-model/lib/opensearch/model/adapters/mongoid.rb similarity index 91% rename from elasticsearch-model/lib/elasticsearch/model/adapters/mongoid.rb rename to opensearch-model/lib/opensearch/model/adapters/mongoid.rb index 8626d743c..30882a1fb 100644 --- a/elasticsearch-model/lib/elasticsearch/model/adapters/mongoid.rb +++ b/opensearch-model/lib/opensearch/model/adapters/mongoid.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Adapter @@ -44,7 +44,7 @@ def records criteria end - # Intercept call to sorting methods, so we can ignore the order from Elasticsearch + # Intercept call to sorting methods, so we can ignore the order from OpenSearch # %w| asc desc order_by |.each do |name| define_method name do |*args| @@ -66,9 +66,9 @@ module Callbacks # @see http://mongoid.org/en/mongoid/docs/callbacks.html # def self.included(base) - base.after_create { |document| document.__elasticsearch__.index_document } - base.after_update { |document| document.__elasticsearch__.update_document } - base.after_destroy { |document| document.__elasticsearch__.delete_document } + base.after_create { |document| document.__opensearch__.index_document } + base.after_update { |document| document.__opensearch__.update_document } + base.after_destroy { |document| document.__opensearch__.delete_document } end end @@ -88,7 +88,7 @@ def __find_in_batches(options={}, &block) scope = all scope = scope.send(named_scope) if named_scope scope = query.is_a?(Proc) ? scope.class_exec(&query) : scope.where(query) if query - + scope.no_timeout.each_slice(batch_size) do |items| yield (preprocess ? self.__send__(preprocess, items) : items) end diff --git a/elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb b/opensearch-model/lib/opensearch/model/adapters/multiple.rb similarity index 90% rename from elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb rename to opensearch-model/lib/opensearch/model/adapters/multiple.rb index 30d851043..501fbb97a 100644 --- a/elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb +++ b/opensearch-model/lib/opensearch/model/adapters/multiple.rb @@ -15,14 +15,14 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Adapter # An adapter to be used for deserializing results from multiple models, - # retrieved through `Elasticsearch::Model.search` + # retrieved through `OpenSearch::Model.search` # - # @see Elasticsearch::Model.search + # @see OpenSearch::Model.search # module Multiple Adapter.register self, lambda { |klass| klass.is_a? Multimodel } @@ -30,7 +30,7 @@ module Multiple module Records # Returns a collection of model instances, possibly of different classes (ActiveRecord, Mongoid, ...) # - # @note The order of results in the Elasticsearch response is preserved + # @note The order of results in the OpenSearch response is preserved # def records records_by_type = __records_by_type @@ -71,9 +71,9 @@ def __records_for_klass(klass, ids) adapter = __adapter_for_klass(klass) case - when Elasticsearch::Model::Adapter::ActiveRecord.equal?(adapter) + when OpenSearch::Model::Adapter::ActiveRecord.equal?(adapter) klass.where(klass.primary_key => ids) - when Elasticsearch::Model::Adapter::Mongoid.equal?(adapter) + when OpenSearch::Model::Adapter::Mongoid.equal?(adapter) klass.where(:id.in => ids) else klass.find(ids) @@ -99,9 +99,9 @@ def __ids_by_type ids_by_type end - # Returns the class of the model corresponding to a specific `hit` in Elasticsearch results + # Returns the class of the model corresponding to a specific `hit` in OpenSearch results # - # @see Elasticsearch::Model::Registry + # @see OpenSearch::Model::Registry # # @api private # diff --git a/elasticsearch-model/lib/elasticsearch/model/callbacks.rb b/opensearch-model/lib/opensearch/model/callbacks.rb similarity index 90% rename from elasticsearch-model/lib/elasticsearch/model/callbacks.rb rename to opensearch-model/lib/opensearch/model/callbacks.rb index cff3d1c9d..f79e1652d 100644 --- a/elasticsearch-model/lib/elasticsearch/model/callbacks.rb +++ b/opensearch-model/lib/opensearch/model/callbacks.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Allows to automatically update index based on model changes, @@ -31,11 +31,11 @@ module Callbacks # When included in a model, automatically injects the callback subscribers (`after_save`, etc) # - # @example Automatically update Elasticsearch index when the model changes + # @example Automatically update OpenSearch index when the model changes # # class Article - # include Elasticsearch::Model - # include Elasticsearch::Model::Callbacks + # include OpenSearch::Model + # include OpenSearch::Model::Callbacks # end # # Article.first.update_attribute :title, 'Updated' diff --git a/elasticsearch-model/lib/elasticsearch/model/client.rb b/opensearch-model/lib/opensearch/model/client.rb similarity index 84% rename from elasticsearch-model/lib/elasticsearch/model/client.rb rename to opensearch-model/lib/opensearch/model/client.rb index b47a0925f..16ed461fb 100644 --- a/elasticsearch-model/lib/elasticsearch/model/client.rb +++ b/opensearch-model/lib/opensearch/model/client.rb @@ -15,9 +15,9 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model - # Contains an `Elasticsearch::Client` instance + # Contains an `OpenSearch::Client` instance # module Client module ClassMethods @@ -26,17 +26,17 @@ module ClassMethods # @example Get the client for `Article` and perform API request # # Article.client.cluster.health - # # => { "cluster_name" => "elasticsearch" ... } + # # => { "cluster_name" => "opensearch" ... } # def client client=nil - @client ||= Elasticsearch::Model.client + @client ||= OpenSearch::Model.client end # Set the client for a specific model class # # @example Configure the client for the `Article` model # - # Article.client = Elasticsearch::Client.new host: 'http://api.server:8080' + # Article.client = OpenSearch::Client.new host: 'http://api.server:8080' # Article.search ... # def client=(client) @@ -62,7 +62,7 @@ def client # @example Set the client for a specific record # # @article = Article.first - # @article.client = Elasticsearch::Client.new host: 'http://api.server:8080' + # @article.client = OpenSearch::Client.new host: 'http://api.server:8080' # def client=(client) @client = client diff --git a/elasticsearch-model/lib/elasticsearch/model/ext/active_record.rb b/opensearch-model/lib/opensearch/model/ext/active_record.rb similarity index 93% rename from elasticsearch-model/lib/elasticsearch/model/ext/active_record.rb rename to opensearch-model/lib/opensearch/model/ext/active_record.rb index 2cdbe7f35..b8aa1a387 100644 --- a/elasticsearch-model/lib/elasticsearch/model/ext/active_record.rb +++ b/opensearch-model/lib/opensearch/model/ext/active_record.rb @@ -16,7 +16,7 @@ # under the License. # Prevent `MyModel.inspect` failing with `ActiveRecord::ConnectionNotEstablished` -# (triggered by elasticsearch-model/lib/elasticsearch/model.rb:79:in `included') +# (triggered by opensearch-model/lib/opensearch/model.rb:79:in `included') # ActiveRecord::Base.instance_eval do class << self diff --git a/elasticsearch-model/lib/elasticsearch/model/hash_wrapper.rb b/opensearch-model/lib/opensearch/model/hash_wrapper.rb similarity index 93% rename from elasticsearch-model/lib/elasticsearch/model/hash_wrapper.rb rename to opensearch-model/lib/opensearch/model/hash_wrapper.rb index 18f4dad23..c5d310010 100644 --- a/elasticsearch-model/lib/elasticsearch/model/hash_wrapper.rb +++ b/opensearch-model/lib/opensearch/model/hash_wrapper.rb @@ -15,11 +15,11 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Subclass of `Hashie::Mash` to wrap Hash-like structures - # (responses from Elasticsearch, search definitions, etc) + # (responses from OpenSearch, search definitions, etc) # # The primary goal of the subclass is to disable the # warning being printed by Hashie for re-defined diff --git a/elasticsearch-model/lib/elasticsearch/model/importing.rb b/opensearch-model/lib/opensearch/model/importing.rb similarity index 93% rename from elasticsearch-model/lib/elasticsearch/model/importing.rb rename to opensearch-model/lib/opensearch/model/importing.rb index 927dd16ee..3b59f48ea 100644 --- a/elasticsearch-model/lib/elasticsearch/model/importing.rb +++ b/opensearch-model/lib/opensearch/model/importing.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Provides support for easily and efficiently importing large amounts of @@ -51,7 +51,7 @@ module ClassMethods # @param options [Hash] Options passed to the underlying `__find_in_batches`method # @param block [Proc] Optional block to evaluate for each batch # - # @yield [Hash] Gives the Hash with the Elasticsearch response to the block + # @yield [Hash] Gives the Hash with the OpenSearch response to the block # # @return [Fixnum] default, number of errors encountered during importing # @return [Array] if +return+ option is specified to be +"errors"+, @@ -85,7 +85,7 @@ module ClassMethods # # Article.import batch_size: 100 # - # @example Process the response from Elasticsearch + # @example Process the response from OpenSearch # # Article.import do |response| # puts "Got " + response['items'].select { |i| i['index']['error'] }.size.to_s + " errors" @@ -99,9 +99,9 @@ module ClassMethods # # Article.import refresh: true # - # @example Import the records into a different index/type than the default one + # @example Import the records into a different index than the default one # - # Article.import index: 'my-new-index', type: 'my-other-type' + # Article.import index: 'my-new-index' # # @example Pass an ActiveRecord scope to limit the imported records # @@ -114,7 +114,7 @@ module ClassMethods # @example Transform records during the import with a lambda # # transform = lambda do |a| - # {index: {_id: a.id, _parent: a.author_id, data: a.__elasticsearch__.as_indexed_json}} + # {index: {_id: a.id, _parent: a.author_id, data: a.__opensearch__.as_indexed_json}} # end # # Article.import transform: transform @@ -141,7 +141,6 @@ def import(options={}, &block) errors = [] refresh = options.delete(:refresh) || false target_index = options.delete(:index) || index_name - target_type = options.delete(:type) || document_type transform = options.delete(:transform) || __transform pipeline = options.delete(:pipeline) return_value = options.delete(:return) || 'count' @@ -161,7 +160,6 @@ def import(options={}, &block) __find_in_batches(options) do |batch| params = { index: target_index, - type: target_type, body: __batch_to_bulk(batch, transform) } diff --git a/elasticsearch-model/lib/elasticsearch/model/indexing.rb b/opensearch-model/lib/opensearch/model/indexing.rb similarity index 86% rename from elasticsearch-model/lib/elasticsearch/model/indexing.rb rename to opensearch-model/lib/opensearch/model/indexing.rb index 3ebd8cfb4..753e72625 100644 --- a/elasticsearch-model/lib/elasticsearch/model/indexing.rb +++ b/opensearch-model/lib/opensearch/model/indexing.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Provides the necessary support to set up index options (mappings, settings) @@ -51,13 +51,12 @@ def as_json(options={}) # Wraps the [index mappings](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html) # class Mappings - attr_accessor :options, :type + attr_accessor :options # @private TYPES_WITH_EMBEDDED_PROPERTIES = %w(object nested) - def initialize(type = nil, options={}) - @type = type + def initialize(options={}) @options = options @mapping = {} end @@ -87,11 +86,7 @@ def indexes(name, options={}, &block) end def to_hash - if @type - { @type.to_sym => @options.merge( properties: @mapping ) } - else - @options.merge( properties: @mapping ) - end + @options.merge( properties: @mapping ) end def as_json(options={}) @@ -149,10 +144,10 @@ module ClassMethods # # => {:article=>{:dynamic=>"strict", :properties=>{:foo=>{:type=>"long"}}}} # # The `mappings` and `settings` methods are accessible directly on the model class, - # when it doesn't already define them. Use the `__elasticsearch__` proxy otherwise. + # when it doesn't already define them. Use the `__opensearch__` proxy otherwise. # def mapping(options={}, &block) - @mapping ||= Mappings.new(document_type, options) + @mapping ||= Mappings.new(options) @mapping.options.update(options) unless options.empty? @@ -179,13 +174,13 @@ def mapping(options={}, &block) # # @example Define index settings from YAML file # - # # config/elasticsearch/articles.yml: + # # config/opensearch/articles.yml: # # # # index: # # number_of_shards: 1 # # # - # Article.settings File.open("config/elasticsearch/articles.yml") + # Article.settings File.open("config/opensearch/articles.yml") # # Article.settings.to_hash # @@ -194,12 +189,12 @@ def mapping(options={}, &block) # # @example Define index settings from JSON file # - # # config/elasticsearch/articles.json: + # # config/opensearch/articles.json: # # # # { "index": { "number_of_shards": 1 } } # # # - # Article.settings File.open("config/elasticsearch/articles.json") + # Article.settings File.open("config/opensearch/articles.json") # # Article.settings.to_hash # @@ -228,15 +223,15 @@ def load_settings_from_io(settings) # # @example Create an index for the `Article` model # - # Article.__elasticsearch__.create_index! + # Article.__opensearch__.create_index! # # @example Forcefully create (delete first) an index for the `Article` model # - # Article.__elasticsearch__.create_index! force: true + # Article.__opensearch__.create_index! force: true # # @example Pass a specific index name # - # Article.__elasticsearch__.create_index! index: 'my-index' + # Article.__opensearch__.create_index! index: 'my-index' # def create_index!(options={}) options = options.clone @@ -261,11 +256,11 @@ def create_index!(options={}) # # @example Check whether the model's index exists # - # Article.__elasticsearch__.index_exists? + # Article.__opensearch__.index_exists? # # @example Check whether a specific index exists # - # Article.__elasticsearch__.index_exists? index: 'my-index' + # Article.__opensearch__.index_exists? index: 'my-index' # def index_exists?(options={}) target_index = options[:index] || self.index_name @@ -277,11 +272,11 @@ def index_exists?(options={}) # # @example Delete the index for the `Article` model # - # Article.__elasticsearch__.delete_index! + # Article.__opensearch__.delete_index! # # @example Pass a specific index name # - # Article.__elasticsearch__.delete_index! index: 'my-index' + # Article.__opensearch__.delete_index! index: 'my-index' # def delete_index!(options={}) target_index = options.delete(:index) || self.index_name @@ -302,11 +297,11 @@ def delete_index!(options={}) # # @example Refresh the index for the `Article` model # - # Article.__elasticsearch__.refresh_index! + # Article.__opensearch__.refresh_index! # # @example Pass a specific index name # - # Article.__elasticsearch__.refresh_index! index: 'my-index' + # Article.__opensearch__.refresh_index! index: 'my-index' # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html # @@ -331,7 +326,7 @@ module InstanceMethods def self.included(base) # Register callback for storing changed attributes for models # which implement `before_save` and return changed attributes - # (ie. when `Elasticsearch::Model` is included) + # (ie. when `OpenSearch::Model` is included) # # @note This is typically triggered only when the module would be # included in the model directly, not within the proxy. @@ -354,16 +349,16 @@ def self.included(base) end # Serializes the model instance into JSON (by calling `as_indexed_json`), - # and saves the document into the Elasticsearch index. + # and saves the document into the OpenSearch index. # # @param options [Hash] Optional arguments for passing to the client # # @example Index a record # - # @article.__elasticsearch__.index_document + # @article.__opensearch__.index_document # 2013-11-20 16:25:57 +0100: PUT http://localhost:9200/articles/article/1 ... # - # @return [Hash] The response from Elasticsearch + # @return [Hash] The response from OpenSearch # # @see http://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions:index # @@ -372,7 +367,6 @@ def index_document(options={}) request = { index: index_name, id: id, body: document } - request.merge!(type: document_type) if document_type client.index(request.merge!(options)) end @@ -383,17 +377,16 @@ def index_document(options={}) # # @example Delete a record # - # @article.__elasticsearch__.delete_document + # @article.__opensearch__.delete_document # 2013-11-20 16:27:00 +0100: DELETE http://localhost:9200/articles/article/1 # - # @return [Hash] The response from Elasticsearch + # @return [Hash] The response from OpenSearch # # @see http://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions:delete # def delete_document(options={}) request = { index: index_name, id: self.id } - request.merge!(type: document_type) if document_type client.delete(request.merge!(options)) end @@ -414,11 +407,11 @@ def delete_document(options={}) # @article.update_attribute :title, 'Updated' # # SQL (0.3ms) UPDATE "articles" SET "title" = ?... # - # @article.__elasticsearch__.update_document + # @article.__opensearch__.update_document # # 2013-11-20 17:00:05 +0100: POST http://localhost:9200/articles/article/1/_update ... # # 2013-11-20 17:00:05 +0100: > {"doc":{"title":"Updated"}} # - # @return [Hash] The response from Elasticsearch + # @return [Hash] The response from OpenSearch # # @see http://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions:update # @@ -434,7 +427,6 @@ def update_document(options={}) request = { index: index_name, id: self.id, body: { doc: attributes } } - request.merge!(type: document_type) if document_type client.update(request.merge!(options)) end @@ -453,15 +445,14 @@ def update_document(options={}) # # @article = Article.first # @article.title = "New title" - # @article.__elasticsearch__.update_document_attributes title: "New title" + # @article.__opensearch__.update_document_attributes title: "New title" # - # @return [Hash] The response from Elasticsearch + # @return [Hash] The response from OpenSearch # def update_document_attributes(attributes, options={}) request = { index: index_name, id: self.id, body: { doc: attributes } } - request.merge!(type: document_type) if document_type client.update(request.merge!(options)) end diff --git a/elasticsearch-model/lib/elasticsearch/model/multimodel.rb b/opensearch-model/lib/opensearch/model/multimodel.rb similarity index 91% rename from elasticsearch-model/lib/elasticsearch/model/multimodel.rb rename to opensearch-model/lib/opensearch/model/multimodel.rb index 6b5fc2a81..03ded9746 100644 --- a/elasticsearch-model/lib/elasticsearch/model/multimodel.rb +++ b/opensearch-model/lib/opensearch/model/multimodel.rb @@ -15,10 +15,10 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model - # Keeps a global registry of classes that include `Elasticsearch::Model` + # Keeps a global registry of classes that include `OpenSearch::Model` # class Registry def initialize @@ -60,7 +60,7 @@ def models # Wraps a collection of models when querying multiple indices # - # @see Elasticsearch::Model.search + # @see OpenSearch::Model.search # class Multimodel attr_reader :models @@ -90,10 +90,10 @@ def document_type # Get the client common for all models # - # @return Elasticsearch::Transport::Client + # @return OpenSearch::Transport::Client # def client - Elasticsearch::Model.client + OpenSearch::Model.client end end end diff --git a/elasticsearch-model/lib/elasticsearch/model/naming.rb b/opensearch-model/lib/opensearch/model/naming.rb similarity index 96% rename from elasticsearch-model/lib/elasticsearch/model/naming.rb rename to opensearch-model/lib/opensearch/model/naming.rb index c4c796ab2..3562656cd 100644 --- a/elasticsearch-model/lib/elasticsearch/model/naming.rb +++ b/opensearch-model/lib/opensearch/model/naming.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Provides methods for getting and setting index name and document type for the model @@ -109,7 +109,7 @@ module InstanceMethods # @example Set the index name for an instance of the `Article` model # # @article.index_name "articles-#{@article.user_id}" - # @article.__elasticsearch__.update_document + # @article.__opensearch__.update_document # def index_name name=nil, &block if name || block_given? @@ -133,7 +133,7 @@ def index_name=(name) # @example Set the document type for an instance of the `Article` model # # @article.document_type "my-article" - # @article.__elasticsearch__.update_document + # @article.__opensearch__.update_document # def document_type name=nil @document_type = name || @document_type || self.class.document_type diff --git a/elasticsearch-model/lib/elasticsearch/model/proxy.rb b/opensearch-model/lib/opensearch/model/proxy.rb similarity index 64% rename from elasticsearch-model/lib/elasticsearch/model/proxy.rb rename to opensearch-model/lib/opensearch/model/proxy.rb index 6fdf66322..397f59581 100644 --- a/elasticsearch-model/lib/elasticsearch/model/proxy.rb +++ b/opensearch-model/lib/opensearch/model/proxy.rb @@ -15,25 +15,25 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # This module provides a proxy interfacing between the including class and - # `Elasticsearch::Model`, preventing the pollution of the including class namespace. + # `OpenSearch::Model`, preventing the pollution of the including class namespace. # - # The only "gateway" between the model and Elasticsearch::Model is the - # `#__elasticsearch__` class and instance method. + # The only "gateway" between the model and OpenSearch::Model is the + # `#__opensearch__` class and instance method. # # The including class must be compatible with # [ActiveModel](https://github.com/rails/rails/tree/master/activemodel). # - # @example Include the `Elasticsearch::Model` module into an `Article` model + # @example Include the `OpenSearch::Model` module into an `Article` model # # class Article < ActiveRecord::Base - # include Elasticsearch::Model + # include OpenSearch::Model # end # - # Article.__elasticsearch__.respond_to?(:search) + # Article.__opensearch__.respond_to?(:search) # # => true # # article = Article.first @@ -41,35 +41,35 @@ module Model # article.respond_to? :index_document # # => false # - # article.__elasticsearch__.respond_to?(:index_document) + # article.__opensearch__.respond_to?(:index_document) # # => true # module Proxy - # Define the `__elasticsearch__` class and instance methods in the including class + # Define the `__opensearch__` class and instance methods in the including class # and register a callback for intercepting changes in the model. # - # @note The callback is triggered only when `Elasticsearch::Model` is included in the + # @note The callback is triggered only when `OpenSearch::Model` is included in the # module and the functionality is accessible via the proxy. # def self.included(base) base.class_eval do - # `ClassMethodsProxy` instance, accessed as `MyModel.__elasticsearch__` - def self.__elasticsearch__ &block - @__elasticsearch__ ||= ClassMethodsProxy.new(self) - @__elasticsearch__.instance_eval(&block) if block_given? - @__elasticsearch__ + # `ClassMethodsProxy` instance, accessed as `MyModel.__opensearch__` + def self.__opensearch__ &block + @__opensearch__ ||= ClassMethodsProxy.new(self) + @__opensearch__.instance_eval(&block) if block_given? + @__opensearch__ end # Mix the importing module into the `ClassMethodsProxy` - self.__elasticsearch__.class_eval do + self.__opensearch__.class_eval do include Adapter.from_class(base).importing_mixin end # Register a callback for storing changed attributes for models which implement - # `before_save` method and return changed attributes (ie. when `Elasticsearch::Model` is included) + # `before_save` method and return changed attributes (ie. when `OpenSearch::Model` is included) # # @see http://api.rubyonrails.org/classes/ActiveModel/Dirty.html # @@ -81,28 +81,28 @@ def self.__elasticsearch__ &block end if changes_to_save - attrs = obj.__elasticsearch__.instance_variable_get(:@__changed_model_attributes) || {} + attrs = obj.__opensearch__.instance_variable_get(:@__changed_model_attributes) || {} latest_changes = changes_to_save.inject({}) { |latest_changes, (k,v)| latest_changes.merge!(k => v.last) } - obj.__elasticsearch__.instance_variable_set(:@__changed_model_attributes, attrs.merge(latest_changes)) + obj.__opensearch__.instance_variable_set(:@__changed_model_attributes, attrs.merge(latest_changes)) end end if respond_to?(:before_save) end - # {InstanceMethodsProxy}, accessed as `@mymodel.__elasticsearch__` + # {InstanceMethodsProxy}, accessed as `@mymodel.__opensearch__` # - def __elasticsearch__ &block - @__elasticsearch__ ||= InstanceMethodsProxy.new(self) - @__elasticsearch__.instance_eval(&block) if block_given? - @__elasticsearch__ + def __opensearch__ &block + @__opensearch__ ||= InstanceMethodsProxy.new(self) + @__opensearch__.instance_eval(&block) if block_given? + @__opensearch__ end end # @overload dup # - # Returns a copy of this object. Resets the __elasticsearch__ proxy so + # Returns a copy of this object. Resets the __opensearch__ proxy so # the duplicate will build its own proxy. def initialize_dup(_) - @__elasticsearch__ = nil + @__opensearch__ = nil super end @@ -135,36 +135,36 @@ def inspect end end - # A proxy interfacing between Elasticsearch::Model class methods and model class methods + # A proxy interfacing between OpenSearch::Model class methods and model class methods # # TODO: Inherit from BasicObject and make Pry's `ls` command behave? # class ClassMethodsProxy include Base - include Elasticsearch::Model::Client::ClassMethods - include Elasticsearch::Model::Naming::ClassMethods - include Elasticsearch::Model::Indexing::ClassMethods - include Elasticsearch::Model::Searching::ClassMethods - include Elasticsearch::Model::Importing::ClassMethods + include OpenSearch::Model::Client::ClassMethods + include OpenSearch::Model::Naming::ClassMethods + include OpenSearch::Model::Indexing::ClassMethods + include OpenSearch::Model::Searching::ClassMethods + include OpenSearch::Model::Importing::ClassMethods end - # A proxy interfacing between Elasticsearch::Model instance methods and model instance methods + # A proxy interfacing between OpenSearch::Model instance methods and model instance methods # # TODO: Inherit from BasicObject and make Pry's `ls` command behave? # class InstanceMethodsProxy include Base - include Elasticsearch::Model::Client::InstanceMethods - include Elasticsearch::Model::Naming::InstanceMethods - include Elasticsearch::Model::Indexing::InstanceMethods - include Elasticsearch::Model::Serializing::InstanceMethods + include OpenSearch::Model::Client::InstanceMethods + include OpenSearch::Model::Naming::InstanceMethods + include OpenSearch::Model::Indexing::InstanceMethods + include OpenSearch::Model::Serializing::InstanceMethods def klass target.class end def class - klass.__elasticsearch__ + klass.__opensearch__ end # Need to redefine `as_json` because we're not inheriting from `BasicObject`; diff --git a/elasticsearch-model/lib/elasticsearch/model/response.rb b/opensearch-model/lib/opensearch/model/response.rb similarity index 92% rename from elasticsearch-model/lib/elasticsearch/model/response.rb rename to opensearch-model/lib/opensearch/model/response.rb index 5d79a1827..eb182a9d5 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response.rb +++ b/opensearch-model/lib/opensearch/model/response.rb @@ -15,14 +15,14 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model - # Contains modules and classes for wrapping the response from Elasticsearch + # Contains modules and classes for wrapping the response from OpenSearch # module Response - # Encapsulate the response returned from the Elasticsearch client + # Encapsulate the response returned from the OpenSearch client # # Implements Enumerable and forwards its methods to the {#results} object. # @@ -38,7 +38,7 @@ def initialize(klass, search, options={}) @search = search end - # Returns the Elasticsearch response + # Returns the OpenSearch response # # @return [Hash] # @@ -46,7 +46,7 @@ def response @response ||= HashWrapper.new(search.execute!) end - # Returns the collection of "hits" from Elasticsearch + # Returns the collection of "hits" from OpenSearch # # @return [Results] # diff --git a/elasticsearch-model/lib/elasticsearch/model/response/aggregations.rb b/opensearch-model/lib/opensearch/model/response/aggregations.rb similarity index 98% rename from elasticsearch-model/lib/elasticsearch/model/response/aggregations.rb rename to opensearch-model/lib/opensearch/model/response/aggregations.rb index 6fc4a8e89..f7d882543 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/aggregations.rb +++ b/opensearch-model/lib/opensearch/model/response/aggregations.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response diff --git a/elasticsearch-model/lib/elasticsearch/model/response/base.rb b/opensearch-model/lib/opensearch/model/response/base.rb similarity index 93% rename from elasticsearch-model/lib/elasticsearch/model/response/base.rb rename to opensearch-model/lib/opensearch/model/response/base.rb index 21853d5bb..fa703dd41 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/base.rb +++ b/opensearch-model/lib/opensearch/model/response/base.rb @@ -15,16 +15,16 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response - # Common funtionality for classes in the {Elasticsearch::Model::Response} module + # Common funtionality for classes in the {OpenSearch::Model::Response} module # module Base attr_reader :klass, :response, :raw_response # @param klass [Class] The name of the model class - # @param response [Hash] The full response returned from Elasticsearch client + # @param response [Hash] The full response returned from OpenSearch client # @param options [Hash] Optional parameters # def initialize(klass, response, options={}) diff --git a/elasticsearch-model/lib/elasticsearch/model/response/pagination.rb b/opensearch-model/lib/opensearch/model/response/pagination.rb similarity index 86% rename from elasticsearch-model/lib/elasticsearch/model/response/pagination.rb rename to opensearch-model/lib/opensearch/model/response/pagination.rb index f12604179..1face4b3b 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/pagination.rb +++ b/opensearch-model/lib/opensearch/model/response/pagination.rb @@ -15,5 +15,5 @@ # specific language governing permissions and limitations # under the License. -require 'elasticsearch/model/response/pagination/kaminari' -require 'elasticsearch/model/response/pagination/will_paginate' +require 'opensearch/model/response/pagination/kaminari' +require 'opensearch/model/response/pagination/will_paginate' diff --git a/elasticsearch-model/lib/elasticsearch/model/response/pagination/kaminari.rb b/opensearch-model/lib/opensearch/model/response/pagination/kaminari.rb similarity index 85% rename from elasticsearch-model/lib/elasticsearch/model/response/pagination/kaminari.rb rename to opensearch-model/lib/opensearch/model/response/pagination/kaminari.rb index 66de07ccb..13f9cbee5 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/pagination/kaminari.rb +++ b/opensearch-model/lib/opensearch/model/response/pagination/kaminari.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response @@ -33,12 +33,12 @@ def self.included(base) # Include the Kaminari paging methods in results and records # - Elasticsearch::Model::Response::Results.__send__ :include, ::Kaminari::ConfigurationMethods::ClassMethods - Elasticsearch::Model::Response::Results.__send__ :include, ::Kaminari::PageScopeMethods - Elasticsearch::Model::Response::Records.__send__ :include, ::Kaminari::PageScopeMethods + OpenSearch::Model::Response::Results.__send__ :include, ::Kaminari::ConfigurationMethods::ClassMethods + OpenSearch::Model::Response::Results.__send__ :include, ::Kaminari::PageScopeMethods + OpenSearch::Model::Response::Records.__send__ :include, ::Kaminari::PageScopeMethods - Elasticsearch::Model::Response::Results.__send__ :delegate, :limit_value, :offset_value, :total_count, :max_pages, to: :response - Elasticsearch::Model::Response::Records.__send__ :delegate, :limit_value, :offset_value, :total_count, :max_pages, to: :response + OpenSearch::Model::Response::Results.__send__ :delegate, :limit_value, :offset_value, :total_count, :max_pages, to: :response + OpenSearch::Model::Response::Records.__send__ :delegate, :limit_value, :offset_value, :total_count, :max_pages, to: :response base.class_eval <<-RUBY, __FILE__, __LINE__ + 1 # Define the `page` Kaminari method diff --git a/elasticsearch-model/lib/elasticsearch/model/response/pagination/will_paginate.rb b/opensearch-model/lib/opensearch/model/response/pagination/will_paginate.rb similarity index 93% rename from elasticsearch-model/lib/elasticsearch/model/response/pagination/will_paginate.rb rename to opensearch-model/lib/opensearch/model/response/pagination/will_paginate.rb index 2d4658544..b5a3b1a67 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/pagination/will_paginate.rb +++ b/opensearch-model/lib/opensearch/model/response/pagination/will_paginate.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response @@ -33,8 +33,8 @@ def self.included(base) # Include the paging methods in results and records # methods = [:current_page, :offset, :length, :per_page, :total_entries, :total_pages, :previous_page, :next_page, :out_of_bounds?] - Elasticsearch::Model::Response::Results.__send__ :delegate, *methods, to: :response - Elasticsearch::Model::Response::Records.__send__ :delegate, *methods, to: :response + OpenSearch::Model::Response::Results.__send__ :delegate, *methods, to: :response + OpenSearch::Model::Response::Records.__send__ :delegate, *methods, to: :response end def offset diff --git a/elasticsearch-model/lib/elasticsearch/model/response/records.rb b/opensearch-model/lib/opensearch/model/response/records.rb similarity index 95% rename from elasticsearch-model/lib/elasticsearch/model/response/records.rb rename to opensearch-model/lib/opensearch/model/response/records.rb index e18ecc83d..390307fa6 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/records.rb +++ b/opensearch-model/lib/opensearch/model/response/records.rb @@ -15,14 +15,14 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response # Encapsulates the collection of records returned from the database # # Implements Enumerable and forwards its methods to the {#records} object, - # which is provided by an {Elasticsearch::Model::Adapter::Adapter} implementation. + # which is provided by an {OpenSearch::Model::Adapter::Adapter} implementation. # class Records include Enumerable diff --git a/elasticsearch-model/lib/elasticsearch/model/response/result.rb b/opensearch-model/lib/opensearch/model/response/result.rb similarity index 96% rename from elasticsearch-model/lib/elasticsearch/model/response/result.rb rename to opensearch-model/lib/opensearch/model/response/result.rb index 5e102c2b3..328a5d21e 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/result.rb +++ b/opensearch-model/lib/opensearch/model/response/result.rb @@ -15,11 +15,11 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response - # Encapsulates the "hit" returned from the Elasticsearch client + # Encapsulates the "hit" returned from the OpenSearch client # # Wraps the raw Hash with in a `Hashie::Mash` instance, providing # access to the Hash properties by calling Ruby methods. diff --git a/elasticsearch-model/lib/elasticsearch/model/response/results.rb b/opensearch-model/lib/opensearch/model/response/results.rb similarity index 93% rename from elasticsearch-model/lib/elasticsearch/model/response/results.rb rename to opensearch-model/lib/opensearch/model/response/results.rb index 564a684a3..d5a085a0d 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/results.rb +++ b/opensearch-model/lib/opensearch/model/response/results.rb @@ -15,11 +15,11 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response - # Encapsulates the collection of documents returned from Elasticsearch + # Encapsulates the collection of documents returned from OpenSearch # # Implements Enumerable and forwards its methods to the {#results} object. # diff --git a/elasticsearch-model/lib/elasticsearch/model/response/suggestions.rb b/opensearch-model/lib/opensearch/model/response/suggestions.rb similarity index 98% rename from elasticsearch-model/lib/elasticsearch/model/response/suggestions.rb rename to opensearch-model/lib/opensearch/model/response/suggestions.rb index 72261a930..15e1ab45b 100644 --- a/elasticsearch-model/lib/elasticsearch/model/response/suggestions.rb +++ b/opensearch-model/lib/opensearch/model/response/suggestions.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model module Response diff --git a/elasticsearch-model/lib/elasticsearch/model/searching.rb b/opensearch-model/lib/opensearch/model/searching.rb similarity index 89% rename from elasticsearch-model/lib/elasticsearch/model/searching.rb rename to opensearch-model/lib/opensearch/model/searching.rb index 714f98a22..6dab12b4c 100644 --- a/elasticsearch-model/lib/elasticsearch/model/searching.rb +++ b/opensearch-model/lib/opensearch/model/searching.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Contains functionality related to searching. @@ -30,14 +30,13 @@ class SearchRequest # @param klass [Class] The class of the model # @param query_or_payload [String,Hash,Object] The search request definition # (string, JSON, Hash, or object responding to `to_hash`) - # @param options [Hash] Optional parameters to be passed to the Elasticsearch client + # @param options [Hash] Optional parameters to be passed to the OpenSearch client # def initialize(klass, query_or_payload, options={}) @klass = klass @options = options __index_name = options[:index] || klass.index_name - __document_type = options[:type] || klass.document_type case # search query: ... @@ -54,15 +53,15 @@ def initialize(klass, query_or_payload, options={}) end if body - @definition = { index: __index_name, type: __document_type, body: body }.update options + @definition = { index: __index_name, body: body }.update options else - @definition = { index: __index_name, type: __document_type, q: q }.update options + @definition = { index: __index_name, q: q }.update options end end # Performs the request and returns the response from client # - # @return [Hash] The response from Elasticsearch + # @return [Hash] The response from OpenSearch # def execute! klass.client.search(@definition) @@ -71,14 +70,14 @@ def execute! module ClassMethods - # Provides a `search` method for the model to easily search within an index/type + # Provides a `search` method for the model to easily search within an index # corresponding to the model settings. # # @param query_or_payload [String,Hash,Object] The search request definition # (string, JSON, Hash, or object responding to `to_hash`) - # @param options [Hash] Optional parameters to be passed to the Elasticsearch client + # @param options [Hash] Optional parameters to be passed to the OpenSearch client # - # @return [Elasticsearch::Model::Response::Response] + # @return [OpenSearch::Model::Response::Response] # # @example Simple search in `Article` # diff --git a/elasticsearch-model/lib/elasticsearch/model/serializing.rb b/opensearch-model/lib/opensearch/model/serializing.rb similarity index 92% rename from elasticsearch-model/lib/elasticsearch/model/serializing.rb rename to opensearch-model/lib/opensearch/model/serializing.rb index 9433dfa12..626f6bbcd 100644 --- a/elasticsearch-model/lib/elasticsearch/model/serializing.rb +++ b/opensearch-model/lib/opensearch/model/serializing.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model # Contains functionality for serializing model instances for the client @@ -35,10 +35,10 @@ module InstanceMethods # # @example Return the model instance as a Hash # - # Article.first.__elasticsearch__.as_indexed_json + # Article.first.__opensearch__.as_indexed_json # => {"title"=>"Foo"} # - # @see Elasticsearch::Model::Indexing + # @see OpenSearch::Model::Indexing # def as_indexed_json(options={}) # TODO: Play with the `MyModel.indexes` method -- reject non-mapped attributes, `:as` options, etc diff --git a/elasticsearch-model/lib/elasticsearch/model/version.rb b/opensearch-model/lib/opensearch/model/version.rb similarity index 94% rename from elasticsearch-model/lib/elasticsearch/model/version.rb rename to opensearch-model/lib/opensearch/model/version.rb index cdd631896..ee92d7fb0 100644 --- a/elasticsearch-model/lib/elasticsearch/model/version.rb +++ b/opensearch-model/lib/opensearch/model/version.rb @@ -15,8 +15,8 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Model - VERSION = "7.2.1" + VERSION = "1.0.0" end end diff --git a/elasticsearch-model/elasticsearch-model.gemspec b/opensearch-model/opensearch-model.gemspec similarity index 76% rename from elasticsearch-model/elasticsearch-model.gemspec rename to opensearch-model/opensearch-model.gemspec index 083938d51..ae8a64a03 100644 --- a/elasticsearch-model/elasticsearch-model.gemspec +++ b/opensearch-model/opensearch-model.gemspec @@ -19,16 +19,16 @@ lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'elasticsearch/model/version' +require 'opensearch/model/version' Gem::Specification.new do |s| - s.name = 'elasticsearch-model' - s.version = Elasticsearch::Model::VERSION - s.authors = ['Karel Minarik'] - s.email = ['karel.minarik@elasticsearch.org'] - s.description = 'ActiveModel/Record integrations for Elasticsearch.' - s.summary = 'ActiveModel/Record integrations for Elasticsearch.' - s.homepage = 'https://github.com/elasticsearch/elasticsearch-rails/' + s.name = 'opensearch-model' + s.version = OpenSearch::Model::VERSION + s.authors = ['CDD Solutions B.V.'] + s.email = ['developers@compliance-innovations.com'] + s.description = 'ActiveModel/Record integrations for OpenSearch.' + s.summary = 'ActiveModel/Record integrations for OpenSearch.' + s.homepage = 'https://github.com/compliance-innovations/opensearch-rails/' s.license = 'Apache 2' s.files = `git ls-files`.split($/) @@ -39,13 +39,13 @@ Gem::Specification.new do |s| s.extra_rdoc_files = ['README.md', 'LICENSE.txt'] s.rdoc_options = ['--charset=UTF-8'] - s.required_ruby_version = '>= 2.4' + s.required_ruby_version = '>= 2.5' - s.add_dependency 'activesupport', '> 3' - s.add_dependency 'elasticsearch', '~> 7' + s.add_dependency 'activesupport', '>= 6.1' + s.add_dependency "opensearch-ruby", '~> 3.0' s.add_dependency 'hashie' - s.add_development_dependency 'activemodel', '> 3' + s.add_development_dependency 'activemodel', '>= 6.1' s.add_development_dependency 'bundler' s.add_development_dependency 'cane' s.add_development_dependency 'kaminari' diff --git a/elasticsearch-model/spec/elasticsearch/model/adapter_spec.rb b/opensearch-model/spec/opensearch/model/adapter_spec.rb similarity index 67% rename from elasticsearch-model/spec/elasticsearch/model/adapter_spec.rb rename to opensearch-model/spec/opensearch/model/adapter_spec.rb index 33dd62590..fad80abee 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapter_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapter_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter do +describe OpenSearch::Model::Adapter do before(:all) do class ::DummyAdapterClass; end @@ -31,7 +31,7 @@ class ::DummyAdapter after(:all) do [DummyAdapterClassWithAdapter, DummyAdapterClass, DummyAdapter].each do |adapter| - Elasticsearch::Model::Adapter::Adapter.adapters.delete(adapter) + OpenSearch::Model::Adapter::Adapter.adapters.delete(adapter) end remove_classes(DummyAdapterClass, DummyAdapterClassWithAdapter, DummyAdapter) end @@ -39,31 +39,31 @@ class ::DummyAdapter describe '#from_class' do it 'should return an Adapter instance' do - expect(Elasticsearch::Model::Adapter.from_class(DummyAdapterClass)).to be_a(Elasticsearch::Model::Adapter::Adapter) + expect(OpenSearch::Model::Adapter.from_class(DummyAdapterClass)).to be_a(OpenSearch::Model::Adapter::Adapter) end end describe 'register' do before do - expect(Elasticsearch::Model::Adapter::Adapter).to receive(:register).and_call_original - Elasticsearch::Model::Adapter.register(:foo, lambda { |c| false }) + expect(OpenSearch::Model::Adapter::Adapter).to receive(:register).and_call_original + OpenSearch::Model::Adapter.register(:foo, lambda { |c| false }) end it 'should register an adapter' do - expect(Elasticsearch::Model::Adapter::Adapter.adapters[:foo]).to be_a(Proc) + expect(OpenSearch::Model::Adapter::Adapter.adapters[:foo]).to be_a(Proc) end context 'when a specific adapter class is set' do before do - expect(Elasticsearch::Model::Adapter::Adapter).to receive(:register).and_call_original - Elasticsearch::Model::Adapter::Adapter.register(DummyAdapter, + expect(OpenSearch::Model::Adapter::Adapter).to receive(:register).and_call_original + OpenSearch::Model::Adapter::Adapter.register(DummyAdapter, lambda { |c| c == DummyAdapterClassWithAdapter }) end let(:adapter) do - Elasticsearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) + OpenSearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) end it 'should register the adapter' do @@ -75,24 +75,24 @@ class ::DummyAdapter describe 'default adapter' do let(:adapter) do - Elasticsearch::Model::Adapter::Adapter.new(DummyAdapterClass) + OpenSearch::Model::Adapter::Adapter.new(DummyAdapterClass) end it 'sets a default adapter' do - expect(adapter.adapter).to eq(Elasticsearch::Model::Adapter::Default) + expect(adapter.adapter).to eq(OpenSearch::Model::Adapter::Default) end end describe '#records_mixin' do before do - Elasticsearch::Model::Adapter::Adapter.register(DummyAdapter, + OpenSearch::Model::Adapter::Adapter.register(DummyAdapter, lambda { |c| c == DummyAdapterClassWithAdapter }) end let(:adapter) do - Elasticsearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) + OpenSearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) end it 'returns a Module' do @@ -103,13 +103,13 @@ class ::DummyAdapter describe '#callbacks_mixin' do before do - Elasticsearch::Model::Adapter::Adapter.register(DummyAdapter, + OpenSearch::Model::Adapter::Adapter.register(DummyAdapter, lambda { |c| c == DummyAdapterClassWithAdapter }) end let(:adapter) do - Elasticsearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) + OpenSearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) end it 'returns a Module' do @@ -120,13 +120,13 @@ class ::DummyAdapter describe '#importing_mixin' do before do - Elasticsearch::Model::Adapter::Adapter.register(DummyAdapter, + OpenSearch::Model::Adapter::Adapter.register(DummyAdapter, lambda { |c| c == DummyAdapterClassWithAdapter }) end let(:adapter) do - Elasticsearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) + OpenSearch::Model::Adapter::Adapter.new(DummyAdapterClassWithAdapter) end it 'returns a Module' do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/associations_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/associations_spec.rb similarity index 93% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/associations_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/associations_spec.rb index c3e460ffb..95fa773d3 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/associations_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/associations_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Associations' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Associations' do before(:all) do ActiveRecord::Schema.define(version: 1) do @@ -59,15 +59,15 @@ end end - Comment.__send__ :include, Elasticsearch::Model - Comment.__send__ :include, Elasticsearch::Model::Callbacks + Comment.__send__ :include, OpenSearch::Model + Comment.__send__ :include, OpenSearch::Model::Callbacks end before do clear_tables(:categories, :categories_posts, :authors, :authorships, :comments, :posts) clear_indices(Post) - Post.__elasticsearch__.create_index!(force: true) - Comment.__elasticsearch__.create_index!(force: true) + Post.__opensearch__.create_index!(force: true) + Comment.__opensearch__.create_index!(force: true) end after do @@ -81,7 +81,7 @@ Post.create!(title: 'Test') Post.create!(title: 'Testing Coding') Post.create!(title: 'Coding') - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end let(:search_result) do @@ -102,7 +102,7 @@ before do post.categories = [category_a, category_b] - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end let(:category_a) do @@ -148,7 +148,7 @@ before do post.categories = [category_a, category_b] post.categories = [category_b] - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end let(:category_a) do @@ -207,7 +207,7 @@ post_2.authors = [author_a] post_3.authors = [author_c] - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end context 'if active record is at least 4' do @@ -247,7 +247,7 @@ # Assign authors post_1.authors = [author_a] post_1.authors << author_b - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end let(:search_result) do @@ -277,7 +277,7 @@ post_2.comments.create!(author: 'John', text: 'Terrible') post_1.comments.create!(author: 'John', text: 'Or rather just good...') - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end let(:search_result) do @@ -318,7 +318,7 @@ category_a.update_attribute(:title, "Updated") category_a.posts.each { |p| p.touch } - Post.__elasticsearch__.refresh_index! + Post.__opensearch__.refresh_index! end it 'executes the callback after #touch' do @@ -336,7 +336,7 @@ post_1.comments.create(text: 'First comment') post_2.comments.create(text: 'Second comment') - Comment.__elasticsearch__.refresh_index! + Comment.__opensearch__.refresh_index! end let(:search_result) do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/basic_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/basic_spec.rb similarity index 89% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/basic_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/basic_spec.rb index a769b38f6..601d507e8 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/basic_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/basic_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter::ActiveRecord do +describe OpenSearch::Model::Adapter::ActiveRecord do context 'when a document_type is not defined for the Model' do @@ -32,13 +32,13 @@ end ArticleNoType.delete_all - ArticleNoType.__elasticsearch__.create_index!(force: true) + ArticleNoType.__opensearch__.create_index!(force: true) ArticleNoType.create!(title: 'Test', body: '', clicks: 1) ArticleNoType.create!(title: 'Testing Coding', body: '', clicks: 2) ArticleNoType.create!(title: 'Coding', body: '', clicks: 3) - ArticleNoType.__elasticsearch__.refresh_index! + ArticleNoType.__opensearch__.refresh_index! end describe 'indexing a document' do @@ -67,13 +67,13 @@ end Article.delete_all - Article.__elasticsearch__.create_index!(force: true, include_type_name: true) + Article.__opensearch__.create_index!(force: true) Article.create!(title: 'Test', body: '', clicks: 1) Article.create!(title: 'Testing Coding', body: '', clicks: 2) Article.create!(title: 'Coding', body: '', clicks: 3) - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! end describe 'indexing a document' do @@ -95,7 +95,7 @@ end it 'returns an instance of Response::Result' do - expect(search_result.results.first).to be_a(Elasticsearch::Model::Response::Result) + expect(search_result.results.first).to be_a(OpenSearch::Model::Response::Result) end it 'prooperly loads the document' do @@ -108,7 +108,7 @@ Article.search(query: { match: { title: 'test' } }, highlight: { fields: { title: {} } }) end - it 'allows access to the Elasticsearch result' do + it 'allows access to the OpenSearch result' do expect(search_result.results.first.title).to eq('Test') expect(search_result.results.first.title?).to be(true) expect(search_result.results.first.boo?).to be(false) @@ -160,24 +160,13 @@ end end - describe '#id' do - - let(:search_result) do - Article.search('title:test') - end - - it 'returns the type' do - expect(search_result.results.first.type).to eq('article') - end - end - describe '#each_with_hit' do let(:search_result) do Article.search('title:test') end - it 'returns the record with the Elasticsearch hit' do + it 'returns the record with the OpenSearch hit' do search_result.records.each_with_hit do |r, h| expect(h._score).not_to be_nil expect(h._source.title).not_to be_nil @@ -228,10 +217,10 @@ before do Article.create!(title: 'destroy', body: '', clicks: 1) - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! Article.where(title: 'destroy').first.destroy - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! end let(:search_result) do @@ -249,11 +238,11 @@ before do article = Article.create!(title: 'update', body: '', clicks: 1) - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! article.title = 'Writing' article.save - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! end let(:search_result) do @@ -270,11 +259,11 @@ before do article = Article.create!(title: 'update', body: '', clicks: 1) - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! article.title = 'special' article.save - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.refresh_index! end let(:search_result) do @@ -300,8 +289,8 @@ article.save end - article.__elasticsearch__.update_document - Article.__elasticsearch__.refresh_index! + article.__opensearch__.update_document + Article.__opensearch__.refresh_index! end let(:search_result) do @@ -347,12 +336,12 @@ Article.search query: { match: { title: { query: 'test' } } } end - it 'allows the SQL query to be ordered independent of the Elasticsearch results order', unless: active_record_at_least_4? do + it 'allows the SQL query to be ordered independent of the OpenSearch results order', unless: active_record_at_least_4? do expect(search_result.records.order('title DESC').first.title).to eq('Testing Coding') expect(search_result.records.order('title DESC')[0].title).to eq('Testing Coding') end - it 'allows the SQL query to be ordered independent of the Elasticsearch results order', if: active_record_at_least_4? do + it 'allows the SQL query to be ordered independent of the OpenSearch results order', if: active_record_at_least_4? do expect(search_result.records.order(title: :desc).first.title).to eq('Testing Coding') expect(search_result.records.order(title: :desc)[0].title).to eq('Testing Coding') end @@ -364,7 +353,7 @@ Article.search query: {match: {title: {query: 'test'}}} end - it 'allows the SQL query to be ordered independent of the Elasticsearch results order', if: active_record_at_least_4? do + it 'allows the SQL query to be ordered independent of the OpenSearch results order', if: active_record_at_least_4? do expect(search_result.records.distinct.order(title: :desc).first.title).to eq('Testing Coding') expect(search_result.records.distinct.order(title: :desc)[0].title).to eq('Testing Coding') end diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/dynamic_index_name_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/dynamic_index_name_spec.rb similarity index 94% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/dynamic_index_name_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/dynamic_index_name_spec.rb index abb4a0bdc..4c1c14b28 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/dynamic_index_name_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/dynamic_index_name_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Dynamic Index naming' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Dynamic Index naming' do before do ArticleWithDynamicIndexName.counter = 0 diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/import_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/import_spec.rb similarity index 86% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/import_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/import_spec.rb index 1f5fe0847..fe19ae79d 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/import_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/import_spec.rb @@ -17,23 +17,23 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Importing' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Importing' do before(:all) do ActiveRecord::Schema.define(:version => 1) do create_table :import_articles do |t| t.string :title t.integer :views - t.string :numeric # For the sake of invalid data sent to Elasticsearch + t.string :numeric # For the sake of invalid data sent to OpenSearch t.datetime :created_at, :default => 'NOW()' end end ImportArticle.delete_all - ImportArticle.__elasticsearch__.client.cluster.health(wait_for_status: 'yellow') + ImportArticle.__opensearch__.client.cluster.health(wait_for_status: 'yellow') end before do - ImportArticle.__elasticsearch__.create_index! + ImportArticle.__opensearch__.create_index! end after do @@ -46,7 +46,7 @@ before do 10.times { |i| ImportArticle.create! title: 'Test', views: i.to_s } ImportArticle.import - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! end it 'imports all documents' do @@ -64,7 +64,7 @@ errors = ImportArticle.import(batch_size: 5) do |response| batches += 1 end - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! batches end @@ -81,7 +81,7 @@ before do 10.times { |i| ImportArticle.create! title: 'Test', views: "#{i}" } ImportArticle.import(scope: 'popular', force: true) - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! end it 'applies the scope' do @@ -93,7 +93,7 @@ before do 10.times { |i| ImportArticle.create! title: 'Test', views: "#{i}" } ImportArticle.import(query: -> { where('views >= 3') }) - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! end it 'applies the query' do @@ -106,10 +106,10 @@ 10.times { |i| ImportArticle.create! title: 'Test', views: "#{i}" } new_article batches = 0 - errors = ImportArticle.__elasticsearch__.import(batch_size: 5) do |response| + errors = ImportArticle.__opensearch__.import(batch_size: 5) do |response| batches += 1 end - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! { batch_size: batches, errors: errors} end @@ -128,7 +128,7 @@ before do 10.times { |i| ImportArticle.create! title: 'Test', views: "#{i}" } ImportArticle.import( transform: ->(a) {{ index: { data: { name: a.title, foo: 'BAR' } }}} ) - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! end it 'transforms the documents' do @@ -151,8 +151,8 @@ end before do - ImportArticle.__elasticsearch__.import - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.import + ImportArticle.__opensearch__.refresh_index! end it 'uses the default scope' do @@ -170,7 +170,7 @@ before do ImportArticle.import(query: -> { where('views <= 4') }) - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! end it 'combines the query and the default scope' do @@ -182,7 +182,7 @@ before do ImportArticle.delete_all ImportArticle.import - ImportArticle.__elasticsearch__.refresh_index! + ImportArticle.__opensearch__.refresh_index! end it 'does not make any requests to create documents' do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/multi_model_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/multi_model_spec.rb similarity index 82% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/multi_model_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/multi_model_spec.rb index c8196242a..942b05d22 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/multi_model_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/multi_model_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord MultiModel' do +describe 'OpenSearch::Model::Adapter::ActiveRecord MultiModel' do before(:all) do ActiveRecord::Schema.define do @@ -37,11 +37,11 @@ models = [ Episode, Series ] clear_tables(models) models.each do |model| - model.__elasticsearch__.create_index! force: true + model.__opensearch__.create_index! force: true model.create name: "The #{model.name}" model.create name: "A great #{model.name}" model.create name: "The greatest #{model.name}" - model.__elasticsearch__.refresh_index! + model.__opensearch__.refresh_index! end end @@ -53,7 +53,7 @@ context 'when the search is across multimodels' do let(:search_result) do - Elasticsearch::Model.search(%q<"The greatest Episode"^2 OR "The greatest Series">, [Series, Episode]) + OpenSearch::Model.search(%q<"The greatest Episode"^2 OR "The greatest Series">, [Series, Episode]) end it 'executes the search across models' do @@ -63,9 +63,9 @@ describe '#results' do - it 'returns an instance of Elasticsearch::Model::Response::Result' do - expect(search_result.results[0]).to be_a(Elasticsearch::Model::Response::Result) - expect(search_result.results[1]).to be_a(Elasticsearch::Model::Response::Result) + it 'returns an instance of OpenSearch::Model::Response::Result' do + expect(search_result.results[0]).to be_a(OpenSearch::Model::Response::Result) + expect(search_result.results[1]).to be_a(OpenSearch::Model::Response::Result) end it 'returns the correct model instance' do @@ -86,7 +86,7 @@ describe '#records' do - it 'returns an instance of Elasticsearch::Model::Response::Result' do + it 'returns an instance of OpenSearch::Model::Response::Result' do expect(search_result.records[0]).to be_a(Episode) expect(search_result.records[1]).to be_a(Series) end @@ -100,7 +100,7 @@ before do Series.find_by_name("The greatest Series").delete - Series.__elasticsearch__.refresh_index! + Series.__opensearch__.refresh_index! end it 'only returns matching records' do @@ -114,7 +114,7 @@ describe 'pagination' do let(:search_result) do - Elasticsearch::Model.search('series OR episode', [Series, Episode]) + OpenSearch::Model.search('series OR episode', [Series, Episode]) end it 'properly paginates the results' do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/namespaced_model_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/namespaced_model_spec.rb similarity index 87% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/namespaced_model_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/namespaced_model_spec.rb index 730dad0e0..4071b147b 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/namespaced_model_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/namespaced_model_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Namespaced Model' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Namespaced Model' do before(:all) do ActiveRecord::Schema.define(:version => 1) do @@ -27,12 +27,12 @@ end MyNamespace::Book.delete_all - MyNamespace::Book.__elasticsearch__.create_index!(force: true, include_type_name: true) + MyNamespace::Book.__opensearch__.create_index!(force: true) MyNamespace::Book.create!(title: 'Test') - MyNamespace::Book.__elasticsearch__.refresh_index! + MyNamespace::Book.__opensearch__.refresh_index! end - after do + after(:all) do clear_indices(MyNamespace::Book) clear_tables(MyNamespace::Book) end diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/pagination_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/pagination_spec.rb similarity index 97% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/pagination_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/pagination_spec.rb index c4a503ed7..cfcd59447 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/pagination_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/pagination_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Pagination' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Pagination' do before(:all) do ActiveRecord::Schema.define(:version => 1) do @@ -30,14 +30,14 @@ Kaminari::Hooks.init if defined?(Kaminari::Hooks) - ArticleForPagination.__elasticsearch__.create_index! force: true + ArticleForPagination.__opensearch__.create_index! force: true 68.times do |i| ArticleForPagination.create! title: "Test #{i}", published: (i % 2 == 0) end ArticleForPagination.import - ArticleForPagination.__elasticsearch__.refresh_index! + ArticleForPagination.__opensearch__.refresh_index! end context 'when no other page is specified' do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/parent_child_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/parent_child_spec.rb similarity index 91% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/parent_child_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/parent_child_spec.rb index 5147943ee..9b62dc9ae 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/parent_child_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/parent_child_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Parent-Child' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Parent-Child' do before(:all) do ActiveRecord::Schema.define(version: 1) do @@ -38,7 +38,7 @@ add_index(:answers, :question_id) unless index_exists?(:answers, :question_id) clear_tables(Question) - ParentChildSearchable.create_index!(force: true, include_type_name: true) + ParentChildSearchable.create_index!(force: true) q_1 = Question.create!(title: 'First Question', author: 'John') q_2 = Question.create!(title: 'Second Question', author: 'Jody') @@ -48,7 +48,7 @@ q_2.answers.create!(text: 'Amet Et', author: 'John') - Question.__elasticsearch__.refresh_index! + Question.__opensearch__.refresh_index! end end @@ -78,7 +78,7 @@ before do Question.where(title: 'First Question').each(&:destroy) - Question.__elasticsearch__.refresh_index! + Question.__opensearch__.refresh_index! end let(:search_result) do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/serialization_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record/serialization_spec.rb similarity index 68% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record/serialization_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record/serialization_spec.rb index 3f01c348b..4a9bad0b8 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record/serialization_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record/serialization_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Serialization' do +describe 'OpenSearch::Model::Adapter::ActiveRecord Serialization' do before(:all) do ActiveRecord::Schema.define(:version => 1) do @@ -28,22 +28,20 @@ end ArticleWithCustomSerialization.delete_all - ArticleWithCustomSerialization.__elasticsearch__.create_index!(force: true) + ArticleWithCustomSerialization.__opensearch__.create_index!(force: true) end context 'when the model has a custom serialization defined' do before do ArticleWithCustomSerialization.create!(title: 'Test', status: 'green') - ArticleWithCustomSerialization.__elasticsearch__.refresh_index! + ArticleWithCustomSerialization.__opensearch__.refresh_index! end context 'when a document is indexed' do let(:search_result) do - ArticleWithCustomSerialization.__elasticsearch__.client.get(index: 'article_with_custom_serializations', - type: '_doc', - id: '1') + ArticleWithCustomSerialization.__opensearch__.client.get(index: 'article_with_custom_serializations', id: '1') end it 'applies the serialization when indexing' do @@ -54,19 +52,18 @@ context 'when a document is updated' do before do - article.update_attributes(title: 'UPDATED', status: 'yellow') - ArticleWithCustomSerialization.__elasticsearch__.refresh_index! + article.update(title: 'UPDATED', status: 'yellow') + ArticleWithCustomSerialization.__opensearch__.refresh_index! end let!(:article) do art = ArticleWithCustomSerialization.create!(title: 'Test', status: 'red') - ArticleWithCustomSerialization.__elasticsearch__.refresh_index! + ArticleWithCustomSerialization.__opensearch__.refresh_index! art end let(:search_result) do - ArticleWithCustomSerialization.__elasticsearch__.client.get(index: 'article_with_custom_serializations', - type: '_doc', + ArticleWithCustomSerialization.__opensearch__.client.get(index: 'article_with_custom_serializations', id: article.id) end diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record_spec.rb b/opensearch-model/spec/opensearch/model/adapters/active_record_spec.rb similarity index 86% rename from elasticsearch-model/spec/elasticsearch/model/adapters/active_record_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/active_record_spec.rb index 8a6fe0171..753c8d209 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/active_record_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/active_record_spec.rb @@ -17,14 +17,14 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter::ActiveRecord do +describe OpenSearch::Model::Adapter::ActiveRecord do before(:all) do class DummyClassForActiveRecord; end end after(:all) do - Elasticsearch::Model::Adapter::Adapter.adapters.delete(DummyClassForActiveRecord) + OpenSearch::Model::Adapter::Adapter.adapters.delete(DummyClassForActiveRecord) remove_classes(DummyClassForActiveRecord) end @@ -65,19 +65,19 @@ class DummyClassForActiveRecord; end describe 'adapter registration' do before(:all) do - DummyClassForActiveRecord.__send__ :include, Elasticsearch::Model::Adapter::ActiveRecord::Records + DummyClassForActiveRecord.__send__ :include, OpenSearch::Model::Adapter::ActiveRecord::Records end it 'can register an adapater' do - expect(Elasticsearch::Model::Adapter.adapters[Elasticsearch::Model::Adapter::ActiveRecord]).not_to be_nil - expect(Elasticsearch::Model::Adapter.adapters[Elasticsearch::Model::Adapter::ActiveRecord].call(DummyClassForActiveRecord)).to be(false) + expect(OpenSearch::Model::Adapter.adapters[OpenSearch::Model::Adapter::ActiveRecord]).not_to be_nil + expect(OpenSearch::Model::Adapter.adapters[OpenSearch::Model::Adapter::ActiveRecord].call(DummyClassForActiveRecord)).to be(false) end end describe '#records' do before(:all) do - DummyClassForActiveRecord.__send__ :include, Elasticsearch::Model::Adapter::ActiveRecord::Records + DummyClassForActiveRecord.__send__ :include, OpenSearch::Model::Adapter::ActiveRecord::Records end let(:instance) do @@ -115,14 +115,14 @@ class DummyClassForActiveRecord; end end it 'should register the model class for callbacks' do - Elasticsearch::Model::Adapter::ActiveRecord::Callbacks.included(DummyClassForActiveRecord) + OpenSearch::Model::Adapter::ActiveRecord::Callbacks.included(DummyClassForActiveRecord) end end describe 'importing' do before do - DummyClassForActiveRecord.__send__ :extend, Elasticsearch::Model::Adapter::ActiveRecord::Importing + DummyClassForActiveRecord.__send__ :extend, OpenSearch::Model::Adapter::ActiveRecord::Importing end context 'when an invalid scope is specified' do @@ -208,7 +208,7 @@ def update_batch(batch) let(:instance) do model.tap do |inst| allow(inst).to receive(:id).and_return(1) - allow(inst).to receive(:__elasticsearch__).and_return(double('object', id: 1, as_indexed_json: {})) + allow(inst).to receive(:__opensearch__).and_return(double('object', id: 1, as_indexed_json: {})) end end diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/default_spec.rb b/opensearch-model/spec/opensearch/model/adapters/default_spec.rb similarity index 74% rename from elasticsearch-model/spec/elasticsearch/model/adapters/default_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/default_spec.rb index cbc59fa70..6f7c64fd6 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/default_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/default_spec.rb @@ -17,16 +17,16 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter::Default do +describe OpenSearch::Model::Adapter::Default do before(:all) do class DummyClassForDefaultAdapter; end - DummyClassForDefaultAdapter.__send__ :include, Elasticsearch::Model::Adapter::Default::Records - DummyClassForDefaultAdapter.__send__ :include, Elasticsearch::Model::Adapter::Default::Importing + DummyClassForDefaultAdapter.__send__ :include, OpenSearch::Model::Adapter::Default::Records + DummyClassForDefaultAdapter.__send__ :include, OpenSearch::Model::Adapter::Default::Importing end after(:all) do - Elasticsearch::Model::Adapter::Adapter.adapters.delete(DummyClassForDefaultAdapter) + OpenSearch::Model::Adapter::Adapter.adapters.delete(DummyClassForDefaultAdapter) remove_classes(DummyClassForDefaultAdapter) end @@ -41,18 +41,18 @@ class DummyClassForDefaultAdapter; end end it 'should have the default Callback implementation' do - expect(Elasticsearch::Model::Adapter::Default::Callbacks).to be_a(Module) + expect(OpenSearch::Model::Adapter::Default::Callbacks).to be_a(Module) end it 'should have the default Importing implementation' do expect { DummyClassForDefaultAdapter.new.__find_in_batches - }.to raise_exception(Elasticsearch::Model::NotImplemented) + }.to raise_exception(OpenSearch::Model::NotImplemented) end it 'should have the default transform implementation' do expect { DummyClassForDefaultAdapter.new.__transform - }.to raise_exception(Elasticsearch::Model::NotImplemented) + }.to raise_exception(OpenSearch::Model::NotImplemented) end end diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/mongoid/basic_spec.rb b/opensearch-model/spec/opensearch/model/adapters/mongoid/basic_spec.rb similarity index 84% rename from elasticsearch-model/spec/elasticsearch/model/adapters/mongoid/basic_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/mongoid/basic_spec.rb index 0a0e71b58..22c84bc1f 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/mongoid/basic_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/mongoid/basic_spec.rb @@ -17,20 +17,20 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter::Mongoid, if: test_mongoid? do +describe OpenSearch::Model::Adapter::Mongoid, if: test_mongoid? do before(:all) do connect_mongoid('mongoid_test') - Elasticsearch::Model::Adapter.register \ - Elasticsearch::Model::Adapter::Mongoid, + OpenSearch::Model::Adapter.register \ + OpenSearch::Model::Adapter::Mongoid, lambda { |klass| !!defined?(::Mongoid::Document) && klass.respond_to?(:ancestors) && klass.ancestors.include?(::Mongoid::Document) } - MongoidArticle.__elasticsearch__.create_index! force: true + MongoidArticle.__opensearch__.create_index! force: true MongoidArticle.delete_all - MongoidArticle.__elasticsearch__.refresh_index! - MongoidArticle.__elasticsearch__.client.cluster.health wait_for_status: 'yellow' + MongoidArticle.__opensearch__.refresh_index! + MongoidArticle.__opensearch__.client.cluster.health wait_for_status: 'yellow' end after do @@ -44,7 +44,7 @@ MongoidArticle.create! title: 'Test' MongoidArticle.create! title: 'Testing Coding' MongoidArticle.create! title: 'Coding' - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end let(:search_result) do @@ -58,11 +58,11 @@ describe '#results' do - it 'returns a Elasticsearch::Model::Response::Result' do - expect(search_result.results.first).to be_a(Elasticsearch::Model::Response::Result) + it 'returns a OpenSearch::Model::Response::Result' do + expect(search_result.results.first).to be_a(OpenSearch::Model::Response::Result) end - it 'retrieves the document from Elasticsearch' do + it 'retrieves the document from OpenSearch' do expect(search_result.results.first.title).to eq('Test') end @@ -77,7 +77,7 @@ expect(search_result.records.first).to be_a(MongoidArticle) end - it 'retrieves the document from Elasticsearch' do + it 'retrieves the document from OpenSearch' do expect(search_result.records.first.title).to eq('Test') end @@ -133,7 +133,7 @@ article MongoidArticle.create!(title: 'Coding') article.destroy - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end it 'removes documents from the index' do @@ -151,7 +151,7 @@ before do article.title = 'Writing' article.save - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end it 'indexes updates' do @@ -166,7 +166,7 @@ MongoidArticle.create! title: 'Test' MongoidArticle.create! title: 'Testing Coding' MongoidArticle.create! title: 'Coding' - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end let(:search_result) do @@ -185,7 +185,7 @@ MongoidArticle.create! title: 'Test' MongoidArticle.create! title: 'Testing Coding' MongoidArticle.create! title: 'Coding' - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end let(:search_result) do @@ -206,8 +206,8 @@ before do 97.times { |i| MongoidArticle.create! title: "Test #{i}" } - MongoidArticle.__elasticsearch__.create_index! force: true - MongoidArticle.__elasticsearch__.client.cluster.health wait_for_status: 'yellow' + MongoidArticle.__opensearch__.create_index! force: true + MongoidArticle.__opensearch__.client.cluster.health wait_for_status: 'yellow' end context 'when there is no default scope' do @@ -217,7 +217,7 @@ errors = MongoidArticle.import(batch_size: 10) do |response| batches += 1 end - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! batches end @@ -240,8 +240,8 @@ end before do - MongoidArticle.__elasticsearch__.import - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.import + MongoidArticle.__opensearch__.refresh_index! end it 'uses the default scope' do @@ -260,7 +260,7 @@ before do MongoidArticle.import(query: -> { lte(views: 4) }) - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end it 'combines the query and the default scope' do @@ -273,7 +273,7 @@ before do MongoidArticle.delete_all MongoidArticle.import - MongoidArticle.__elasticsearch__.refresh_index! + MongoidArticle.__opensearch__.refresh_index! end it 'does not make any requests to create documents' do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/mongoid/multi_model_spec.rb b/opensearch-model/spec/opensearch/model/adapters/mongoid/multi_model_spec.rb similarity index 79% rename from elasticsearch-model/spec/elasticsearch/model/adapters/mongoid/multi_model_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/mongoid/multi_model_spec.rb index 5614522c9..317e8f443 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/mongoid/multi_model_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/mongoid/multi_model_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Adapter::ActiveRecord Multimodel', if: test_mongoid? do +describe 'OpenSearch::Model::Adapter::ActiveRecord Multimodel', if: test_mongoid? do before(:all) do connect_mongoid('mongoid_test') @@ -35,32 +35,32 @@ before do clear_tables(Episode, Image) - Episode.__elasticsearch__.create_index! force: true + Episode.__opensearch__.create_index! force: true Episode.create name: 'TheEpisode' Episode.create name: 'A great Episode' Episode.create name: 'The greatest Episode' - Episode.__elasticsearch__.refresh_index! + Episode.__opensearch__.refresh_index! - Image.__elasticsearch__.create_index! force: true + Image.__opensearch__.create_index! force: true Image.create! name: 'The Image' Image.create! name: 'A great Image' Image.create! name: 'The greatest Image' - Image.__elasticsearch__.refresh_index! - Image.__elasticsearch__.client.cluster.health wait_for_status: 'yellow' + Image.__opensearch__.refresh_index! + Image.__opensearch__.client.cluster.health wait_for_status: 'yellow' end after do [Episode, Image].each do |model| - model.__elasticsearch__.client.delete_by_query(index: model.index_name, q: '*', body: {}) + model.__opensearch__.client.delete_by_query(index: model.index_name, q: '*', body: {}) model.delete_all - model.__elasticsearch__.refresh_index! + model.__opensearch__.refresh_index! end end context 'when the search is across multimodels with different adapters' do let(:search_result) do - Elasticsearch::Model.search(%q<"greatest Episode" OR "greatest Image"^2>, [Episode, Image]) + OpenSearch::Model.search(%q<"greatest Episode" OR "greatest Image"^2>, [Episode, Image]) end it 'executes the search across models' do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/mongoid_spec.rb b/opensearch-model/spec/opensearch/model/adapters/mongoid_spec.rb similarity index 88% rename from elasticsearch-model/spec/elasticsearch/model/adapters/mongoid_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/mongoid_spec.rb index 81a286c0d..0078f9349 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/mongoid_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/mongoid_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter::Mongoid do +describe OpenSearch::Model::Adapter::Mongoid do before(:all) do class DummyClassForMongoid; end @@ -25,7 +25,7 @@ class DummyClassForMongoid; end end after(:all) do - Elasticsearch::Model::Adapter::Adapter.adapters.delete(DummyClassForMongoid) + OpenSearch::Model::Adapter::Adapter.adapters.delete(DummyClassForMongoid) remove_classes(DummyClassForMongoid) end @@ -64,19 +64,19 @@ class DummyClassForMongoid; end describe 'adapter registration' do it 'registers an adapater' do - expect(Elasticsearch::Model::Adapter.adapters[Elasticsearch::Model::Adapter::Mongoid]).not_to be_nil - expect(Elasticsearch::Model::Adapter.adapters[Elasticsearch::Model::Adapter::Mongoid].call(DummyClassForMongoid)).to be(false) + expect(OpenSearch::Model::Adapter.adapters[OpenSearch::Model::Adapter::Mongoid]).not_to be_nil + expect(OpenSearch::Model::Adapter.adapters[OpenSearch::Model::Adapter::Mongoid].call(DummyClassForMongoid)).to be(false) end it 'registers the records module' do - expect(Elasticsearch::Model::Adapter::Mongoid::Records).to be_a(Module) + expect(OpenSearch::Model::Adapter::Mongoid::Records).to be_a(Module) end end describe '#records' do before(:all) do - DummyClassForMongoid.__send__ :include, Elasticsearch::Model::Adapter::Mongoid::Records + DummyClassForMongoid.__send__ :include, OpenSearch::Model::Adapter::Mongoid::Records end let(:instance) do @@ -130,7 +130,7 @@ class DummyClassForMongoid; end end it 'should register the model class for callbacks' do - Elasticsearch::Model::Adapter::Mongoid::Callbacks.included(DummyClassForMongoid) + OpenSearch::Model::Adapter::Mongoid::Callbacks.included(DummyClassForMongoid) end end end @@ -138,7 +138,7 @@ class DummyClassForMongoid; end describe 'importing' do before(:all) do - DummyClassForMongoid.__send__ :extend, Elasticsearch::Model::Adapter::Mongoid::Importing + DummyClassForMongoid.__send__ :extend, OpenSearch::Model::Adapter::Mongoid::Importing end let(:relation) do @@ -174,7 +174,7 @@ class DummyClassForMongoid; end context 'query criteria specified as a hash' do before do - expect(relation).to receive(:where).with(color: 'red').and_return(relation) + expect(relation).to receive(:where).with({ color: 'red' }).and_return(relation) end let(:query) do diff --git a/elasticsearch-model/spec/elasticsearch/model/adapters/multiple_spec.rb b/opensearch-model/spec/opensearch/model/adapters/multiple_spec.rb similarity index 88% rename from elasticsearch-model/spec/elasticsearch/model/adapters/multiple_spec.rb rename to opensearch-model/spec/opensearch/model/adapters/multiple_spec.rb index eb5a983b0..9d6ed44b2 100644 --- a/elasticsearch-model/spec/elasticsearch/model/adapters/multiple_spec.rb +++ b/opensearch-model/spec/opensearch/model/adapters/multiple_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Model::Adapter::Multiple do +describe OpenSearch::Model::Adapter::Multiple do before(:all) do class DummyOne - include Elasticsearch::Model + include OpenSearch::Model index_name 'dummy' document_type 'dummy_one' @@ -39,7 +39,7 @@ def initialize(id) module Namespace class DummyTwo - include Elasticsearch::Model + include OpenSearch::Model index_name 'dummy' document_type 'dummy_two' @@ -57,7 +57,7 @@ def initialize(id) end class DummyTwo - include Elasticsearch::Model + include OpenSearch::Model index_name 'other_index' document_type 'dummy_two' @@ -76,7 +76,7 @@ def initialize(id) after(:all) do [DummyOne, Namespace::DummyTwo, DummyTwo].each do |adapter| - Elasticsearch::Model::Adapter::Adapter.adapters.delete(adapter) + OpenSearch::Model::Adapter::Adapter.adapters.delete(adapter) end Namespace.send(:remove_const, :DummyTwo) if defined?(Namespace::DummyTwo) remove_classes(DummyOne, DummyTwo, Namespace) @@ -117,13 +117,13 @@ def initialize(id) end let(:multimodel) do - Elasticsearch::Model::Multimodel.new(DummyOne, DummyTwo, Namespace::DummyTwo) + OpenSearch::Model::Multimodel.new(DummyOne, DummyTwo, Namespace::DummyTwo) end describe '#records' do before do - multimodel.class.send :include, Elasticsearch::Model::Adapter::Multiple::Records + multimodel.class.send :include, OpenSearch::Model::Adapter::Multiple::Records expect(multimodel).to receive(:response).at_least(:once).and_return(response) end diff --git a/elasticsearch-model/spec/elasticsearch/model/callbacks_spec.rb b/opensearch-model/spec/opensearch/model/callbacks_spec.rb similarity index 85% rename from elasticsearch-model/spec/elasticsearch/model/callbacks_spec.rb rename to opensearch-model/spec/opensearch/model/callbacks_spec.rb index f128d8732..97a87f070 100644 --- a/elasticsearch-model/spec/elasticsearch/model/callbacks_spec.rb +++ b/opensearch-model/spec/opensearch/model/callbacks_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Callbacks do +describe OpenSearch::Model::Callbacks do before(:all) do class ::DummyCallbacksModel @@ -40,11 +40,11 @@ def callbacks_mixin context 'when a model includes the Callbacks module' do before do - Elasticsearch::Model::Callbacks.included(DummyCallbacksModel) + OpenSearch::Model::Callbacks.included(DummyCallbacksModel) end it 'includes the callbacks mixin from the model adapter' do - expect(DummyCallbacksModel.ancestors).to include(Elasticsearch::Model::Adapter::Default::Callbacks) + expect(DummyCallbacksModel.ancestors).to include(OpenSearch::Model::Adapter::Default::Callbacks) end end end diff --git a/elasticsearch-model/spec/elasticsearch/model/client_spec.rb b/opensearch-model/spec/opensearch/model/client_spec.rb similarity index 84% rename from elasticsearch-model/spec/elasticsearch/model/client_spec.rb rename to opensearch-model/spec/opensearch/model/client_spec.rb index 12814d701..95f3dcc70 100644 --- a/elasticsearch-model/spec/elasticsearch/model/client_spec.rb +++ b/opensearch-model/spec/opensearch/model/client_spec.rb @@ -17,12 +17,12 @@ require 'spec_helper' -describe Elasticsearch::Model::Client do +describe OpenSearch::Model::Client do before(:all) do class ::DummyClientModel - extend Elasticsearch::Model::Client::ClassMethods - include Elasticsearch::Model::Client::InstanceMethods + extend OpenSearch::Model::Client::ClassMethods + include OpenSearch::Model::Client::InstanceMethods end end @@ -33,14 +33,14 @@ class ::DummyClientModel context 'when a class includes the client module class methods' do it 'defines the client module class methods on the model' do - expect(DummyClientModel.client).to be_a(Elasticsearch::Client) + expect(DummyClientModel.client).to be_a(OpenSearch::Client) end end context 'when a class includes the client module instance methods' do it 'defines the client module class methods on the model' do - expect(DummyClientModel.new.client).to be_a(Elasticsearch::Client) + expect(DummyClientModel.new.client).to be_a(OpenSearch::Client) end end @@ -77,7 +77,7 @@ class ::DummyClientModel end it 'does not set the client on the class' do - expect(DummyClientModel.client).to be_a(Elasticsearch::Client) + expect(DummyClientModel.client).to be_a(OpenSearch::Client) end end end diff --git a/elasticsearch-model/spec/elasticsearch/model/hash_wrapper_spec.rb b/opensearch-model/spec/opensearch/model/hash_wrapper_spec.rb similarity index 86% rename from elasticsearch-model/spec/elasticsearch/model/hash_wrapper_spec.rb rename to opensearch-model/spec/opensearch/model/hash_wrapper_spec.rb index ae4c857ac..9d35701a0 100644 --- a/elasticsearch-model/spec/elasticsearch/model/hash_wrapper_spec.rb +++ b/opensearch-model/spec/opensearch/model/hash_wrapper_spec.rb @@ -17,13 +17,13 @@ require 'spec_helper' -describe Elasticsearch::Model::HashWrapper, if: Hashie::VERSION >= '3.5.3' do +describe OpenSearch::Model::HashWrapper, if: Hashie::VERSION >= '3.5.3' do before do expect(Hashie.logger).to receive(:warn).never end it 'does not print a warning for re-defined methods' do - Elasticsearch::Model::HashWrapper.new(:foo => 'bar', :sort => true) + OpenSearch::Model::HashWrapper.new(:foo => 'bar', :sort => true) end end diff --git a/elasticsearch-model/spec/elasticsearch/model/importing_spec.rb b/opensearch-model/spec/opensearch/model/importing_spec.rb similarity index 84% rename from elasticsearch-model/spec/elasticsearch/model/importing_spec.rb rename to opensearch-model/spec/opensearch/model/importing_spec.rb index 02cde6d6c..dc45dca20 100644 --- a/elasticsearch-model/spec/elasticsearch/model/importing_spec.rb +++ b/opensearch-model/spec/opensearch/model/importing_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Importing do +describe OpenSearch::Model::Importing do before(:all) do class DummyImportingModel @@ -44,8 +44,8 @@ def importing_mixin end before do - allow(Elasticsearch::Model::Adapter).to receive(:from_class).with(DummyImportingModel).and_return(DummyImportingAdapter) - DummyImportingModel.__send__ :include, Elasticsearch::Model::Importing + allow(OpenSearch::Model::Adapter).to receive(:from_class).with(DummyImportingModel).and_return(DummyImportingAdapter) + DummyImportingModel.__send__ :include, OpenSearch::Model::Importing end context 'when a model includes the Importing module' do @@ -60,7 +60,6 @@ def importing_mixin before do allow(DummyImportingModel).to receive(:index_name).and_return('foo') - allow(DummyImportingModel).to receive(:document_type).and_return('foo') allow(DummyImportingModel).to receive(:index_exists?).and_return(true) allow(DummyImportingModel).to receive(:__batch_to_bulk) allow(client).to receive(:bulk).and_return(response) @@ -134,8 +133,8 @@ def importing_mixin context 'when the method is called with the force option' do before do - expect(DummyImportingModel).to receive(:create_index!).with(force: true, index: 'foo').and_return(true) - expect(DummyImportingModel).to receive(:__find_in_batches).with(foo: 'bar').and_return(true) + expect(DummyImportingModel).to receive(:create_index!).with({ force: true, index: 'foo' }).and_return(true) + expect(DummyImportingModel).to receive(:__find_in_batches).with({ foo: 'bar' }).and_return(true) end it 'deletes and creates the index' do @@ -146,8 +145,8 @@ def importing_mixin context 'when the method is called with the refresh option' do before do - expect(DummyImportingModel).to receive(:refresh_index!).with(index: 'foo').and_return(true) - expect(DummyImportingModel).to receive(:__find_in_batches).with(foo: 'bar').and_return(true) + expect(DummyImportingModel).to receive(:refresh_index!).with({ index: 'foo' }).and_return(true) + expect(DummyImportingModel).to receive(:__find_in_batches).with({ foo: 'bar' }).and_return(true) end it 'refreshes the index' do @@ -159,7 +158,7 @@ def importing_mixin before do expect(DummyImportingModel).to receive(:client).and_return(client) - expect(client).to receive(:bulk).with(body: nil, index: 'my-new-index', type: 'foo').and_return(response) + expect(client).to receive(:bulk).with({ body: nil, index: 'my-new-index' }).and_return(response) end it 'uses the alternate index name' do @@ -167,18 +166,6 @@ def importing_mixin end end - context 'when a different document type is provided' do - - before do - expect(DummyImportingModel).to receive(:client).and_return(client) - expect(client).to receive(:bulk).with(body: nil, index: 'foo', type: 'my-new-type').and_return(response) - end - - it 'uses the alternate index name' do - expect(DummyImportingModel.import(type: 'my-new-type')).to eq(0) - end - end - context 'the transform method' do before do @@ -232,7 +219,7 @@ def importing_mixin before do expect(DummyImportingModel).to receive(:client).and_return(client) - expect(client).to receive(:bulk).with(body: nil, index: 'foo', type: 'foo', pipeline: 'my-pipeline').and_return(response) + expect(client).to receive(:bulk).with({ body: nil, index: 'foo', pipeline: 'my-pipeline' }).and_return(response) end it 'uses the pipeline option' do diff --git a/elasticsearch-model/spec/elasticsearch/model/indexing_spec.rb b/opensearch-model/spec/opensearch/model/indexing_spec.rb similarity index 76% rename from elasticsearch-model/spec/elasticsearch/model/indexing_spec.rb rename to opensearch-model/spec/opensearch/model/indexing_spec.rb index eb9651a73..60b57e43f 100644 --- a/elasticsearch-model/spec/elasticsearch/model/indexing_spec.rb +++ b/opensearch-model/spec/opensearch/model/indexing_spec.rb @@ -17,13 +17,13 @@ require 'spec_helper' -describe Elasticsearch::Model::Indexing do +describe OpenSearch::Model::Indexing do before(:all) do class ::DummyIndexingModel extend ActiveModel::Naming - extend Elasticsearch::Model::Naming::ClassMethods - extend Elasticsearch::Model::Indexing::ClassMethods + extend OpenSearch::Model::Naming::ClassMethods + extend OpenSearch::Model::Indexing::ClassMethods def self.foo 'bar' @@ -40,18 +40,18 @@ class NotFound < Exception; end describe 'the Settings class' do it 'should be convertible to a hash' do - expect(Elasticsearch::Model::Indexing::Settings.new(foo: 'bar').to_hash).to eq(foo: 'bar') + expect(OpenSearch::Model::Indexing::Settings.new(foo: 'bar').to_hash).to eq(foo: 'bar') end it 'should be convertible to json' do - expect(Elasticsearch::Model::Indexing::Settings.new(foo: 'bar').as_json).to eq(foo: 'bar') + expect(OpenSearch::Model::Indexing::Settings.new(foo: 'bar').as_json).to eq(foo: 'bar') end end describe '#settings' do it 'returns an instance of the Settings class' do - expect(DummyIndexingModel.settings).to be_a(Elasticsearch::Model::Indexing::Settings) + expect(DummyIndexingModel.settings).to be_a(OpenSearch::Model::Indexing::Settings) end context 'when the settings are updated' do @@ -94,68 +94,29 @@ class NotFound < Exception; end describe '#mappings' do let(:expected_mapping_hash) do - { :mytype => { foo: 'bar', :properties => {} } } + { foo: 'bar', :properties => {} } end it 'returns an instance of the Mappings class' do - expect(DummyIndexingModel.mappings).to be_a(Elasticsearch::Model::Indexing::Mappings) + expect(DummyIndexingModel.mappings).to be_a(OpenSearch::Model::Indexing::Mappings) end it 'does not raise an exception when there is no type passed to the #initialize method' do - expect(Elasticsearch::Model::Indexing::Mappings.new) + expect(OpenSearch::Model::Indexing::Mappings.new) end it 'should be convertible to a hash' do - expect(Elasticsearch::Model::Indexing::Mappings.new(:mytype, { foo: 'bar' }).to_hash).to eq(expected_mapping_hash) + expect(OpenSearch::Model::Indexing::Mappings.new({ foo: 'bar' }).to_hash).to eq(expected_mapping_hash) end it 'should be convertible to json' do - expect(Elasticsearch::Model::Indexing::Mappings.new(:mytype, { foo: 'bar' }).as_json).to eq(expected_mapping_hash) - end - - context 'when a type is specified' do - - let(:mappings) do - Elasticsearch::Model::Indexing::Mappings.new(:mytype) - end - - before do - mappings.indexes :foo, { type: 'boolean', include_in_all: false } - mappings.indexes :bar - end - - it 'creates the correct mapping definition' do - expect(mappings.to_hash[:mytype][:properties][:foo][:type]).to eq('boolean') - end - - it 'uses text as the default field type' do - expect(mappings.to_hash[:mytype][:properties][:bar][:type]).to eq('text') - end - - context 'when the \'include_type_name\' option is specified' do - - let(:mappings) do - Elasticsearch::Model::Indexing::Mappings.new(:mytype, include_type_name: true) - end - - before do - mappings.indexes :foo, { type: 'boolean', include_in_all: false } - end - - it 'creates the correct mapping definition' do - expect(mappings.to_hash[:mytype][:properties][:foo][:type]).to eq('boolean') - end - - it 'sets the \'include_type_name\' option' do - expect(mappings.to_hash[:mytype][:include_type_name]).to eq(true) - end - end + expect(OpenSearch::Model::Indexing::Mappings.new({ foo: 'bar' }).as_json).to eq(expected_mapping_hash) end context 'when a type is not specified' do let(:mappings) do - Elasticsearch::Model::Indexing::Mappings.new + OpenSearch::Model::Indexing::Mappings.new end before do @@ -173,9 +134,8 @@ class NotFound < Exception; end end context 'when specific mappings are defined' do - let(:mappings) do - Elasticsearch::Model::Indexing::Mappings.new(:mytype, include_type_name: true) + OpenSearch::Model::Indexing::Mappings.new end before do @@ -184,11 +144,11 @@ class NotFound < Exception; end end it 'creates the correct mapping definition' do - expect(mappings.to_hash[:mytype][:properties][:foo][:type]).to eq('boolean') + expect(mappings.to_hash[:properties][:foo][:type]).to eq('boolean') end it 'uses text as the default type' do - expect(mappings.to_hash[:mytype][:properties][:bar][:type]).to eq('text') + expect(mappings.to_hash[:properties][:bar][:type]).to eq('text') end context 'when mappings are defined for multiple fields' do @@ -200,9 +160,9 @@ class NotFound < Exception; end end it 'defines the mapping for all the fields' do - expect(mappings.to_hash[:mytype][:properties][:my_field][:type]).to eq('text') - expect(mappings.to_hash[:mytype][:properties][:my_field][:fields][:raw][:type]).to eq('keyword') - expect(mappings.to_hash[:mytype][:properties][:my_field][:fields][:raw][:properties]).to be_nil + expect(mappings.to_hash[:properties][:my_field][:type]).to eq('text') + expect(mappings.to_hash[:properties][:my_field][:fields][:raw][:type]).to eq('keyword') + expect(mappings.to_hash[:properties][:my_field][:fields][:raw][:properties]).to be_nil end end @@ -227,25 +187,21 @@ class NotFound < Exception; end end it 'defines mappings for the embedded properties' do - expect(mappings.to_hash[:mytype][:properties][:foo][:type]).to eq('object') - expect(mappings.to_hash[:mytype][:properties][:foo][:properties][:bar][:type]).to eq('text') - expect(mappings.to_hash[:mytype][:properties][:foo][:fields]).to be_nil - - expect(mappings.to_hash[:mytype][:properties][:foo_object][:type]).to eq('object') - expect(mappings.to_hash[:mytype][:properties][:foo_object][:properties][:bar][:type]).to eq('text') - expect(mappings.to_hash[:mytype][:properties][:foo_object][:fields]).to be_nil + expect(mappings.to_hash[:properties][:foo][:type]).to eq('object') + expect(mappings.to_hash[:properties][:foo][:properties][:bar][:type]).to eq('text') + expect(mappings.to_hash[:properties][:foo][:fields]).to be_nil - expect(mappings.to_hash[:mytype][:properties][:foo_nested][:type]).to eq('nested') - expect(mappings.to_hash[:mytype][:properties][:foo_nested][:properties][:bar][:type]).to eq('text') - expect(mappings.to_hash[:mytype][:properties][:foo_nested][:fields]).to be_nil + expect(mappings.to_hash[:properties][:foo_object][:type]).to eq('object') + expect(mappings.to_hash[:properties][:foo_object][:properties][:bar][:type]).to eq('text') + expect(mappings.to_hash[:properties][:foo_object][:fields]).to be_nil - expect(mappings.to_hash[:mytype][:properties][:foo_nested_as_symbol][:type]).to eq(:nested) - expect(mappings.to_hash[:mytype][:properties][:foo_nested_as_symbol][:properties]).not_to be_nil - expect(mappings.to_hash[:mytype][:properties][:foo_nested_as_symbol][:fields]).to be_nil - end + expect(mappings.to_hash[:properties][:foo_nested][:type]).to eq('nested') + expect(mappings.to_hash[:properties][:foo_nested][:properties][:bar][:type]).to eq('text') + expect(mappings.to_hash[:properties][:foo_nested][:fields]).to be_nil - it 'defines the settings' do - expect(mappings.to_hash[:mytype][:include_type_name]).to be(true) + expect(mappings.to_hash[:properties][:foo_nested_as_symbol][:type]).to eq(:nested) + expect(mappings.to_hash[:properties][:foo_nested_as_symbol][:properties]).not_to be_nil + expect(mappings.to_hash[:properties][:foo_nested_as_symbol][:fields]).to be_nil end end end @@ -282,13 +238,12 @@ class NotFound < Exception; end before do DummyIndexingModel.instance_variable_set(:@mapping, nil) - DummyIndexingModel.document_type(:mytype) DummyIndexingModel.mappings(foo: 'boo') DummyIndexingModel.mappings(bar: 'bam') end let(:expected_mappings_hash) do - { mytype: { foo: "boo", bar: "bam", properties: {} } } + { foo: "boo", bar: "bam", properties: {} } end it 'sets the mappings' do @@ -302,8 +257,8 @@ class NotFound < Exception; end before(:all) do class ::DummyIndexingModelWithCallbacks - extend Elasticsearch::Model::Indexing::ClassMethods - include Elasticsearch::Model::Indexing::InstanceMethods + extend OpenSearch::Model::Indexing::ClassMethods + include OpenSearch::Model::Indexing::InstanceMethods def self.before_save(&block) (@callbacks ||= {})[block.hash] = block @@ -315,8 +270,8 @@ def changes_to_save end class ::DummyIndexingModelWithNoChanges - extend Elasticsearch::Model::Indexing::ClassMethods - include Elasticsearch::Model::Indexing::InstanceMethods + extend OpenSearch::Model::Indexing::ClassMethods + include OpenSearch::Model::Indexing::InstanceMethods def self.before_save(&block) (@callbacks ||= {})[block.hash] = block @@ -328,8 +283,8 @@ def changes_to_save end class ::DummyIndexingModelWithCallbacksAndCustomAsIndexedJson - extend Elasticsearch::Model::Indexing::ClassMethods - include Elasticsearch::Model::Indexing::InstanceMethods + extend OpenSearch::Model::Indexing::ClassMethods + include OpenSearch::Model::Indexing::InstanceMethods def self.before_save(&block) (@callbacks ||= {})[block.hash] = block @@ -345,8 +300,8 @@ def as_indexed_json(options={}) end class ::DummyIndexingModelWithOldDirty - extend Elasticsearch::Model::Indexing::ClassMethods - include Elasticsearch::Model::Indexing::InstanceMethods + extend OpenSearch::Model::Indexing::ClassMethods + include OpenSearch::Model::Indexing::InstanceMethods def self.before_save(&block) (@callbacks ||= {})[block.hash] = block @@ -370,7 +325,7 @@ def changes context 'when the model uses the old ActiveModel::Dirty' do before do - DummyIndexingModelWithOldDirty.__send__ :include, Elasticsearch::Model::Indexing::InstanceMethods + DummyIndexingModelWithOldDirty.__send__ :include, OpenSearch::Model::Indexing::InstanceMethods end it 'registers callbacks' do @@ -392,7 +347,7 @@ def changes context 'when the model users the current ActiveModel::Dirty' do before do - DummyIndexingModelWithCallbacks.__send__ :include, Elasticsearch::Model::Indexing::InstanceMethods + DummyIndexingModelWithCallbacks.__send__ :include, OpenSearch::Model::Indexing::InstanceMethods end it 'registers callbacks' do @@ -418,7 +373,6 @@ def changes expect(instance).to receive(:client).and_return(client) expect(instance).to receive(:as_indexed_json).and_return('JSON') expect(instance).to receive(:index_name).and_return('foo') - expect(instance).to receive(:document_type).twice.and_return('bar') expect(instance).to receive(:id).and_return('1') end @@ -433,7 +387,7 @@ def changes context 'when no options are passed to the method' do before do - expect(client).to receive(:index).with(index: 'foo', type: 'bar', id: '1', body: 'JSON').and_return(true) + expect(client).to receive(:index).with({ index: 'foo', id: '1', body: 'JSON' }).and_return(true) end it 'provides the method on an instance' do @@ -444,7 +398,7 @@ def changes context 'when extra options are passed to the method' do before do - expect(client).to receive(:index).with(index: 'foo', type: 'bar', id: '1', body: 'JSON', parent: 'A').and_return(true) + expect(client).to receive(:index).with({ index: 'foo', id: '1', body: 'JSON', parent: 'A' }).and_return(true) end it 'passes the extra options to the method call on the client' do @@ -458,7 +412,6 @@ def changes before do expect(instance).to receive(:client).and_return(client) expect(instance).to receive(:index_name).and_return('foo') - expect(instance).to receive(:document_type).twice.and_return('bar') expect(instance).to receive(:id).and_return('1') end @@ -473,7 +426,7 @@ def changes context 'when no options are passed to the method' do before do - expect(client).to receive(:delete).with(index: 'foo', type: 'bar', id: '1').and_return(true) + expect(client).to receive(:delete).with({ index: 'foo', id: '1' }).and_return(true) end it 'provides the method on an instance' do @@ -484,7 +437,7 @@ def changes context 'when extra options are passed to the method' do before do - expect(client).to receive(:delete).with(index: 'foo', type: 'bar', id: '1', parent: 'A').and_return(true) + expect(client).to receive(:delete).with({ index: 'foo', id: '1', parent: 'A' }).and_return(true) end it 'passes the extra options to the method call on the client' do @@ -529,7 +482,7 @@ def changes before do instance.instance_variable_set(:@__changed_model_attributes, { foo: 'bar' }) - expect(client).to receive(:update).with(index: 'foo', type: 'bar', id: '1', body: { doc: { foo: 'bar' } }).and_return(true) + expect(client).to receive(:update).with({ index: 'foo', id: '1', body: { doc: { foo: 'bar' } } }).and_return(true) end it 'updates the document' do @@ -545,7 +498,7 @@ def changes before do instance.instance_variable_set(:@__changed_model_attributes, {'foo' => 'B', 'bar' => 'D' }) - expect(client).to receive(:update).with(index: 'foo', type: 'bar', id: '1', body: { doc: { foo: 'B' } }).and_return(true) + expect(client).to receive(:update).with({ index: 'foo', id: '1', body: { doc: { foo: 'B' } } }).and_return(true) end it 'updates the document' do @@ -575,9 +528,9 @@ def changes end before do - instance.instance_variable_set(:@__changed_model_attributes, { 'foo' => { 'bar' => 'BAR'} }) + instance.instance_variable_set(:@__changed_model_attributes, { 'foo' => { 'bar' => 'BAR' } }) expect(instance).to receive(:as_indexed_json).and_return('foo' => 'BAR') - expect(client).to receive(:update).with(index: 'foo', type: 'bar', id: '1', body: { doc: { 'foo' => 'BAR' } }).and_return(true) + expect(client).to receive(:update).with({ index: 'foo', id: '1', body: { doc: { 'foo' => 'BAR' } } }).and_return(true) end it 'updates the document' do @@ -602,7 +555,6 @@ def changes before do expect(instance).to receive(:client).and_return(client) expect(instance).to receive(:index_name).and_return('foo') - expect(instance).to receive(:document_type).twice.and_return('bar') expect(instance).to receive(:id).and_return('1') instance.instance_variable_set(:@__changed_model_attributes, { author: 'john' }) end @@ -610,7 +562,7 @@ def changes context 'when no options are specified' do before do - expect(client).to receive(:update).with(index: 'foo', type: 'bar', id: '1', body: { doc: { title: 'green' } }).and_return(true) + expect(client).to receive(:update).with({ index: 'foo', id: '1', body: { doc: { title: 'green' } } }).and_return(true) end it 'updates the document' do @@ -621,7 +573,7 @@ def changes context 'when extra options are provided' do before do - expect(client).to receive(:update).with(index: 'foo', type: 'bar', id: '1', body: { doc: { title: 'green' } }, refresh: true).and_return(true) + expect(client).to receive(:update).with({ index: 'foo', id: '1', body: { doc: { title: 'green' } }, refresh: true }).and_return(true) end it 'updates the document' do @@ -666,8 +618,8 @@ def changes before(:all) do class ::DummyIndexingModelForRecreate extend ActiveModel::Naming - extend Elasticsearch::Model::Naming::ClassMethods - extend Elasticsearch::Model::Indexing::ClassMethods + extend OpenSearch::Model::Naming::ClassMethods + extend OpenSearch::Model::Indexing::ClassMethods end end @@ -678,7 +630,7 @@ class ::DummyIndexingModelForRecreate context 'when the index is not found' do let(:logger) { nil } let(:transport) do - Elasticsearch::Transport::Client.new(logger: logger) + OpenSearch::Transport::Client.new(logger: logger) end let(:client) do @@ -749,7 +701,7 @@ class ::DummyIndexingModelForRecreate before do expect(DummyIndexingModelForRecreate).to receive(:client).and_return(client) - expect(indices).to receive(:delete).with(index: 'custom-foo') + expect(indices).to receive(:delete).with({ index: 'custom-foo' }) end let(:client) do @@ -771,8 +723,8 @@ class ::DummyIndexingModelForRecreate before(:all) do class ::DummyIndexingModelForCreate extend ActiveModel::Naming - extend Elasticsearch::Model::Naming::ClassMethods - extend Elasticsearch::Model::Indexing::ClassMethods + extend OpenSearch::Model::Naming::ClassMethods + extend OpenSearch::Model::Indexing::ClassMethods index_name 'foo' @@ -812,7 +764,7 @@ class ::DummyIndexingModelForCreate end before do - expect(indices).to receive(:create).with(index: 'foo', body: expected_body).and_return(true) + expect(indices).to receive(:create).with({ index: 'foo', body: expected_body }).and_return(true) end it 'creates the index' do @@ -828,7 +780,7 @@ class ::DummyIndexingModelForCreate end before do - expect(indices).to receive(:create).with(index: 'foobar', body: expected_body).and_return(true) + expect(indices).to receive(:create).with({ index: 'foobar', body: expected_body }).and_return(true) end it 'creates the index' do @@ -874,7 +826,7 @@ class ::DummyIndexingModelForCreate before do expect(DummyIndexingModelForCreate).to receive(:client).and_return(client).twice expect(indices).to receive(:exists).and_return(false) - expect(indices).to receive(:create).with(index: 'custom-foo', body: expected_body) + expect(indices).to receive(:create).with({ index: 'custom-foo', body: expected_body }) end let(:expected_body) do @@ -896,8 +848,8 @@ class ::DummyIndexingModelForCreate before(:all) do class ::DummyIndexingModelForRefresh extend ActiveModel::Naming - extend Elasticsearch::Model::Naming::ClassMethods - extend Elasticsearch::Model::Indexing::ClassMethods + extend OpenSearch::Model::Naming::ClassMethods + extend OpenSearch::Model::Indexing::ClassMethods index_name 'foo' @@ -918,7 +870,7 @@ class ::DummyIndexingModelForRefresh end let(:transport) do - Elasticsearch::Transport::Client.new(logger: nil) + OpenSearch::Transport::Client.new(logger: nil) end let(:indices) do @@ -949,7 +901,7 @@ class ::DummyIndexingModelForRefresh end let(:transport) do - Elasticsearch::Transport::Client.new(logger: logger) + OpenSearch::Transport::Client.new(logger: logger) end it 'does not raise an exception' do @@ -978,7 +930,7 @@ class ::DummyIndexingModelForRefresh context 'when an index name is provided in the options' do before do - expect(indices).to receive(:refresh).with(index: 'custom-foo') + expect(indices).to receive(:refresh).with({ index: 'custom-foo' }) end it 'uses the index name' do diff --git a/elasticsearch-model/spec/elasticsearch/model/module_spec.rb b/opensearch-model/spec/opensearch/model/module_spec.rb similarity index 78% rename from elasticsearch-model/spec/elasticsearch/model/module_spec.rb rename to opensearch-model/spec/opensearch/model/module_spec.rb index ed7a58297..932ca506d 100644 --- a/elasticsearch-model/spec/elasticsearch/model/module_spec.rb +++ b/opensearch-model/spec/opensearch/model/module_spec.rb @@ -17,23 +17,23 @@ require 'spec_helper' -describe Elasticsearch::Model do +describe OpenSearch::Model do describe '#client' do it 'should have a default' do - expect(Elasticsearch::Model.client).to be_a(Elasticsearch::Client) + expect(OpenSearch::Model.client).to be_a(OpenSearch::Client) end end describe '#client=' do before do - Elasticsearch::Model.client = 'Foobar' + OpenSearch::Model.client = 'Foobar' end it 'should allow the client to be set' do - expect(Elasticsearch::Model.client).to eq('Foobar') + expect(OpenSearch::Model.client).to eq('Foobar') end end @@ -47,8 +47,8 @@ def self.search(query, options={}) end end - DummyIncludingModel.__send__ :include, Elasticsearch::Model - DummyIncludingModelWithSearchMethodDefined.__send__ :include, Elasticsearch::Model + DummyIncludingModel.__send__ :include, OpenSearch::Model + DummyIncludingModelWithSearchMethodDefined.__send__ :include, OpenSearch::Model end after(:all) do @@ -56,8 +56,8 @@ def self.search(query, options={}) end it 'should include and set up the proxy' do - expect(DummyIncludingModel).to respond_to(:__elasticsearch__) - expect(DummyIncludingModel.new).to respond_to(:__elasticsearch__) + expect(DummyIncludingModel).to respond_to(:__opensearch__) + expect(DummyIncludingModel.new).to respond_to(:__opensearch__) end it 'should delegate methods to the proxy' do @@ -77,17 +77,17 @@ def self.search(query, options={}) describe '#settings' do it 'allows access to the settings' do - expect(Elasticsearch::Model.settings).to eq({}) + expect(OpenSearch::Model.settings).to eq({}) end context 'when settings are changed' do before do - Elasticsearch::Model.settings[:foo] = 'bar' + OpenSearch::Model.settings[:foo] = 'bar' end it 'persists the changes' do - expect(Elasticsearch::Model.settings[:foo]).to eq('bar') + expect(OpenSearch::Model.settings[:foo]).to eq('bar') end end end diff --git a/elasticsearch-model/spec/elasticsearch/model/multimodel_spec.rb b/opensearch-model/spec/opensearch/model/multimodel_spec.rb similarity index 85% rename from elasticsearch-model/spec/elasticsearch/model/multimodel_spec.rb rename to opensearch-model/spec/opensearch/model/multimodel_spec.rb index 3652dac1e..2e7261107 100644 --- a/elasticsearch-model/spec/elasticsearch/model/multimodel_spec.rb +++ b/opensearch-model/spec/opensearch/model/multimodel_spec.rb @@ -17,10 +17,10 @@ require 'spec_helper' -describe Elasticsearch::Model::Multimodel do +describe OpenSearch::Model::Multimodel do let(:multimodel) do - Elasticsearch::Model::Multimodel.new(model_1, model_2) + OpenSearch::Model::Multimodel.new(model_1, model_2) end let(:model_1) do @@ -40,7 +40,7 @@ end it 'has a client' do - expect(multimodel.client).to eq(Elasticsearch::Model.client) + expect(multimodel.client).to eq(OpenSearch::Model.client) end describe 'the model registry' do @@ -48,11 +48,11 @@ before(:all) do class JustAModel - include Elasticsearch::Model + include OpenSearch::Model end class JustAnotherModel - include Elasticsearch::Model + include OpenSearch::Model end end @@ -61,7 +61,7 @@ class JustAnotherModel end let(:multimodel) do - Elasticsearch::Model::Multimodel.new + OpenSearch::Model::Multimodel.new end it 'includes model in the registry' do diff --git a/elasticsearch-model/spec/elasticsearch/model/naming_spec.rb b/opensearch-model/spec/opensearch/model/naming_spec.rb similarity index 95% rename from elasticsearch-model/spec/elasticsearch/model/naming_spec.rb rename to opensearch-model/spec/opensearch/model/naming_spec.rb index 57a53b8d7..31189ac3f 100644 --- a/elasticsearch-model/spec/elasticsearch/model/naming_spec.rb +++ b/opensearch-model/spec/opensearch/model/naming_spec.rb @@ -23,16 +23,16 @@ class ::DummyNamingModel extend ActiveModel::Naming - extend Elasticsearch::Model::Naming::ClassMethods - include Elasticsearch::Model::Naming::InstanceMethods + extend OpenSearch::Model::Naming::ClassMethods + include OpenSearch::Model::Naming::InstanceMethods end module ::MyNamespace class DummyNamingModelInNamespace extend ActiveModel::Naming - extend Elasticsearch::Model::Naming::ClassMethods - include Elasticsearch::Model::Naming::InstanceMethods + extend OpenSearch::Model::Naming::ClassMethods + include OpenSearch::Model::Naming::InstanceMethods end end end diff --git a/elasticsearch-model/spec/elasticsearch/model/proxy_spec.rb b/opensearch-model/spec/opensearch/model/proxy_spec.rb similarity index 66% rename from elasticsearch-model/spec/elasticsearch/model/proxy_spec.rb rename to opensearch-model/spec/opensearch/model/proxy_spec.rb index f21baad3d..d14106436 100644 --- a/elasticsearch-model/spec/elasticsearch/model/proxy_spec.rb +++ b/opensearch-model/spec/opensearch/model/proxy_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Model::Proxy do +describe OpenSearch::Model::Proxy do before(:all) do class ::DummyProxyModel - include Elasticsearch::Model::Proxy + include OpenSearch::Model::Proxy def self.foo 'classy foo' @@ -50,7 +50,7 @@ def changes_to_save end end - DummyProxyModelWithCallbacks.__send__ :include, Elasticsearch::Model::Proxy + DummyProxyModelWithCallbacks.__send__ :include, OpenSearch::Model::Proxy end after(:all) do @@ -58,11 +58,11 @@ def changes_to_save end it 'sets up a proxy method on the class' do - expect(DummyProxyModel).to respond_to(:__elasticsearch__) + expect(DummyProxyModel).to respond_to(:__opensearch__) end it 'sets up a proxy method on instances' do - expect(DummyProxyModel.new).to respond_to(:__elasticsearch__) + expect(DummyProxyModel.new).to respond_to(:__opensearch__) end it 'sets up hooks for before_save callbacks' do @@ -70,35 +70,35 @@ def changes_to_save end it 'delegates methods to the target' do - expect(DummyProxyModel.__elasticsearch__).to respond_to(:foo) - expect(DummyProxyModel.__elasticsearch__.foo).to eq('classy foo') - expect(DummyProxyModel.new.__elasticsearch__).to respond_to(:bar) - expect(DummyProxyModel.new.__elasticsearch__.bar).to eq('insta barr') + expect(DummyProxyModel.__opensearch__).to respond_to(:foo) + expect(DummyProxyModel.__opensearch__.foo).to eq('classy foo') + expect(DummyProxyModel.new.__opensearch__).to respond_to(:bar) + expect(DummyProxyModel.new.__opensearch__.bar).to eq('insta barr') expect { - DummyProxyModel.__elasticsearch__.xoxo + DummyProxyModel.__opensearch__.xoxo }.to raise_exception(NoMethodError) expect { - DummyProxyModel.new.__elasticsearch__.xoxo + DummyProxyModel.new.__opensearch__.xoxo }.to raise_exception(NoMethodError) end it 'returns the proxy class from an instance proxy' do - expect(DummyProxyModel.new.__elasticsearch__.class.class).to eq(Elasticsearch::Model::Proxy::ClassMethodsProxy) + expect(DummyProxyModel.new.__opensearch__.class.class).to eq(OpenSearch::Model::Proxy::ClassMethodsProxy) end it 'returns the origin class from an instance proxy' do - expect(DummyProxyModel.new.__elasticsearch__.klass).to eq(DummyProxyModel) + expect(DummyProxyModel.new.__opensearch__.klass).to eq(DummyProxyModel) end it 'delegates #as_json from the proxy to the target' do - expect(DummyProxyModel.new.__elasticsearch__.as_json).to eq(foo: 'bar') + expect(DummyProxyModel.new.__opensearch__.as_json).to eq(foo: 'bar') end it 'includes the proxy in the inspect string' do - expect(DummyProxyModel.__elasticsearch__.inspect).to match(/PROXY/) - expect(DummyProxyModel.new.__elasticsearch__.inspect).to match(/PROXY/) + expect(DummyProxyModel.__opensearch__.inspect).to match(/PROXY/) + expect(DummyProxyModel.new.__opensearch__.inspect).to match(/PROXY/) end context 'when instances are cloned' do @@ -107,7 +107,7 @@ def changes_to_save end let!(:model_target) do - model.__elasticsearch__.target + model.__opensearch__.target end let!(:duplicate) do @@ -115,7 +115,7 @@ def changes_to_save end let!(:duplicate_target) do - duplicate.__elasticsearch__.target + duplicate.__opensearch__.target end it 'resets the proxy target' do @@ -126,7 +126,7 @@ def changes_to_save end it 'forwards keyword arguments to target methods' do - expect(DummyProxyModel.new.__elasticsearch__.keyword_method(foo: 'bar')).to eq('bar') + expect(DummyProxyModel.new.__opensearch__.keyword_method(foo: 'bar')).to eq('bar') end end diff --git a/elasticsearch-model/spec/elasticsearch/model/response/aggregations_spec.rb b/opensearch-model/spec/opensearch/model/response/aggregations_spec.rb similarity index 90% rename from elasticsearch-model/spec/elasticsearch/model/response/aggregations_spec.rb rename to opensearch-model/spec/opensearch/model/response/aggregations_spec.rb index a455140ea..7f7a7319f 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/aggregations_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/aggregations_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Response::Aggregations do +describe OpenSearch::Model::Response::Aggregations do before(:all) do class OriginClass @@ -43,13 +43,13 @@ def self.document_type; 'bar'; end end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| + OpenSearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| allow(request).to receive(:execute!).and_return(response_document) end end let(:aggregations) do - Elasticsearch::Model::Response::Response.new(OriginClass, search).aggregations + OpenSearch::Model::Response::Response.new(OriginClass, search).aggregations end describe 'method delegation' do diff --git a/elasticsearch-model/spec/elasticsearch/model/response/base_spec.rb b/opensearch-model/spec/opensearch/model/response/base_spec.rb similarity index 85% rename from elasticsearch-model/spec/elasticsearch/model/response/base_spec.rb rename to opensearch-model/spec/opensearch/model/response/base_spec.rb index d3459b93b..6788cb2dc 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/base_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/base_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Model::Response::Base do +describe OpenSearch::Model::Response::Base do before(:all) do class DummyBaseClass - include Elasticsearch::Model::Response::Base + include OpenSearch::Model::Response::Base end class OriginClass @@ -39,13 +39,13 @@ def self.document_type; 'bar'; end end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| + OpenSearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| allow(request).to receive(:execute!).and_return(response_document) end end let(:response) do - Elasticsearch::Model::Response::Response.new(OriginClass, search) + OpenSearch::Model::Response::Response.new(OriginClass, search) end let(:response_base) do @@ -92,7 +92,7 @@ def self.document_type; 'bar'; end it 'raises a NotImplemented error' do expect { response_base.results - }.to raise_exception(Elasticsearch::Model::NotImplemented) + }.to raise_exception(OpenSearch::Model::NotImplemented) end end @@ -101,7 +101,7 @@ def self.document_type; 'bar'; end it 'raises a NotImplemented error' do expect { response_base.records - }.to raise_exception(Elasticsearch::Model::NotImplemented) + }.to raise_exception(OpenSearch::Model::NotImplemented) end end end diff --git a/elasticsearch-model/spec/elasticsearch/model/response/pagination/kaminari_spec.rb b/opensearch-model/spec/opensearch/model/response/pagination/kaminari_spec.rb similarity index 90% rename from elasticsearch-model/spec/elasticsearch/model/response/pagination/kaminari_spec.rb rename to opensearch-model/spec/opensearch/model/response/pagination/kaminari_spec.rb index 15ee6113c..e877f3d51 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/pagination/kaminari_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/pagination/kaminari_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Response::Response Kaminari' do +describe 'OpenSearch::Model::Response::Response Kaminari' do before(:all) do class ModelClass @@ -32,12 +32,12 @@ def self.document_type; 'bar'; end end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(model, '*') + OpenSearch::Model::Searching::SearchRequest.new(model, '*') end let(:response) do allow(model).to receive(:client).and_return(client) - Elasticsearch::Model::Response::Response.new(model, search, response_document).tap do |resp| + OpenSearch::Model::Response::Response.new(model, search, response_document).tap do |resp| allow(resp).to receive(:client).and_return(client) end end @@ -58,7 +58,7 @@ def self.document_type; 'bar'; end context 'when page is called once' do let(:search_request) do - { index: index_field, from: 25, size: 25, q: '*', type: type_field} + { index: index_field, from: 25, size: 25, q: '*'} end before do @@ -75,11 +75,11 @@ def self.document_type; 'bar'; end context 'when page is called more than once' do let(:search_request_one) do - { index: index_field, from: 25, size: 25, q: '*', type: type_field} + { index: index_field, from: 25, size: 25, q: '*'} end let(:search_request_two) do - { index: index_field, from: 75, size: 25, q: '*', type: type_field} + { index: index_field, from: 75, size: 25, q: '*'} end before do @@ -152,7 +152,7 @@ def self.document_type; 'bar'; end context 'when there is a limit in the search definition' do let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(model, '*', size: 10) + OpenSearch::Model::Searching::SearchRequest.new(model, '*', size: 10) end it 'gets the limit from the search definition' do @@ -163,7 +163,7 @@ def self.document_type; 'bar'; end context 'when there is a limit in the search body' do let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(model, { query: { match_all: {} }, size: 999 }) + OpenSearch::Model::Searching::SearchRequest.new(model, { query: { match_all: {} }, size: 999 }) end it 'does not use the limit' do @@ -184,7 +184,7 @@ def self.document_type; 'bar'; end context 'when there is an offset in the search definition' do let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(model, '*', from: 50) + OpenSearch::Model::Searching::SearchRequest.new(model, '*', from: 50) end it 'gets the limit from the search definition' do @@ -195,7 +195,7 @@ def self.document_type; 'bar'; end context 'when there is an offset in the search body' do let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(model, { query: { match_all: {} }, from: 333 }) + OpenSearch::Model::Searching::SearchRequest.new(model, { query: { match_all: {} }, from: 333 }) end it 'does not use the offset' do @@ -386,7 +386,7 @@ def self.document_type; 'bar'; end end end - context 'when Elasticsearch version is < 7.0' do + context 'when OpenSearch version is < 7.0' do let(:response_document) do { 'took' => '5', 'timed_out' => false, '_shards' => {'one' => 'OK'}, @@ -399,10 +399,6 @@ def self.document_type; 'bar'; end ModelClass end - let(:type_field) do - 'bar' - end - let(:index_field) do 'foo' end @@ -413,11 +409,7 @@ def self.document_type; 'bar'; end context 'when the model is a multimodel' do let(:model) do - Elasticsearch::Model::Multimodel.new(ModelClass) - end - - let(:type_field) do - ['bar'] + OpenSearch::Model::Multimodel.new(ModelClass) end let(:index_field) do @@ -428,7 +420,7 @@ def self.document_type; 'bar'; end end end - context 'when Elasticsearch version is >= 7.0' do + context 'when OpenSearch version is >= 7.0' do let(:response_document) do { 'took' => '5', 'timed_out' => false, '_shards' => {'one' => 'OK'}, @@ -441,10 +433,6 @@ def self.document_type; 'bar'; end ModelClass end - let(:type_field) do - 'bar' - end - let(:index_field) do 'foo' end @@ -455,11 +443,7 @@ def self.document_type; 'bar'; end context 'when the model is a multimodel' do let(:model) do - Elasticsearch::Model::Multimodel.new(ModelClass) - end - - let(:type_field) do - ['bar'] + OpenSearch::Model::Multimodel.new(ModelClass) end let(:index_field) do diff --git a/elasticsearch-model/spec/elasticsearch/model/response/pagination/will_paginate_spec.rb b/opensearch-model/spec/opensearch/model/response/pagination/will_paginate_spec.rb similarity index 95% rename from elasticsearch-model/spec/elasticsearch/model/response/pagination/will_paginate_spec.rb rename to opensearch-model/spec/opensearch/model/response/pagination/will_paginate_spec.rb index 25f1f0d1e..8883ff6bc 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/pagination/will_paginate_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/pagination/will_paginate_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe 'Elasticsearch::Model::Response::Response WillPaginate' do +describe 'OpenSearch::Model::Response::Response WillPaginate' do before(:all) do class ModelClass @@ -30,8 +30,8 @@ def self.per_page end # Subclass Response so we can include WillPaginate module without conflicts with Kaminari. - class WillPaginateResponse < Elasticsearch::Model::Response::Response - include Elasticsearch::Model::Response::Pagination::WillPaginate + class WillPaginateResponse < OpenSearch::Model::Response::Response + include OpenSearch::Model::Response::Pagination::WillPaginate end end @@ -45,7 +45,7 @@ class WillPaginateResponse < Elasticsearch::Model::Response::Response end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(model, '*') + OpenSearch::Model::Searching::SearchRequest.new(model, '*') end let(:response) do @@ -267,7 +267,7 @@ class WillPaginateResponse < Elasticsearch::Model::Response::Response context 'when the model is a multimodel' do let(:model) do - Elasticsearch::Model::Multimodel.new(ModelClass) + OpenSearch::Model::Multimodel.new(ModelClass) end let(:default_per_page) do diff --git a/elasticsearch-model/spec/elasticsearch/model/response/records_spec.rb b/opensearch-model/spec/opensearch/model/response/records_spec.rb similarity index 83% rename from elasticsearch-model/spec/elasticsearch/model/response/records_spec.rb rename to opensearch-model/spec/opensearch/model/response/records_spec.rb index 2a80dcfc6..a329ffc05 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/records_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/records_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Response::Records do +describe OpenSearch::Model::Response::Records do before(:all) do class DummyCollection @@ -48,17 +48,17 @@ def self.find(*args) end let(:results) do - Elasticsearch::Model::Response::Results.new(DummyModel, response_document) + OpenSearch::Model::Response::Results.new(DummyModel, response_document) end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummyModel, '*').tap do |request| + OpenSearch::Model::Searching::SearchRequest.new(DummyModel, '*').tap do |request| allow(request).to receive(:execute!).and_return(response_document) end end let(:response) do - Elasticsearch::Model::Response::Response.new(DummyModel, search) + OpenSearch::Model::Response::Response.new(DummyModel, search) end let(:records) do @@ -79,7 +79,7 @@ def self.find(*args) describe '#each_with_hit' do - it 'returns each record with its Elasticsearch hit' do + it 'returns each record with its OpenSearch hit' do records.each_with_hit do |record, hit| expect(record).to eq('FOO') expect(hit.foo).to eq('bar') @@ -93,7 +93,7 @@ def self.find(*args) records.map_with_hit { |record, hit| "#{record}---#{hit.foo}" } end - it 'returns each record with its Elasticsearch hit' do + it 'returns each record with its OpenSearch hit' do expect(value).to eq(['FOO---bar']) end end @@ -120,11 +120,11 @@ def records_mixin end; module_function :records_mixin end - allow(Elasticsearch::Model::Adapter).to receive(:from_class).and_return(DummyAdapter) + allow(OpenSearch::Model::Adapter).to receive(:from_class).and_return(DummyAdapter) end after do - Elasticsearch::Model::Adapter::Adapter.adapters.delete(DummyAdapter) + OpenSearch::Model::Adapter::Adapter.adapters.delete(DummyAdapter) Object.send(:remove_const, :DummyAdapter) if defined?(DummyAdapter) end diff --git a/elasticsearch-model/spec/elasticsearch/model/response/response_spec.rb b/opensearch-model/spec/opensearch/model/response/response_spec.rb similarity index 89% rename from elasticsearch-model/spec/elasticsearch/model/response/response_spec.rb rename to opensearch-model/spec/opensearch/model/response/response_spec.rb index e9a423812..5527578d0 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/response_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/response_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Response::Response do +describe OpenSearch::Model::Response::Response do before(:all) do class OriginClass @@ -39,16 +39,16 @@ def self.document_type; 'bar'; end end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| + OpenSearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| allow(request).to receive(:execute!).and_return(response_document) end end let(:response) do - Elasticsearch::Model::Response::Response.new(OriginClass, search) + OpenSearch::Model::Response::Response.new(OriginClass, search) end - it 'performs the Elasticsearch request lazily' do + it 'performs the OpenSearch request lazily' do expect(search).not_to receive(:execute!) response end @@ -98,7 +98,7 @@ def self.document_type; 'bar'; end describe '#results' do it 'provides access to the results' do - expect(response.results).to be_a(Elasticsearch::Model::Response::Results) + expect(response.results).to be_a(OpenSearch::Model::Response::Results) expect(response.size).to be(0) end end @@ -106,7 +106,7 @@ def self.document_type; 'bar'; end describe '#records' do it 'provides access to the records' do - expect(response.records).to be_a(Elasticsearch::Model::Response::Records) + expect(response.records).to be_a(OpenSearch::Model::Response::Records) expect(response.size).to be(0) end end diff --git a/elasticsearch-model/spec/elasticsearch/model/response/result_spec.rb b/opensearch-model/spec/opensearch/model/response/result_spec.rb similarity index 97% rename from elasticsearch-model/spec/elasticsearch/model/response/result_spec.rb rename to opensearch-model/spec/opensearch/model/response/result_spec.rb index 5aa7c8f4f..3e6865365 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/result_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/result_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'active_support/json/encoding' -describe Elasticsearch::Model::Response::Result do +describe OpenSearch::Model::Response::Result do let(:result) do described_class.new(foo: 'bar', bar: { bam: 'baz' }) @@ -78,7 +78,7 @@ expect(result.respond_to? :bar).to be true end - context 'when methods map to keys in subdocuments of the response from Elasticsearch' do + context 'when methods map to keys in subdocuments of the response from OpenSearch' do it 'provides access to top level fields via a method' do expect(result.foo).to eq('bar') @@ -118,7 +118,7 @@ end end - context 'when methods do not map to keys in subdocuments of the response from Elasticsearch' do + context 'when methods do not map to keys in subdocuments of the response from OpenSearch' do it 'raises a NoMethodError' do expect { result.does_not_exist }.to raise_exception(NoMethodError) diff --git a/elasticsearch-model/spec/elasticsearch/model/response/results_spec.rb b/opensearch-model/spec/opensearch/model/response/results_spec.rb similarity index 90% rename from elasticsearch-model/spec/elasticsearch/model/response/results_spec.rb rename to opensearch-model/spec/opensearch/model/response/results_spec.rb index f69db2c01..8e2e02426 100644 --- a/elasticsearch-model/spec/elasticsearch/model/response/results_spec.rb +++ b/opensearch-model/spec/opensearch/model/response/results_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Model::Response::Results do +describe OpenSearch::Model::Response::Results do before(:all) do class OriginClass @@ -35,13 +35,13 @@ def self.document_type; 'bar'; end end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| + OpenSearch::Model::Searching::SearchRequest.new(OriginClass, '*').tap do |request| allow(request).to receive(:execute!).and_return(response_document) end end let(:response) do - Elasticsearch::Model::Response::Response.new(OriginClass, search) + OpenSearch::Model::Response::Response.new(OriginClass, search) end let(:results) do diff --git a/elasticsearch-model/spec/elasticsearch/model/searching_search_request_spec.rb b/opensearch-model/spec/opensearch/model/searching_search_request_spec.rb similarity index 69% rename from elasticsearch-model/spec/elasticsearch/model/searching_search_request_spec.rb rename to opensearch-model/spec/opensearch/model/searching_search_request_spec.rb index 1f5e72bf2..7a1bbd938 100644 --- a/elasticsearch-model/spec/elasticsearch/model/searching_search_request_spec.rb +++ b/opensearch-model/spec/opensearch/model/searching_search_request_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Model::Serializing do +describe OpenSearch::Model::Serializing do before(:all) do class ::DummySearchingModel - extend Elasticsearch::Model::Searching::ClassMethods + extend OpenSearch::Model::Searching::ClassMethods def self.index_name; 'foo'; end def self.document_type; 'bar'; end end @@ -44,11 +44,11 @@ def self.document_type; 'bar'; end context 'when the search definition is a simple query' do before do - expect(client).to receive(:search).with(index: 'foo', type: 'bar', q: 'foo').and_return({}) + expect(client).to receive(:search).with({ index: 'foo', q: 'foo' }).and_return({}) end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummySearchingModel, 'foo') + OpenSearch::Model::Searching::SearchRequest.new(DummySearchingModel, 'foo') end it 'passes the query to the client' do @@ -59,11 +59,11 @@ def self.document_type; 'bar'; end context 'when the search definition is a hash' do before do - expect(client).to receive(:search).with(index: 'foo', type: 'bar', body: { foo: 'bar' }).and_return({}) + expect(client).to receive(:search).with({ index: 'foo', body: { foo: 'bar' } }).and_return({}) end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummySearchingModel, foo: 'bar') + OpenSearch::Model::Searching::SearchRequest.new(DummySearchingModel, foo: 'bar') end it 'passes the hash to the client' do @@ -74,11 +74,11 @@ def self.document_type; 'bar'; end context 'when the search definition is a json string' do before do - expect(client).to receive(:search).with(index: 'foo', type: 'bar', body: '{"foo":"bar"}').and_return({}) + expect(client).to receive(:search).with({ index: 'foo', body: '{"foo":"bar"}' }).and_return({}) end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummySearchingModel, '{"foo":"bar"}') + OpenSearch::Model::Searching::SearchRequest.new(DummySearchingModel, '{"foo":"bar"}') end it 'passes the json string to the client' do @@ -99,11 +99,11 @@ def to_hash; {foo: 'bar'}; end end before do - expect(client).to receive(:search).with(index: 'foo', type: 'bar', body: {foo: 'bar'}).and_return({}) + expect(client).to receive(:search).with({ index: 'foo', body: { foo: 'bar' } }).and_return({}) end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummySearchingModel, MySpecialQueryBuilder.new) + OpenSearch::Model::Searching::SearchRequest.new(DummySearchingModel, MySpecialQueryBuilder.new) end it 'passes the query builder to the client and calls #to_hash on it' do @@ -114,11 +114,11 @@ def to_hash; {foo: 'bar'}; end context 'when extra options are specified' do before do - expect(client).to receive(:search).with(index: 'foo', type: 'bar', q: 'foo', size: 15).and_return({}) + expect(client).to receive(:search).with({ index: 'foo', q: 'foo', size: 15 }).and_return({}) end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummySearchingModel, 'foo', size: 15) + OpenSearch::Model::Searching::SearchRequest.new(DummySearchingModel, 'foo', size: 15) end it 'passes the extra options to the client as part of the request' do diff --git a/elasticsearch-model/spec/elasticsearch/model/searching_spec.rb b/opensearch-model/spec/opensearch/model/searching_spec.rb similarity index 83% rename from elasticsearch-model/spec/elasticsearch/model/searching_spec.rb rename to opensearch-model/spec/opensearch/model/searching_spec.rb index ccede7435..089139788 100644 --- a/elasticsearch-model/spec/elasticsearch/model/searching_spec.rb +++ b/opensearch-model/spec/opensearch/model/searching_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Model::Searching::ClassMethods do +describe OpenSearch::Model::Searching::ClassMethods do before(:all) do class ::DummySearchingModel - extend Elasticsearch::Model::Searching::ClassMethods + extend OpenSearch::Model::Searching::ClassMethods def self.index_name; 'foo'; end def self.document_type; 'bar'; end @@ -43,11 +43,11 @@ def self.document_type; 'bar'; end end before do - expect(Elasticsearch::Model::Searching::SearchRequest).to receive(:new).with(DummySearchingModel, 'foo', { default_operator: 'AND' }).and_return(response) + expect(OpenSearch::Model::Searching::SearchRequest).to receive(:new).with(DummySearchingModel, 'foo', { default_operator: 'AND' }).and_return(response) end it 'creates a search object' do - expect(DummySearchingModel.search('foo', default_operator: 'AND')).to be_a(Elasticsearch::Model::Response::Response) + expect(DummySearchingModel.search('foo', default_operator: 'AND')).to be_a(OpenSearch::Model::Response::Response) end end diff --git a/elasticsearch-model/spec/elasticsearch/model/serializing_spec.rb b/opensearch-model/spec/opensearch/model/serializing_spec.rb similarity index 90% rename from elasticsearch-model/spec/elasticsearch/model/serializing_spec.rb rename to opensearch-model/spec/opensearch/model/serializing_spec.rb index c5a26a4e4..22d03a7e8 100644 --- a/elasticsearch-model/spec/elasticsearch/model/serializing_spec.rb +++ b/opensearch-model/spec/opensearch/model/serializing_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Model::Serializing do +describe OpenSearch::Model::Serializing do before(:all) do class DummyClass - include Elasticsearch::Model::Serializing::InstanceMethods + include OpenSearch::Model::Serializing::InstanceMethods def as_json(options={}) 'HASH' diff --git a/elasticsearch-model/spec/spec_helper.rb b/opensearch-model/spec/spec_helper.rb similarity index 89% rename from elasticsearch-model/spec/spec_helper.rb rename to opensearch-model/spec/spec_helper.rb index 3bb7f8742..834499f60 100644 --- a/elasticsearch-model/spec/spec_helper.rb +++ b/opensearch-model/spec/spec_helper.rb @@ -20,7 +20,7 @@ require 'kaminari/version' require 'will_paginate' require 'will_paginate/collection' -require 'elasticsearch/model' +require 'opensearch/model' require 'hashie/version' require 'active_model' begin @@ -31,8 +31,8 @@ require 'yaml' require 'active_record' -unless defined?(ELASTICSEARCH_URL) - ELASTICSEARCH_URL = ENV['ELASTICSEARCH_URL'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" +unless defined?(OPENSEARCH_URL) + OPENSEARCH_URL = ENV['OPENSEARCH_URL'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" end RSpec.configure do |config| @@ -42,10 +42,10 @@ config.before(:suite) do require 'ansi' tracer = ::Logger.new(STDERR) - tracer.formatter = lambda { |s, d, p, m| "#{m.gsub(/^.*$/) { |n| ' ' + n }.ansi(:faint)}\n" } - Elasticsearch::Model.client = Elasticsearch::Client.new host: ELASTICSEARCH_URL, + tracer.formatter = lambda { |s, d, p, m| "#{m&.gsub(/^.*$/) { |n| ' ' + n }&.ansi(:faint)}\n" } + OpenSearch::Model.client = OpenSearch::Client.new host: OPENSEARCH_URL, tracer: (ENV['QUIET'] ? nil : tracer) - puts "Elasticsearch Version: #{Elasticsearch::Model.client.info['version']}" + puts "OpenSearch Version: #{OpenSearch::Model.client.info['version']}" unless ActiveRecord::Base.connected? ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => ":memory:" ) @@ -82,7 +82,7 @@ def active_record_at_least_4? def clear_indices(*models) models.each do |model| begin - Elasticsearch::Model.client.delete_by_query( + OpenSearch::Model.client.delete_by_query( index: model.index_name, q: '*', body: {} @@ -126,10 +126,10 @@ def drop_all_tables! # # @since 6.0.1 def delete_all_indices! - client = Elasticsearch::Model.client + client = OpenSearch::Model.client ActiveRecord::Base.descendants.each do |model| begin - client.indices.delete(index: model.index_name) if model.__elasticsearch__.index_exists? + client.indices.delete(index: model.index_name) if model.__opensearch__.index_exists? rescue end end and true diff --git a/elasticsearch-model/spec/support/app.rb b/opensearch-model/spec/support/app.rb similarity index 100% rename from elasticsearch-model/spec/support/app.rb rename to opensearch-model/spec/support/app.rb diff --git a/elasticsearch-model/spec/support/app/answer.rb b/opensearch-model/spec/support/app/answer.rb similarity index 80% rename from elasticsearch-model/spec/support/app/answer.rb rename to opensearch-model/spec/support/app/answer.rb index 9c58cc991..2d12adbd4 100644 --- a/elasticsearch-model/spec/support/app/answer.rb +++ b/opensearch-model/spec/support/app/answer.rb @@ -16,7 +16,7 @@ # under the License. class Answer < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model belongs_to :question @@ -44,7 +44,7 @@ def as_indexed_json(options={}) json.merge(join_field: { name: JOIN_TYPE, parent: question_id }) end - after_commit lambda { __elasticsearch__.index_document(routing: (question_id || 1)) }, on: :create - after_commit lambda { __elasticsearch__.update_document(routing: (question_id || 1)) }, on: :update - after_commit lambda {__elasticsearch__.delete_document(routing: (question_id || 1)) }, on: :destroy + after_commit lambda { __opensearch__.index_document(routing: (question_id || 1)) }, on: :create + after_commit lambda { __opensearch__.update_document(routing: (question_id || 1)) }, on: :update + after_commit lambda {__opensearch__.delete_document(routing: (question_id || 1)) }, on: :destroy end diff --git a/elasticsearch-model/spec/support/app/article.rb b/opensearch-model/spec/support/app/article.rb similarity index 94% rename from elasticsearch-model/spec/support/app/article.rb rename to opensearch-model/spec/support/app/article.rb index 2c122dd77..c9b861277 100644 --- a/elasticsearch-model/spec/support/app/article.rb +++ b/opensearch-model/spec/support/app/article.rb @@ -16,8 +16,8 @@ # under the License. class ::Article < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks document_type 'article' diff --git a/elasticsearch-model/spec/support/app/article_for_pagination.rb b/opensearch-model/spec/support/app/article_for_pagination.rb similarity index 81% rename from elasticsearch-model/spec/support/app/article_for_pagination.rb rename to opensearch-model/spec/support/app/article_for_pagination.rb index 7916e56b9..1a3ceea09 100644 --- a/elasticsearch-model/spec/support/app/article_for_pagination.rb +++ b/opensearch-model/spec/support/app/article_for_pagination.rb @@ -16,7 +16,12 @@ # under the License. class ::ArticleForPagination < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model + + # NOTE: This was added to fix pagination tests in ruby 3. It is not clear why + # this is necessary since this should be done automatically by including + # `OpenSearch::Model`. + include OpenSearch::Model::Importing scope :published, -> { where(published: true) } diff --git a/elasticsearch-model/spec/support/app/article_no_type.rb b/opensearch-model/spec/support/app/article_no_type.rb similarity index 94% rename from elasticsearch-model/spec/support/app/article_no_type.rb rename to opensearch-model/spec/support/app/article_no_type.rb index d3cb6b4e3..830d33946 100644 --- a/elasticsearch-model/spec/support/app/article_no_type.rb +++ b/opensearch-model/spec/support/app/article_no_type.rb @@ -16,8 +16,8 @@ # under the License. class ::ArticleNoType < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks settings index: {number_of_shards: 1, number_of_replicas: 0} do mapping do diff --git a/elasticsearch-model/spec/support/app/article_with_custom_serialization.rb b/opensearch-model/spec/support/app/article_with_custom_serialization.rb similarity index 93% rename from elasticsearch-model/spec/support/app/article_with_custom_serialization.rb rename to opensearch-model/spec/support/app/article_with_custom_serialization.rb index 527143694..826eae75f 100644 --- a/elasticsearch-model/spec/support/app/article_with_custom_serialization.rb +++ b/opensearch-model/spec/support/app/article_with_custom_serialization.rb @@ -16,8 +16,8 @@ # under the License. class ::ArticleWithCustomSerialization < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks mapping do indexes :title diff --git a/elasticsearch-model/spec/support/app/article_with_dynamic_index_name.rb b/opensearch-model/spec/support/app/article_with_dynamic_index_name.rb similarity index 93% rename from elasticsearch-model/spec/support/app/article_with_dynamic_index_name.rb rename to opensearch-model/spec/support/app/article_with_dynamic_index_name.rb index 6fa1f1298..9f40abef2 100644 --- a/elasticsearch-model/spec/support/app/article_with_dynamic_index_name.rb +++ b/opensearch-model/spec/support/app/article_with_dynamic_index_name.rb @@ -16,8 +16,8 @@ # under the License. class ::ArticleWithDynamicIndexName < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks def self.counter=(value) @counter = 0 diff --git a/elasticsearch-model/spec/support/app/author.rb b/opensearch-model/spec/support/app/author.rb similarity index 100% rename from elasticsearch-model/spec/support/app/author.rb rename to opensearch-model/spec/support/app/author.rb diff --git a/elasticsearch-model/spec/support/app/authorship.rb b/opensearch-model/spec/support/app/authorship.rb similarity index 100% rename from elasticsearch-model/spec/support/app/authorship.rb rename to opensearch-model/spec/support/app/authorship.rb diff --git a/elasticsearch-model/spec/support/app/category.rb b/opensearch-model/spec/support/app/category.rb similarity index 100% rename from elasticsearch-model/spec/support/app/category.rb rename to opensearch-model/spec/support/app/category.rb diff --git a/elasticsearch-model/spec/support/app/comment.rb b/opensearch-model/spec/support/app/comment.rb similarity index 100% rename from elasticsearch-model/spec/support/app/comment.rb rename to opensearch-model/spec/support/app/comment.rb diff --git a/elasticsearch-model/spec/support/app/episode.rb b/opensearch-model/spec/support/app/episode.rb similarity index 93% rename from elasticsearch-model/spec/support/app/episode.rb rename to opensearch-model/spec/support/app/episode.rb index 34ebfc3eb..f5369ff29 100644 --- a/elasticsearch-model/spec/support/app/episode.rb +++ b/opensearch-model/spec/support/app/episode.rb @@ -16,8 +16,8 @@ # under the License. class Episode < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks settings index: {number_of_shards: 1, number_of_replicas: 0} do mapping do diff --git a/elasticsearch-model/spec/support/app/image.rb b/opensearch-model/spec/support/app/image.rb similarity index 94% rename from elasticsearch-model/spec/support/app/image.rb rename to opensearch-model/spec/support/app/image.rb index 155e974cd..ffd8ad33c 100644 --- a/elasticsearch-model/spec/support/app/image.rb +++ b/opensearch-model/spec/support/app/image.rb @@ -17,8 +17,8 @@ class Image include Mongoid::Document - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks field :name, type: String attr_accessible :name if respond_to? :attr_accessible diff --git a/elasticsearch-model/spec/support/app/import_article.rb b/opensearch-model/spec/support/app/import_article.rb similarity index 93% rename from elasticsearch-model/spec/support/app/import_article.rb rename to opensearch-model/spec/support/app/import_article.rb index eb0a4962c..5a754631a 100644 --- a/elasticsearch-model/spec/support/app/import_article.rb +++ b/opensearch-model/spec/support/app/import_article.rb @@ -16,7 +16,8 @@ # under the License. class ImportArticle < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model + include OpenSearch::Model::Importing scope :popular, -> { where('views >= 5') } diff --git a/elasticsearch-model/spec/support/app/mongoid_article.rb b/opensearch-model/spec/support/app/mongoid_article.rb similarity index 94% rename from elasticsearch-model/spec/support/app/mongoid_article.rb rename to opensearch-model/spec/support/app/mongoid_article.rb index 5e7c991ca..eb02d360a 100644 --- a/elasticsearch-model/spec/support/app/mongoid_article.rb +++ b/opensearch-model/spec/support/app/mongoid_article.rb @@ -17,8 +17,8 @@ class ::MongoidArticle include Mongoid::Document - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks field :id, type: String field :title, type: String diff --git a/elasticsearch-model/spec/support/app/namespaced_book.rb b/opensearch-model/spec/support/app/namespaced_book.rb similarity index 92% rename from elasticsearch-model/spec/support/app/namespaced_book.rb rename to opensearch-model/spec/support/app/namespaced_book.rb index f6d9c838c..b449f563a 100644 --- a/elasticsearch-model/spec/support/app/namespaced_book.rb +++ b/opensearch-model/spec/support/app/namespaced_book.rb @@ -17,8 +17,8 @@ module MyNamespace class Book < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks document_type 'book' diff --git a/elasticsearch-model/spec/support/app/parent_and_child_searchable.rb b/opensearch-model/spec/support/app/parent_and_child_searchable.rb similarity index 88% rename from elasticsearch-model/spec/support/app/parent_and_child_searchable.rb rename to opensearch-model/spec/support/app/parent_and_child_searchable.rb index 91693479f..b500b0bbd 100644 --- a/elasticsearch-model/spec/support/app/parent_and_child_searchable.rb +++ b/opensearch-model/spec/support/app/parent_and_child_searchable.rb @@ -20,16 +20,16 @@ module ParentChildSearchable JOIN = 'join'.freeze def create_index!(options={}) - client = Question.__elasticsearch__.client + client = Question.__opensearch__.client client.indices.delete index: INDEX_NAME rescue nil if options.delete(:force) settings = Question.settings.to_hash.merge Answer.settings.to_hash mapping_properties = { join_field: { type: JOIN, relations: { Question::JOIN_TYPE => Answer::JOIN_TYPE } } } - merged_properties = mapping_properties.merge(Question.mappings.to_hash[:doc][:properties]).merge( - Answer.mappings.to_hash[:doc][:properties]) - mappings = { doc: { properties: merged_properties }} + merged_properties = mapping_properties.merge(Question.mappings.to_hash[:properties]).merge( + Answer.mappings.to_hash[:properties]) + mappings = { properties: merged_properties } client.indices.create({ index: INDEX_NAME, body: { diff --git a/elasticsearch-model/spec/support/app/post.rb b/opensearch-model/spec/support/app/post.rb similarity index 66% rename from elasticsearch-model/spec/support/app/post.rb rename to opensearch-model/spec/support/app/post.rb index 9805d9cc3..1aad43998 100644 --- a/elasticsearch-model/spec/support/app/post.rb +++ b/opensearch-model/spec/support/app/post.rb @@ -18,14 +18,14 @@ class Post < ActiveRecord::Base include Searchable - has_and_belongs_to_many :categories, after_add: [ lambda { |a,c| a.__elasticsearch__.index_document } ], - after_remove: [ lambda { |a,c| a.__elasticsearch__.index_document } ] + has_and_belongs_to_many :categories, after_add: [ lambda { |a,c| a.__opensearch__.index_document } ], + after_remove: [ lambda { |a,c| a.__opensearch__.index_document } ] has_many :authorships has_many :authors, through: :authorships, - after_add: [ lambda { |a,c| a.__elasticsearch__.index_document } ], - after_remove: [ lambda { |a,c| a.__elasticsearch__.index_document } ] - has_many :comments, after_add: [ lambda { |a,c| a.__elasticsearch__.index_document } ], - after_remove: [ lambda { |a,c| a.__elasticsearch__.index_document } ] + after_add: [ lambda { |a,c| a.__opensearch__.index_document } ], + after_remove: [ lambda { |a,c| a.__opensearch__.index_document } ] + has_many :comments, after_add: [ lambda { |a,c| a.__opensearch__.index_document } ], + after_remove: [ lambda { |a,c| a.__opensearch__.index_document } ] - after_touch() { __elasticsearch__.index_document } + after_touch() { __opensearch__.index_document } end diff --git a/elasticsearch-model/spec/support/app/question.rb b/opensearch-model/spec/support/app/question.rb similarity index 83% rename from elasticsearch-model/spec/support/app/question.rb rename to opensearch-model/spec/support/app/question.rb index 62a7d4550..4862c99d6 100644 --- a/elasticsearch-model/spec/support/app/question.rb +++ b/opensearch-model/spec/support/app/question.rb @@ -16,7 +16,7 @@ # under the License. class Question < ActiveRecord::Base - include Elasticsearch::Model + include OpenSearch::Model has_many :answers, dependent: :destroy @@ -38,7 +38,7 @@ def as_indexed_json(options={}) json.merge(JOIN_METADATA) end - after_commit lambda { __elasticsearch__.index_document }, on: :create - after_commit lambda { __elasticsearch__.update_document }, on: :update - after_commit lambda { __elasticsearch__.delete_document }, on: :destroy + after_commit lambda { __opensearch__.index_document }, on: :create + after_commit lambda { __opensearch__.update_document }, on: :update + after_commit lambda { __opensearch__.delete_document }, on: :destroy end diff --git a/elasticsearch-model/spec/support/app/searchable.rb b/opensearch-model/spec/support/app/searchable.rb similarity index 90% rename from elasticsearch-model/spec/support/app/searchable.rb rename to opensearch-model/spec/support/app/searchable.rb index 81ddf78b3..014f30881 100644 --- a/elasticsearch-model/spec/support/app/searchable.rb +++ b/opensearch-model/spec/support/app/searchable.rb @@ -19,8 +19,8 @@ module Searchable extend ActiveSupport::Concern included do - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks # Set up the mapping # @@ -46,7 +46,7 @@ module Searchable end end - # Customize the JSON serialization for Elasticsearch + # Customize the JSON serialization for OpenSearch # def as_indexed_json(options={}) { @@ -60,6 +60,6 @@ def as_indexed_json(options={}) # Update document in the index after touch # - after_touch() { __elasticsearch__.index_document } + after_touch() { __opensearch__.index_document } end end diff --git a/elasticsearch-model/spec/support/app/series.rb b/opensearch-model/spec/support/app/series.rb similarity index 93% rename from elasticsearch-model/spec/support/app/series.rb rename to opensearch-model/spec/support/app/series.rb index 3b4d17989..a5d86ad2b 100644 --- a/elasticsearch-model/spec/support/app/series.rb +++ b/opensearch-model/spec/support/app/series.rb @@ -16,8 +16,8 @@ # under the License. class Series < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks settings index: {number_of_shards: 1, number_of_replicas: 0} do mapping do diff --git a/elasticsearch-model/spec/support/model.json b/opensearch-model/spec/support/model.json similarity index 100% rename from elasticsearch-model/spec/support/model.json rename to opensearch-model/spec/support/model.json diff --git a/elasticsearch-model/spec/support/model.yml b/opensearch-model/spec/support/model.yml similarity index 100% rename from elasticsearch-model/spec/support/model.yml rename to opensearch-model/spec/support/model.yml diff --git a/elasticsearch-persistence/.gitignore b/opensearch-persistence/.gitignore similarity index 100% rename from elasticsearch-persistence/.gitignore rename to opensearch-persistence/.gitignore diff --git a/elasticsearch-persistence/.rspec b/opensearch-persistence/.rspec similarity index 100% rename from elasticsearch-persistence/.rspec rename to opensearch-persistence/.rspec diff --git a/opensearch-persistence/CHANGELOG.md b/opensearch-persistence/CHANGELOG.md new file mode 100644 index 000000000..4e3adb6d2 --- /dev/null +++ b/opensearch-persistence/CHANGELOG.md @@ -0,0 +1 @@ +## 0.1.0 (Initial Version) diff --git a/elasticsearch-persistence/Gemfile b/opensearch-persistence/Gemfile similarity index 84% rename from elasticsearch-persistence/Gemfile rename to opensearch-persistence/Gemfile index 17e92d051..bd8f896d1 100644 --- a/elasticsearch-persistence/Gemfile +++ b/opensearch-persistence/Gemfile @@ -17,11 +17,11 @@ source 'https://rubygems.org' -# Specify your gem's dependencies in elasticsearch-persistence.gemspec +# Specify your gem's dependencies in opensearch-persistence.gemspec gemspec -gem 'elasticsearch-model', - path: File.expand_path('../elasticsearch-model', __dir__), +gem 'opensearch-model', + path: File.expand_path('../opensearch-model', __dir__), require: false group :development, :testing do diff --git a/elasticsearch-persistence/LICENSE.txt b/opensearch-persistence/LICENSE.txt similarity index 100% rename from elasticsearch-persistence/LICENSE.txt rename to opensearch-persistence/LICENSE.txt diff --git a/elasticsearch-persistence/README.md b/opensearch-persistence/README.md similarity index 76% rename from elasticsearch-persistence/README.md rename to opensearch-persistence/README.md index 6b905f593..cf68ab1d4 100644 --- a/elasticsearch-persistence/README.md +++ b/opensearch-persistence/README.md @@ -1,35 +1,31 @@ -# Elasticsearch::Persistence +# OpenSearch::Persistence -Persistence layer for Ruby domain objects in Elasticsearch, using the Repository pattern. +Persistence layer for Ruby domain objects in OpenSearch, using the Repository pattern. ## Compatibility This library is compatible with Ruby 2.4 and higher. -The library version numbers follow the Elasticsearch major versions. The `main` branch is compatible with the latest Elasticsearch stack stable release. +The library version numbers follow the OpenSearch major versions. The `main` branch is compatible with the latest OpenSearch stack stable release. -| Rubygem | | Elasticsearch | +| Rubygem | | OpenSearch | |:-------------:|:-:| :-----------: | -| 0.1 | → | 1.x | -| 2.x | → | 2.x | -| 5.x | → | 5.x | -| 6.x | → | 6.x | -| main | → | 7.x | +| main | → | 2.x | ## Installation Install the package from [Rubygems](https://rubygems.org): - gem install elasticsearch-persistence + gem install opensearch-persistence To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://bundler.io): - gem 'elasticsearch-persistence', git: 'git://github.com/elastic/elasticsearch-rails.git', branch: '6.x' + gem 'opensearch-persistence', git: 'git://github.com/compliance-innovations/opensearch-rails.git', branch: '6.x' or install it from a source code checkout: - git clone https://github.com/elastic/elasticsearch-rails.git - cd elasticsearch-rails/elasticsearch-persistence + git clone https://github.com/compliance-innovations/opensearch-rails.git + cd opensearch-rails/opensearch-persistence bundle install rake install @@ -39,9 +35,9 @@ The library provides the Repository pattern for adding persistence to your Ruby ### The Repository Pattern -The `Elasticsearch::Persistence::Repository` module provides an implementation of the +The `OpenSearch::Persistence::Repository` module provides an implementation of the [repository pattern](http://martinfowler.com/eaaCatalog/repository.html) and allows -you to save, delete, find and search objects stored in Elasticsearch, as well as configure +you to save, delete, find and search objects stored in OpenSearch, as well as configure mappings and settings for the index. It's an unobtrusive and decoupled way of adding persistence to your Ruby objects. @@ -64,8 +60,8 @@ end Let's create a default, "dumb" repository, as a first step: ```ruby -require 'elasticsearch/persistence' -class MyRepository; include Elasticsearch::Persistence::Repository; end +require 'opensearch/persistence' +class MyRepository; include OpenSearch::Persistence::Repository; end repository = MyRepository.new ``` @@ -110,26 +106,26 @@ repository.delete(note) The repository module provides a number of features and facilities to configure and customize the behavior: -* Configuring the Elasticsearch [client](https://github.com/elastic/elasticsearch-ruby#usage) being used +* Configuring the OpenSearch [client](https://github.com/opensearch-project/opensearch-ruby#sample-code) being used * Setting the index name, document type, and object class for deserialization * Composing mappings and settings for the index * Creating, deleting or refreshing the index * Finding or searching for documents * Providing access both to domain objects and hits for search results -* Providing access to the Elasticsearch response for search results (aggregations, total, ...) +* Providing access to the OpenSearch response for search results (aggregations, total, ...) * Defining the methods for serialization and deserialization -There are two mixins you can include in your Repository class. The first `Elasticsearch::Persistence::Repository`, -provides the basic methods and settings you'll need. The second, `Elasticsearch::Persistence::Repository::DSL` adds +There are two mixins you can include in your Repository class. The first `OpenSearch::Persistence::Repository`, +provides the basic methods and settings you'll need. The second, `OpenSearch::Persistence::Repository::DSL` adds some additional class methods that allow you to set options that instances of the class will share. #### Basic Repository mixin -For simple cases, you can just include the Elasticsearch::Persistence::Repository mixin to your class: +For simple cases, you can just include the OpenSearch::Persistence::Repository mixin to your class: ```ruby class MyRepository - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository # Customize the serialization logic def serialize(document) @@ -143,8 +139,8 @@ class MyRepository end end -client = Elasticsearch::Client.new(url: ENV['ELASTICSEARCH_URL'], log: true) -repository = MyRepository.new(client: client, index_name: :my_notes, type: :note, klass: Note) +client = OpenSearch::Client.new(url: ENV['OPENSEARCH_URL'], log: true) +repository = MyRepository.new(client: client, index_name: :my_notes, klass: Note) repository.settings number_of_shards: 1 do mapping do indexes :text, analyzer: 'snowball' @@ -152,7 +148,7 @@ repository.settings number_of_shards: 1 do end ``` -The custom Elasticsearch client will be used now, with a custom index and type names, +The custom OpenSearch client will be used now, with a custom index and type names, as well as the custom serialization and de-serialization logic. We can create the index with the desired settings and mappings: @@ -189,8 +185,8 @@ most sense when the instances of the repository will use that same configuration require 'base64' class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL index_name 'notes' document_type 'note' @@ -225,7 +221,7 @@ end You can create an instance of this custom class and get each of the configurations. ```ruby -client = Elasticsearch::Client.new(url: 'http://localhost:9200', log: true) +client = OpenSearch::Client.new(url: 'http://localhost:9200', log: true) repository = NoteRepository.new(client: client) repository.index_name # => 'notes' @@ -235,7 +231,7 @@ repository.index_name You can also override the default configuration with options passed to the initialize method: ```ruby -client = Elasticsearch::Client.new(url: 'http://localhost:9250', log: true) +client = OpenSearch::Client.new(url: 'http://localhost:9250', log: true) client.transport.transport.logger.formatter = proc { |s, d, p, m| "\e[2m# #{m}\n\e[0m" } repository = NoteRepository.new(client: client, index_name: 'notes_development') @@ -255,21 +251,21 @@ puts repository.find(1).attributes['image'] #### Functionality Provided by the Repository mixin Each of the following configurations can be set for a repository instance. -If you have included the `Elasticsearch::Persistence::Repository::DSL` mixin, then you can use the class-level DSL +If you have included the `OpenSearch::Persistence::Repository::DSL` mixin, then you can use the class-level DSL methods to set each value. You can still override the configuration for any instance by passing options to the `#initialize` method. Even if you don't use the DSL mixin, you can set the instance configuration with options passed the `#initialize` method. ##### Client -The repository uses the standard Elasticsearch [client](https://github.com/elastic/elasticsearch-ruby#usage). +The repository uses the standard OpenSearch [client](https://github.com/opensearch-project/opensearch-ruby#sample-code). ```ruby -client = Elasticsearch::Client.new(url: 'http://search.server.org') +client = OpenSearch::Client.new(url: 'http://search.server.org') repository = NoteRepository.new(client: client) repository.client.transport.transport.logger = Logger.new(STDERR) repository.client -# => Elasticsearch::Client +# => OpenSearch::Client ``` @@ -277,21 +273,21 @@ or with the DSL mixin: ```ruby class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL - client Elasticsearch::Client.new url: 'http://search.server.org' + client OpenSearch::Client.new url: 'http://search.server.org' end repository = NoteRepository.new repository.client -# => Elasticsearch::Client +# => OpenSearch::Client ``` ##### Naming -The `index_name` method specifies the Elasticsearch index to use for storage, lookup and search. The default index name +The `index_name` method specifies the OpenSearch index to use for storage, lookup and search. The default index name is 'repository'. ```ruby @@ -305,8 +301,8 @@ or with the DSL mixin: ```ruby class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL index_name 'notes_development' end @@ -317,8 +313,8 @@ repository.index_name ``` -The `document_type` method specifies the Elasticsearch document type to use for storage, lookup and search. The default value is -'_doc'. Keep in mind that future versions of Elasticsearch will not allow you to set this yourself and will use the type, +The `document_type` method specifies the OpenSearch document type to use for storage, lookup and search. The default value is +'_doc'. Keep in mind that future versions of OpenSearch will not allow you to set this yourself and will use the type, '_doc'. ```ruby @@ -332,8 +328,8 @@ or with the DSL mixin: ```ruby class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL document_type 'note' end @@ -359,8 +355,8 @@ or with the DSL mixin: ```ruby class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL klass Note end @@ -374,7 +370,7 @@ repository.klass ##### Index Configuration The `settings` and `mappings` methods, provided by the -[`elasticsearch-model`](http://rubydoc.info/gems/elasticsearch-model/Elasticsearch/Model/Indexing/ClassMethods) +[`opensearch-model`](http://rubydoc.info/gems/opensearch-model/OpenSearch/Model/Indexing/ClassMethods) gem, allow you to configure the index properties: ```ruby @@ -391,8 +387,8 @@ or with the DSL mixin: ```ruby class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL mappings { indexes :title, analyzer: 'snowball' } settings number_of_shards: 1 @@ -428,11 +424,11 @@ These methods can only be called on repository instances and are not implemented ##### Serialization The `serialize` and `deserialize` methods allow you to customize the serialization of the document when it -is persisted to Elasticsearch, and define the initialization procedure when loading it from the storage: +is persisted to OpenSearch, and define the initialization procedure when loading it from the storage: ```ruby class NoteRepository - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository def serialize(document) Hash[document.to_hash.map() { |k,v| v.upcase! if k == :title; [k,v] }] @@ -502,7 +498,7 @@ Handle the missing objects in the application code, or call `compact` on the res ##### Search -The `search` method is used to retrieve objects from the repository by a query string or definition in the Elasticsearch DSL: +The `search` method is used to retrieve objects from the repository by a query string or definition in the OpenSearch DSL: ```ruby repository.search('fox or dog').to_a @@ -515,7 +511,7 @@ repository.search(query: { match: { title: 'fox dog' } }).to_a # => [, ] ``` -The returned object is an instance of the `Elasticsearch::Persistence::Repository::Response::Results` class, +The returned object is an instance of the `OpenSearch::Persistence::Repository::Response::Results` class, which provides access to the results, the full returned response and hits. ```ruby @@ -564,11 +560,6 @@ and demonstrates a rich set of features: * How to write complex search definitions, including pagination, highlighting and aggregations * How to use search results in the application view -### The ActiveRecord Pattern - -The ActiveRecord pattern has been deprecated as of version 6.0.0 of this gem. Please use the -[Repository Pattern](#the-repository-pattern) instead. For more information on migrating 5.x ActiveRecord-based applications to use the Repository Pattern, please see [this blog post](https://www.elastic.co/blog/activerecord-to-repository-changing-persistence-patterns-with-the-elasticsearch-rails-gem). - ## License This software is licensed under the Apache 2 license, quoted below. diff --git a/elasticsearch-persistence/Rakefile b/opensearch-persistence/Rakefile similarity index 100% rename from elasticsearch-persistence/Rakefile rename to opensearch-persistence/Rakefile diff --git a/elasticsearch-persistence/examples/notes/.gitignore b/opensearch-persistence/examples/notes/.gitignore similarity index 100% rename from elasticsearch-persistence/examples/notes/.gitignore rename to opensearch-persistence/examples/notes/.gitignore diff --git a/elasticsearch-persistence/examples/notes/Gemfile b/opensearch-persistence/examples/notes/Gemfile similarity index 82% rename from elasticsearch-persistence/examples/notes/Gemfile rename to opensearch-persistence/examples/notes/Gemfile index ef2c098c4..8436621e1 100644 --- a/elasticsearch-persistence/examples/notes/Gemfile +++ b/opensearch-persistence/examples/notes/Gemfile @@ -25,9 +25,9 @@ gem 'oj' gem 'hashie' gem 'patron' -gem 'elasticsearch' -gem 'elasticsearch-model', git: 'https://github.com/elastic/elasticsearch-rails.git' -gem 'elasticsearch-persistence', git: 'https://github.com/elastic/elasticsearch-rails.git' +gem 'opensearch-ruby', '~> 2.0' +gem 'opensearch-model', git: 'https://github.com/compliance-innovations/opensearch-rails.git' +gem 'opensearch-persistence', git: 'https://github.com/compliance-innovations/opensearch-rails.git' gem 'sinatra', require: false gem 'thin' diff --git a/elasticsearch-persistence/examples/notes/README.markdown b/opensearch-persistence/examples/notes/README.markdown similarity index 96% rename from elasticsearch-persistence/examples/notes/README.markdown rename to opensearch-persistence/examples/notes/README.markdown index 0d9313d72..0f9960934 100644 --- a/elasticsearch-persistence/examples/notes/README.markdown +++ b/opensearch-persistence/examples/notes/README.markdown @@ -1,7 +1,7 @@ Demo Aplication for the Repository Pattern ========================================== -This directory contains a simple demo application for the repository pattern of the `Elasticsearch::Persistence` +This directory contains a simple demo application for the repository pattern of the `OpenSearch::Persistence` module in the [Sinatra](http://www.sinatrarb.com) framework. To run the application, first install the required gems and start the application: diff --git a/elasticsearch-persistence/examples/notes/application.rb b/opensearch-persistence/examples/notes/application.rb similarity index 96% rename from elasticsearch-persistence/examples/notes/application.rb rename to opensearch-persistence/examples/notes/application.rb index 0f1724476..23dcf8240 100644 --- a/elasticsearch-persistence/examples/notes/application.rb +++ b/opensearch-persistence/examples/notes/application.rb @@ -23,9 +23,9 @@ require 'oj' require 'hashie/mash' -require 'elasticsearch' -require 'elasticsearch/model' -require 'elasticsearch/persistence' +require 'opensearch-ruby' +require 'opensearch/model' +require 'opensearch/persistence' class Note attr_reader :attributes @@ -69,10 +69,10 @@ def __truncate_text end class NoteRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL - client Elasticsearch::Client.new url: ENV['ELASTICSEARCH_URL'], log: true + client OpenSearch::Client.new url: ENV['OPENSEARCH_URL'], log: true index_name :notes document_type :note diff --git a/elasticsearch-persistence/examples/notes/config.ru b/opensearch-persistence/examples/notes/config.ru similarity index 100% rename from elasticsearch-persistence/examples/notes/config.ru rename to opensearch-persistence/examples/notes/config.ru diff --git a/elasticsearch-persistence/examples/notes/test.rb b/opensearch-persistence/examples/notes/test.rb similarity index 91% rename from elasticsearch-persistence/examples/notes/test.rb rename to opensearch-persistence/examples/notes/test.rb index 27922933b..badbcc07b 100644 --- a/elasticsearch-persistence/examples/notes/test.rb +++ b/opensearch-persistence/examples/notes/test.rb @@ -17,7 +17,7 @@ ENV['RACK_ENV'] = 'test' -at_exit { Elasticsearch::Test::IntegrationTestCase.__run_at_exit_hooks } if ENV['SERVER'] +at_exit { OpenSearch::Test::IntegrationTestCase.__run_at_exit_hooks } if ENV['SERVER'] require 'test/unit' require 'shoulda-context' @@ -25,14 +25,14 @@ require 'rack/test' require 'turn' -require 'elasticsearch/extensions/test/cluster' -require 'elasticsearch/extensions/test/startup_shutdown' +require 'opensearch/extensions/test/cluster' +require 'opensearch/extensions/test/startup_shutdown' require_relative 'application' NoteRepository.index_name = 'notes_test' -class Elasticsearch::Persistence::ExampleApplicationTest < Test::Unit::TestCase +class OpenSearch::Persistence::ExampleApplicationTest < Test::Unit::TestCase include Rack::Test::Methods alias :response :last_response @@ -87,7 +87,7 @@ def app context "Application" do setup do - app.settings.repository.client = Elasticsearch::Client.new \ + app.settings.repository.client = OpenSearch::Client.new \ hosts: [{ host: 'localhost', port: ENV.fetch('TEST_CLUSTER_PORT', 9250)}], log: true app.settings.repository.client.transport.transport.logger.formatter = proc { |s, d, p, m| "\e[2m#{m}\n\e[0m" } diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence.rb b/opensearch-persistence/lib/opensearch/persistence.rb similarity index 79% rename from elasticsearch-persistence/lib/elasticsearch/persistence.rb rename to opensearch-persistence/lib/opensearch/persistence.rb index ac845ce77..e0ccd86e2 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence.rb +++ b/opensearch-persistence/lib/opensearch/persistence.rb @@ -17,9 +17,9 @@ require 'hashie/mash' -require 'elasticsearch' -require 'elasticsearch/model' +require 'opensearch-ruby' +require 'opensearch/model' -require 'elasticsearch/persistence/version' -require 'elasticsearch/persistence/repository' -require 'elasticsearch/persistence/repository/response/results' +require 'opensearch/persistence/version' +require 'opensearch/persistence/repository' +require 'opensearch/persistence/repository/response/results' diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository.rb b/opensearch-persistence/lib/opensearch/persistence/repository.rb similarity index 85% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository.rb rename to opensearch-persistence/lib/opensearch/persistence/repository.rb index 607de1769..af32e4570 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository.rb @@ -15,17 +15,17 @@ # specific language governing permissions and limitations # under the License. -require 'elasticsearch/persistence/repository/dsl' -require 'elasticsearch/persistence/repository/find' -require 'elasticsearch/persistence/repository/store' -require 'elasticsearch/persistence/repository/serialize' -require 'elasticsearch/persistence/repository/search' +require 'opensearch/persistence/repository/dsl' +require 'opensearch/persistence/repository/find' +require 'opensearch/persistence/repository/store' +require 'opensearch/persistence/repository/serialize' +require 'opensearch/persistence/repository/search' -module Elasticsearch +module OpenSearch module Persistence # The base Repository mixin. This module should be included in classes that - # represent an Elasticsearch repository. + # represent an OpenSearch repository. # # @since 6.0.0 module Repository @@ -33,7 +33,7 @@ module Repository include Serialize include Find include Search - include Elasticsearch::Model::Indexing::ClassMethods + include OpenSearch::Model::Indexing::ClassMethods def self.included(base) base.send(:extend, ClassMethods) @@ -59,11 +59,11 @@ module ClassMethods # # @option options [ Symbol, String ] :index_name The name of the index. # @option options [ Symbol, String ] :document_type The type of documents persisted in this repository. - # @option options [ Symbol, String ] :client The client used to handle requests to and from Elasticsearch. + # @option options [ Symbol, String ] :client The client used to handle requests to and from OpenSearch. # @option options [ Symbol, String ] :klass The class used to instantiate an object when documents are # deserialized. The default is nil, in which case the raw document will be returned as a Hash. - # @option options [ Elasticsearch::Model::Indexing::Mappings, Hash ] :mapping The mapping for this index. - # @option options [ Elasticsearch::Model::Indexing::Settings, Hash ] :settings The settings for this index. + # @option options [ OpenSearch::Model::Indexing::Mappings, Hash ] :mapping The mapping for this index. + # @option options [ OpenSearch::Model::Indexing::Settings, Hash ] :settings The settings for this index. # # @since 6.0.0 def create(options = {}, &block) @@ -96,11 +96,11 @@ def create(options = {}, &block) # # @option options [ Symbol, String ] :index_name The name of the index. # @option options [ Symbol, String ] :document_type The type of documents persisted in this repository. - # @option options [ Symbol, String ] :client The client used to handle requests to and from Elasticsearch. + # @option options [ Symbol, String ] :client The client used to handle requests to and from OpenSearch. # @option options [ Symbol, String ] :klass The class used to instantiate an object when documents are # deserialized. The default is nil, in which case the raw document will be returned as a Hash. - # @option options [ Elasticsearch::Model::Indexing::Mappings, Hash ] :mapping The mapping for this index. - # @option options [ Elasticsearch::Model::Indexing::Settings, Hash ] :settings The settings for this index. + # @option options [ OpenSearch::Model::Indexing::Mappings, Hash ] :mapping The mapping for this index. + # @option options [ OpenSearch::Model::Indexing::Settings, Hash ] :settings The settings for this index. # # @since 6.0.0 def initialize(options = {}) @@ -112,13 +112,13 @@ def initialize(options = {}) # @example # repository.client # - # @return [ Elasticsearch::Client ] The repository's client. + # @return [ OpenSearch::Client ] The repository's client. # # @since 6.0.0 def client @client ||= @options[:client] || __get_class_value(:client) || - Elasticsearch::Client.new + OpenSearch::Client.new end # Get the document type used by the repository object. @@ -174,7 +174,7 @@ def klass # @note If mappings were set when the repository was created, a block passed to this # method will not be evaluated. # - # @return [ Elasticsearch::Model::Indexing::Mappings ] The index mappings. + # @return [ OpenSearch::Model::Indexing::Mappings ] The index mappings. # # @since 6.0.0 def mapping(*args) @@ -201,7 +201,7 @@ def mapping(*args) # end # end # - # @return [ Elasticsearch::Model::Indexing::Settings ] The index settings. + # @return [ OpenSearch::Model::Indexing::Settings ] The index settings. # # @since 6.0.0 def settings(*args) diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/dsl.rb b/opensearch-persistence/lib/opensearch/persistence/repository/dsl.rb similarity index 92% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository/dsl.rb rename to opensearch-persistence/lib/opensearch/persistence/repository/dsl.rb index de2848071..e022f2209 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/dsl.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository/dsl.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence module Repository @@ -25,12 +25,12 @@ module Repository module DSL def self.included(base) - base.send(:extend, Elasticsearch::Model::Indexing::ClassMethods) + base.send(:extend, OpenSearch::Model::Indexing::ClassMethods) base.send(:extend, ClassMethods) end # These methods are necessary to define at the class-level so that the methods available - # via Elasticsearch::Model::Indexing::ClassMethods have the references they depend on. + # via OpenSearch::Model::Indexing::ClassMethods have the references they depend on. # # @since 6.0.0 module ClassMethods @@ -80,7 +80,7 @@ def klass(_class = nil) # # @since 6.0.0 def client(_client = nil) - @client ||= (_client || Elasticsearch::Client.new) + @client ||= (_client || OpenSearch::Client.new) end def create_index!(*args) diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/find.rb b/opensearch-persistence/lib/opensearch/persistence/repository/find.rb similarity index 86% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository/find.rb rename to opensearch-persistence/lib/opensearch/persistence/repository/find.rb index cdd50c042..8598d0cbf 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/find.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository/find.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence module Repository class DocumentNotFound < StandardError; end @@ -24,7 +24,7 @@ class DocumentNotFound < StandardError; end # module Find - # Retrieve a single object or multiple objects from Elasticsearch by ID or IDs + # Retrieve a single object or multiple objects from OpenSearch by ID or IDs # # @example Retrieve a single object by ID # @@ -64,19 +64,18 @@ def find(*args) # def exists?(id, options={}) request = { index: index_name, id: id } - request[:type] = document_type if document_type client.exists(request.merge(options)) end private # The key for accessing the document found and returned from an - # Elasticsearch _mget query. + # OpenSearch _mget query. # DOCS = 'docs'.freeze # The key for the boolean value indicating whether a particular id - # has been successfully found in an Elasticsearch _mget query. + # has been successfully found in an OpenSearch _mget query. # FOUND = 'found'.freeze @@ -84,10 +83,9 @@ def exists?(id, options={}) # def __find_one(id, options={}) request = { index: index_name, id: id } - request[:type] = document_type if document_type document = client.get(request.merge(options)) deserialize(document) - rescue Elasticsearch::Transport::Transport::Errors::NotFound => e + rescue OpenSearch::Transport::Transport::Errors::NotFound => e raise DocumentNotFound, e.message, caller end @@ -95,7 +93,6 @@ def __find_one(id, options={}) # def __find_many(ids, options={}) request = { index: index_name, body: { ids: ids } } - request[:type] = document_type if document_type documents = client.mget(request.merge(options)) documents[DOCS].map do |document| deserialize(document) if document[FOUND] diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/response/results.rb b/opensearch-persistence/lib/opensearch/persistence/repository/response/results.rb similarity index 84% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository/response/results.rb rename to opensearch-persistence/lib/opensearch/persistence/repository/response/results.rb index 1852f192a..a2a817a2f 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/response/results.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository/response/results.rb @@ -15,12 +15,12 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence module Repository module Response # :nodoc: - # Encapsulates the domain objects and documents returned from Elasticsearch when searching + # Encapsulates the domain objects and documents returned from OpenSearch when searching # # Implements `Enumerable` and forwards its methods to the {#results} object. # @@ -30,24 +30,24 @@ class Results attr_reader :repository attr_reader :raw_response - # The key for accessing the results in an Elasticsearch query response. + # The key for accessing the results in an OpenSearch query response. # HITS = 'hits'.freeze - # The key for accessing the total number of hits in an Elasticsearch query response. + # The key for accessing the total number of hits in an OpenSearch query response. # TOTAL = 'total'.freeze - # The key for accessing the value field in an Elasticsearch query response when 'total' is an object. + # The key for accessing the value field in an OpenSearch query response when 'total' is an object. # VALUE = 'value'.freeze - # The key for accessing the maximum score in an Elasticsearch query response. + # The key for accessing the maximum score in an OpenSearch query response. # MAX_SCORE = 'max_score'.freeze - # @param repository [Elasticsearch::Persistence::Repository::Class] The repository instance - # @param response [Hash] The full response returned from the Elasticsearch client + # @param repository [OpenSearch::Persistence::Repository::Class] The repository instance + # @param response [Hash] The full response returned from the OpenSearch client # @param options [Hash] Optional parameters # def initialize(repository, response, options={}) @@ -107,7 +107,7 @@ def results end end - # Access the response returned from Elasticsearch by the client + # Access the response returned from OpenSearch by the client # # @example Access the aggregations in the response # @@ -116,10 +116,10 @@ def results # results.response.aggregations.titles.buckets.map { |term| "#{term['key']}: #{term['doc_count']}" } # # => ["brown: 1", "dog: 1", ...] # - # @return [Elasticsearch::Model::HashWrapper] + # @return [OpenSearch::Model::HashWrapper] # def response - @response ||= Elasticsearch::Model::HashWrapper.new(raw_response) + @response ||= OpenSearch::Model::HashWrapper.new(raw_response) end end end diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/search.rb b/opensearch-persistence/lib/opensearch/persistence/repository/search.rb similarity index 87% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository/search.rb rename to opensearch-persistence/lib/opensearch/persistence/repository/search.rb index 2aa7db725..be8d4250f 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/search.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository/search.rb @@ -15,15 +15,15 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence module Repository - # Returns a collection of domain objects by an Elasticsearch query + # Returns a collection of domain objects by an OpenSearch query # module Search - # Returns a collection of domain objects by an Elasticsearch query + # Returns a collection of domain objects by an OpenSearch query # # Pass the query either as a string or a Hash-like object # @@ -31,7 +31,7 @@ module Search # # repository.search('fox or dog') # - # @example Return objects matching a query in the Elasticsearch DSL + # @example Return objects matching a query in the OpenSearch DSL # # repository.search(query: { match: { title: 'fox dog' } }) # @@ -57,11 +57,10 @@ module Search # @param [ Hash, String ] query_or_definition The query or search definition. # @param [ Hash ] options The search options. # - # @return [Elasticsearch::Persistence::Repository::Response::Results] + # @return [OpenSearch::Persistence::Repository::Response::Results] # def search(query_or_definition, options={}) - request = { index: index_name, - type: document_type } + request = { index: index_name } if query_or_definition.respond_to?(:to_hash) request[:body] = query_or_definition.to_hash elsif query_or_definition.is_a?(String) @@ -86,7 +85,7 @@ def search(query_or_definition, options={}) # repository.count('fox or dog') # # => 1 # - # @example Return the count of domain object matching a query in the Elasticsearch DSL + # @example Return the count of domain object matching a query in the OpenSearch DSL # # repository.count(query: { match: { title: 'fox dog' } }) # # => 1 @@ -98,8 +97,7 @@ def search(query_or_definition, options={}) # def count(query_or_definition=nil, options={}) query_or_definition ||= { query: { match_all: {} } } - request = { index: index_name, - type: document_type } + request = { index: index_name } if query_or_definition.respond_to?(:to_hash) request[:body] = query_or_definition.to_hash @@ -115,7 +113,7 @@ def count(query_or_definition=nil, options={}) private - # The key for accessing the count in a Elasticsearch query response. + # The key for accessing the count in a OpenSearch query response. # COUNT = 'count'.freeze end diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/serialize.rb b/opensearch-persistence/lib/opensearch/persistence/repository/serialize.rb similarity index 88% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository/serialize.rb rename to opensearch-persistence/lib/opensearch/persistence/repository/serialize.rb index fe68a7fbb..f1d21bdf3 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/serialize.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository/serialize.rb @@ -15,17 +15,17 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence module Repository - # Provide serialization and deserialization between Ruby objects and Elasticsearch documents. + # Provide serialization and deserialization between Ruby objects and OpenSearch documents. # # Override these methods in your repository class to customize the logic. # module Serialize - # Serialize the object for storing it in Elasticsearch. + # Serialize the object for storing it in OpenSearch. # # In the default implementation, call the `to_hash` method on the passed object. # @@ -37,7 +37,7 @@ def serialize(document) document.to_hash end - # Deserialize the document retrieved from Elasticsearch into a Ruby object. + # Deserialize the document retrieved from OpenSearch into a Ruby object. # If no klass is set for the Repository then the raw document '_source' field will be returned. # # def deserialize(document) @@ -54,13 +54,13 @@ def deserialize(document) private - # The key for document fields in an Elasticsearch query response. + # The key for document fields in an OpenSearch query response. # SOURCE = '_source'.freeze - # The key for the document type in an Elasticsearch query response. + # The key for the document type in an OpenSearch query response. # Note that it will be removed eventually, as multiple types in a single - # index are deprecated as of Elasticsearch 6.0. + # index are deprecated. # TYPE = '_type'.freeze diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/store.rb b/opensearch-persistence/lib/opensearch/persistence/repository/store.rb similarity index 80% rename from elasticsearch-persistence/lib/elasticsearch/persistence/repository/store.rb rename to opensearch-persistence/lib/opensearch/persistence/repository/store.rb index a8eeb1866..d442513ae 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/repository/store.rb +++ b/opensearch-persistence/lib/opensearch/persistence/repository/store.rb @@ -15,24 +15,24 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence module Repository - # Save and delete documents in Elasticsearch + # Save and delete documents in OpenSearch # module Store - # Store the serialized object in Elasticsearch + # Store the serialized object in OpenSearch # # @example # repository.save(myobject) # => {"_index"=>"...", "_type"=>"...", "_id"=>"...", "_version"=>1, "created"=>true} # - # @param [ Object ] document The document to save into Elasticsearch. + # @param [ Object ] document The document to save into OpenSearch. # @param [ Hash ] options The save request options. # - # @return [ Hash ] The response from Elasticsearch + # @return [ Hash ] The response from OpenSearch # def save(document, options={}) serialized = serialize(document) @@ -40,11 +40,10 @@ def save(document, options={}) request = { index: index_name, id: id, body: serialized } - request[:type] = document_type if document_type client.index(request.merge(options)) end - # Update the serialized object in Elasticsearch with partial data or script + # Update the serialized object in OpenSearch with partial data or script # # @example Update the document with partial data # @@ -59,13 +58,12 @@ def save(document, options={}) # @param [ Object ] document_or_id The document to update or the id of the document to update. # @param [ Hash ] options The update request options. # - # @return [ Hash ] The response from Elasticsearch + # @return [ Hash ] The response from OpenSearch # def update(document_or_id, options = {}) if document_or_id.is_a?(String) || document_or_id.is_a?(Integer) id = document_or_id body = options - type = document_type else document = serialize(document_or_id) id = __extract_id_from_document(document) @@ -74,12 +72,11 @@ def update(document_or_id, options = {}) else body = { doc: document }.merge(options) end - type = document.delete(:type) || document_type end - client.update(index: index_name, id: id, type: type, body: body) + client.update(index: index_name, id: id, body: body) end - # Remove the serialized object or document with specified ID from Elasticsearch + # Remove the serialized object or document with specified ID from OpenSearch # # @example Remove the document with ID 1 # @@ -89,7 +86,7 @@ def update(document_or_id, options = {}) # @param [ Object ] document_or_id The document to delete or the id of the document to delete. # @param [ Hash ] options The delete request options. # - # @return [ Hash ] The response from Elasticsearch + # @return [ Hash ] The response from OpenSearch # def delete(document_or_id, options = {}) if document_or_id.is_a?(String) || document_or_id.is_a?(Integer) @@ -98,7 +95,7 @@ def delete(document_or_id, options = {}) serialized = serialize(document_or_id) id = __get_id_from_document(serialized) end - client.delete({ index: index_name, type: document_type, id: id }.merge(options)) + client.delete({ index: index_name, id: id }.merge(options)) end end end diff --git a/elasticsearch-persistence/lib/elasticsearch/persistence/version.rb b/opensearch-persistence/lib/opensearch/persistence/version.rb similarity index 94% rename from elasticsearch-persistence/lib/elasticsearch/persistence/version.rb rename to opensearch-persistence/lib/opensearch/persistence/version.rb index 18fe2466d..fda4847c8 100644 --- a/elasticsearch-persistence/lib/elasticsearch/persistence/version.rb +++ b/opensearch-persistence/lib/opensearch/persistence/version.rb @@ -15,8 +15,8 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Persistence - VERSION = '7.2.1' + VERSION = '1.0.0' end end diff --git a/elasticsearch-persistence/elasticsearch-persistence.gemspec b/opensearch-persistence/opensearch-persistence.gemspec similarity index 71% rename from elasticsearch-persistence/elasticsearch-persistence.gemspec rename to opensearch-persistence/opensearch-persistence.gemspec index f1a736127..26c210930 100644 --- a/elasticsearch-persistence/elasticsearch-persistence.gemspec +++ b/opensearch-persistence/opensearch-persistence.gemspec @@ -18,16 +18,16 @@ # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'elasticsearch/persistence/version' +require 'opensearch/persistence/version' Gem::Specification.new do |s| - s.name = "elasticsearch-persistence" - s.version = Elasticsearch::Persistence::VERSION - s.authors = ["Karel Minarik"] - s.email = ["karel.minarik@elasticsearch.org"] - s.description = "Persistence layer for Ruby models and Elasticsearch." - s.summary = "Persistence layer for Ruby models and Elasticsearch." - s.homepage = "https://github.com/elasticsearch/elasticsearch-rails/" + s.name = "opensearch-persistence" + s.version = OpenSearch::Persistence::VERSION + s.authors = ["CDD Solutions B.V."] + s.email = ["developers@compliance-innovations.com"] + s.description = "Persistence layer for Ruby models and OpenSearch." + s.summary = "Persistence layer for Ruby models and OpenSearch." + s.homepage = "https://github.com/compliance-innovations/opensearch-rails/" s.license = "Apache 2" s.files = `git ls-files -z`.split("\x0") @@ -38,12 +38,12 @@ Gem::Specification.new do |s| s.extra_rdoc_files = [ "README.md", "LICENSE.txt" ] s.rdoc_options = [ "--charset=UTF-8" ] - s.required_ruby_version = ">= 1.9.3" + s.required_ruby_version = ">= 2.5" - s.add_dependency "elasticsearch", '~> 7' - s.add_dependency "elasticsearch-model", '7.2.1' - s.add_dependency "activesupport", '> 4' - s.add_dependency "activemodel", '> 4' + s.add_dependency "opensearch-ruby", '~> 3.0' + s.add_dependency "opensearch-model" + s.add_dependency "activesupport", '>= 6.1' + s.add_dependency "activemodel", '>= 6.1' s.add_dependency "hashie" s.add_development_dependency "bundler" @@ -51,7 +51,7 @@ Gem::Specification.new do |s| s.add_development_dependency "oj" unless defined?(JRUBY_VERSION) - s.add_development_dependency "rails", '> 4' + s.add_development_dependency "rails", '>= 6.1' s.add_development_dependency "minitest" s.add_development_dependency "test-unit" diff --git a/elasticsearch-persistence/spec/repository/find_spec.rb b/opensearch-persistence/spec/repository/find_spec.rb similarity index 72% rename from elasticsearch-persistence/spec/repository/find_spec.rb rename to opensearch-persistence/spec/repository/find_spec.rb index 083ee4c25..7ea0307bf 100644 --- a/elasticsearch-persistence/spec/repository/find_spec.rb +++ b/opensearch-persistence/spec/repository/find_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Persistence::Repository::Find do +describe OpenSearch::Persistence::Repository::Find do after do begin; repository.delete_index!; rescue; end @@ -46,17 +46,6 @@ expect(repository.exists?('1')).to be(false) end end - - context 'when options are provided' do - - let(:id) do - repository.save(a: 1)['_id'] - end - - it 'applies the options' do - expect(repository.exists?(id, type: 'other_type')).to be(false) - end - end end describe '#find' do @@ -127,49 +116,7 @@ it 'raises a DocumentNotFound exception' do expect { repository.find(1) - }.to raise_exception(Elasticsearch::Persistence::Repository::DocumentNotFound) - end - end - end - - context 'when options are provided' do - - context 'when a single id is passed' do - - let!(:id) do - repository.save(a: 1)['_id'] - end - - it 'applies the options' do - expect { - repository.find(id, type: 'none') - }.to raise_exception(Elasticsearch::Persistence::Repository::DocumentNotFound) - end - end - - context 'when an array of ids is passed' do - - let!(:ids) do - 3.times.collect do |i| - repository.save(a: i)['_id'] - end - end - - it 'applies the options' do - expect(repository.find(ids, type: 'none')).to eq([nil, nil, nil]) - end - end - - context 'when multiple ids are passed' do - - let!(:ids) do - 3.times.collect do |i| - repository.save(a: i)['_id'] - end - end - - it 'applies the options' do - expect(repository.find(*ids, type: 'none')).to eq([nil, nil, nil]) + }.to raise_exception(OpenSearch::Persistence::Repository::DocumentNotFound) end end end diff --git a/elasticsearch-persistence/spec/repository/response/results_spec.rb b/opensearch-persistence/spec/repository/response/results_spec.rb similarity index 91% rename from elasticsearch-persistence/spec/repository/response/results_spec.rb rename to opensearch-persistence/spec/repository/response/results_spec.rb index 9d98cfc79..775b722d0 100644 --- a/elasticsearch-persistence/spec/repository/response/results_spec.rb +++ b/opensearch-persistence/spec/repository/response/results_spec.rb @@ -17,11 +17,11 @@ require 'spec_helper' -describe Elasticsearch::Persistence::Repository::Response::Results do +describe OpenSearch::Persistence::Repository::Response::Results do before(:all) do class MyRepository - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository def deserialize(document) 'Object' @@ -87,7 +87,7 @@ def deserialize(document) context 'when the response method is not called' do it 'does not create an instance of HashWrapper' do - expect(Elasticsearch::Model::HashWrapper).not_to receive(:new) + expect(OpenSearch::Model::HashWrapper).not_to receive(:new) results end end @@ -95,7 +95,7 @@ def deserialize(document) context 'when the response method is called' do it 'does create an instance of HashWrapper' do - expect(Elasticsearch::Model::HashWrapper).to receive(:new) + expect(OpenSearch::Model::HashWrapper).to receive(:new) results.response end end @@ -138,7 +138,7 @@ def deserialize(document) describe '#raw_response' do - it 'returns the raw response from Elasticsearch' do + it 'returns the raw response from OpenSearch' do expect(results.raw_response).to eq(response) end end diff --git a/opensearch-persistence/spec/repository/search_spec.rb b/opensearch-persistence/spec/repository/search_spec.rb new file mode 100644 index 000000000..d0fbff7f4 --- /dev/null +++ b/opensearch-persistence/spec/repository/search_spec.rb @@ -0,0 +1,84 @@ +# Licensed to Elasticsearch B.V. under one or more contributor +# license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright +# ownership. Elasticsearch B.V. licenses this file to you under +# the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +require 'spec_helper' + +describe OpenSearch::Persistence::Repository::Search do + + after do + begin; repository.delete_index!; rescue; end + end + + describe '#search' do + + let(:repository) do + DEFAULT_REPOSITORY + end + + before do + repository.save({ name: 'user' }, refresh: true) + end + + context 'when a query definition is provided as a hash' do + + it 'uses the default document type' do + expect(repository.search({ query: { match: { name: 'user' } } }).first).to eq('name' => 'user') + end + end + + context 'when a query definition is provided as a string' do + + it 'uses the default document type' do + expect(repository.search('user').first).to eq('name' => 'user') + end + end + + context 'when the query definition is neither a String nor a Hash' do + + it 'raises an ArgumentError' do + expect { + repository.search(1) + }.to raise_exception(ArgumentError) + end + end + end + + describe '#count' do + + let(:repository) do + DEFAULT_REPOSITORY + end + + before do + repository.save({ name: 'user' }, refresh: true) + end + + context 'when a query definition is provided as a hash' do + + it 'uses the default document type' do + expect(repository.count({ query: { match: { name: 'user' } } })).to eq(1) + end + end + + context 'when a query definition is provided as a string' do + + it 'uses the default document type' do + expect(repository.count('user')).to eq(1) + end + end + end +end diff --git a/elasticsearch-persistence/spec/repository/serialize_spec.rb b/opensearch-persistence/spec/repository/serialize_spec.rb similarity index 96% rename from elasticsearch-persistence/spec/repository/serialize_spec.rb rename to opensearch-persistence/spec/repository/serialize_spec.rb index 17e358686..310513960 100644 --- a/elasticsearch-persistence/spec/repository/serialize_spec.rb +++ b/opensearch-persistence/spec/repository/serialize_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Persistence::Repository::Serialize do +describe OpenSearch::Persistence::Repository::Serialize do let(:repository) do DEFAULT_REPOSITORY diff --git a/elasticsearch-persistence/spec/repository/store_spec.rb b/opensearch-persistence/spec/repository/store_spec.rb similarity index 90% rename from elasticsearch-persistence/spec/repository/store_spec.rb rename to opensearch-persistence/spec/repository/store_spec.rb index bebf810aa..5d46d7088 100644 --- a/elasticsearch-persistence/spec/repository/store_spec.rb +++ b/opensearch-persistence/spec/repository/store_spec.rb @@ -17,7 +17,7 @@ require 'spec_helper' -describe Elasticsearch::Persistence::Repository::Store do +describe OpenSearch::Persistence::Repository::Store do let(:repository) do DEFAULT_REPOSITORY @@ -45,7 +45,7 @@ before do class OtherNoteRepository - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository def serialize(document) { b: 1 } end @@ -74,14 +74,12 @@ def serialize(document) context 'when options are provided' do let!(:response) do - repository.save(document, type: 'other_note') + repository.save(document) end it 'saves the document using the options' do - expect { - repository.find(response['_id']) - }.to raise_exception(Elasticsearch::Persistence::Repository::DocumentNotFound) - expect(repository.find(response['_id'], type: 'other_note')).to eq('a' => 1) + repository.find(response['_id']) + expect(repository.find(response['_id'])).to eq('a' => 1) end end end @@ -242,7 +240,7 @@ def to_hash it 'raises an exception' do expect { repository.update(1, doc: { text: 'testing_2' }) - }.to raise_exception(Elasticsearch::Transport::Transport::Errors::NotFound) + }.to raise_exception(OpenSearch::Transport::Transport::Errors::NotFound) end context 'when upsert is provided' do @@ -262,7 +260,7 @@ def to_hash it 'raises an exception' do expect { repository.update(id: 1, text: 'testing_2') - }.to raise_exception(Elasticsearch::Transport::Transport::Errors::NotFound) + }.to raise_exception(OpenSearch::Transport::Transport::Errors::NotFound) end context 'when upsert is provided' do @@ -310,7 +308,7 @@ def to_hash it 'deletes the document using the id' do expect { repository.find(id) - }.to raise_exception(Elasticsearch::Persistence::Repository::DocumentNotFound) + }.to raise_exception(OpenSearch::Persistence::Repository::DocumentNotFound) end end @@ -323,7 +321,7 @@ def to_hash it 'deletes the document using the document' do expect { repository.find(id) - }.to raise_exception(Elasticsearch::Persistence::Repository::DocumentNotFound) + }.to raise_exception(OpenSearch::Persistence::Repository::DocumentNotFound) end end end @@ -331,13 +329,13 @@ def to_hash context 'when the document does not exist' do before do - repository.create_index!(include_type_name: true) + repository.create_index! end it 'raises an exception' do expect { repository.delete(1) - }.to raise_exception(Elasticsearch::Transport::Transport::Errors::NotFound) + }.to raise_exception(OpenSearch::Transport::Transport::Errors::NotFound) end end end diff --git a/elasticsearch-persistence/spec/repository_spec.rb b/opensearch-persistence/spec/repository_spec.rb similarity index 86% rename from elasticsearch-persistence/spec/repository_spec.rb rename to opensearch-persistence/spec/repository_spec.rb index 05aeb1f53..08c810b32 100644 --- a/elasticsearch-persistence/spec/repository_spec.rb +++ b/opensearch-persistence/spec/repository_spec.rb @@ -17,13 +17,13 @@ require 'spec_helper' -describe Elasticsearch::Persistence::Repository do +describe OpenSearch::Persistence::Repository do describe '#create' do before(:all) do class RepositoryWithoutDSL - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository end end @@ -59,7 +59,7 @@ class RepositoryWithoutDSL end it 'executes the block on the instance' do - expect(repository.mapping.to_hash).to eq(note: { dynamic: 'strict', properties: { foo: { type: 'text' } } }) + expect(repository.mapping.to_hash).to eq( dynamic: 'strict', properties: { foo: { type: 'text' } }) end context 'when options are provided in the args and set in the block' do @@ -83,7 +83,7 @@ class RepositoryWithoutDSL before(:all) do class RepositoryWithoutDSL - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository end end @@ -104,7 +104,7 @@ class RepositoryWithoutDSL end it 'sets a default client' do - expect(repository.client).to be_a(Elasticsearch::Client) + expect(repository.client).to be_a(OpenSearch::Client) end @@ -120,7 +120,7 @@ class RepositoryWithoutDSL context 'when options are provided' do let(:client) do - Elasticsearch::Client.new + OpenSearch::Client.new end let(:repository) do @@ -149,8 +149,8 @@ class RepositoryWithoutDSL before(:all) do class RepositoryWithDSL - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL document_type 'note' index_name 'notes_repo' @@ -279,7 +279,7 @@ class RepositoryWithDSL before do begin; repository.delete_index!; rescue; end - repository.create_index!(include_type_name: true) + repository.create_index! end it 'creates the index' do @@ -334,7 +334,7 @@ class RepositoryWithDSL end before do - repository.create_index!(include_type_name: true) + repository.create_index! end it 'refreshes the index' do @@ -361,7 +361,7 @@ class RepositoryWithDSL end before do - repository.create_index!(include_type_name: true) + repository.create_index! end it 'determines if the index exists' do @@ -389,11 +389,10 @@ class RepositoryWithDSL describe '#mapping' do let(:expected_mapping) do - { note: { dynamic: 'strict', - properties: { foo: { type: 'object', - properties: { bar: { type: 'text' } } }, - baz: { type: 'text' } } - } + { dynamic: 'strict', + properties: { foo: { type: 'object', + properties: { bar: { type: 'text' } } }, + baz: { type: 'text' } } } end @@ -406,17 +405,16 @@ class RepositoryWithDSL end it 'allows the value to be overridden with options on the instance' do - expect(RepositoryWithDSL.new(mapping: double('mapping', to_hash: { note: {} })).mapping.to_hash).to eq(note: {}) + expect(RepositoryWithDSL.new(mapping: double('mapping', to_hash: {})).mapping.to_hash).to eq({}) end context 'when the instance has a different document type' do let(:expected_mapping) do - { other_note: { dynamic: 'strict', - properties: { foo: { type: 'object', - properties: { bar: { type: 'text' } } }, - baz: { type: 'text' } } - } + { dynamic: 'strict', + properties: { foo: { type: 'object', + properties: { bar: { type: 'text' } } }, + baz: { type: 'text' } } } end @@ -446,7 +444,7 @@ class RepositoryWithDSL before(:all) do class RepositoryWithoutDSL - include Elasticsearch::Persistence::Repository + include OpenSearch::Persistence::Repository end end @@ -465,7 +463,7 @@ class RepositoryWithoutDSL end it 'sets a default on the instance' do - expect(RepositoryWithoutDSL.new.client).to be_a(Elasticsearch::Client) + expect(RepositoryWithoutDSL.new.client).to be_a(OpenSearch::Client) end it 'allows the value to be overridden with options on the instance' do @@ -547,24 +545,9 @@ class RepositoryWithoutDSL RepositoryWithoutDSL.new(client: DEFAULT_CLIENT, document_type: 'mytype') end - context 'when the server is version >= 7.0', if: server_version > '7.0' do - - context 'when the include_type_name option is specified' do - - it 'creates an index' do - repository.create_index!(include_type_name: true) - expect(repository.index_exists?).to eq(true) - end - end - - context 'when the include_type_name option is not specified' do - - it 'raises an error' do - expect { - repository.create_index! - }.to raise_exception(Elasticsearch::Transport::Transport::Errors::BadRequest) - end - end + it 'raises an error' do + repository.create_index! + expect(repository.index_exists?).to eq(true) end end end @@ -582,7 +565,7 @@ class RepositoryWithoutDSL end it 'deletes an index' do - repository.create_index!(include_type_name: true) + repository.create_index! repository.delete_index! expect(repository.index_exists?).to eq(false) end @@ -605,7 +588,7 @@ class RepositoryWithoutDSL end it 'refreshes an index' do - repository.create_index!(include_type_name: true) + repository.create_index! expect(repository.refresh_index!['_shards']).to be_a(Hash) end end @@ -627,7 +610,7 @@ class RepositoryWithoutDSL end it 'returns whether the index exists' do - repository.create_index!(include_type_name: true) + repository.create_index! expect(repository.index_exists?).to be(true) end end @@ -645,17 +628,16 @@ class RepositoryWithoutDSL end it 'allows the mapping to be set as an option' do - expect(RepositoryWithoutDSL.new(mapping: double('mapping', to_hash: { note: {} })).mapping.to_hash).to eq(note: {}) + expect(RepositoryWithoutDSL.new(mapping: double('mapping', to_hash: { })).mapping.to_hash).to eq({}) end context 'when a block is passed to the create method' do let(:expected_mapping) do - { note: { dynamic: 'strict', - properties: { foo: { type: 'object', - properties: { bar: { type: 'text' } } }, - baz: { type: 'text' } } - } + { dynamic: 'strict', + properties: { foo: { type: 'object', + properties: { bar: { type: 'text' } } }, + baz: { type: 'text' } } } end @@ -677,7 +659,7 @@ class RepositoryWithoutDSL context 'when the mapping is set in the options' do let(:repository) do - RepositoryWithoutDSL.create(mapping: double('mapping', to_hash: { note: {} })) do + RepositoryWithoutDSL.create(mapping: double('mapping', to_hash: { })) do mapping dynamic: 'strict' do indexes :foo do indexes :bar @@ -688,7 +670,7 @@ class RepositoryWithoutDSL end it 'uses the mapping from the options' do - expect(repository.mapping.to_hash).to eq(note: {}) + expect(repository.mapping.to_hash).to eq({}) end end end @@ -725,11 +707,10 @@ class RepositoryWithoutDSL context 'when a mapping is set in the block as well' do let(:expected_mapping) do - { note: { dynamic: 'strict', - properties: { foo: { type: 'object', - properties: { bar: { type: 'text' } } }, - baz: { type: 'text' } } - } + { dynamic: 'strict', + properties: { foo: { type: 'object', + properties: { bar: { type: 'text' } } }, + baz: { type: 'text' } } } end diff --git a/elasticsearch-persistence/spec/spec_helper.rb b/opensearch-persistence/spec/spec_helper.rb similarity index 73% rename from elasticsearch-persistence/spec/spec_helper.rb rename to opensearch-persistence/spec/spec_helper.rb index 6e5f58402..8f0003cb2 100644 --- a/elasticsearch-persistence/spec/spec_helper.rb +++ b/opensearch-persistence/spec/spec_helper.rb @@ -16,17 +16,17 @@ # under the License. require 'pry-nav' -require 'elasticsearch/persistence' +require 'opensearch/persistence' -unless defined?(ELASTICSEARCH_URL) - ELASTICSEARCH_URL = ENV['ELASTICSEARCH_URL'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" +unless defined?(OPENSEARCH_URL) + OPENSEARCH_URL = ENV['OPENSEARCH_URL'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" end RSpec.configure do |config| config.formatter = 'documentation' config.color = true - config.before(:suite) { puts "Elasticsearch Version: #{DEFAULT_CLIENT.info['version']}" } + config.before(:suite) { puts "OpenSearch Version: #{DEFAULT_CLIENT.info['version']}" } config.after(:suite) do DEFAULT_CLIENT.indices.delete(index: '_all') end @@ -35,12 +35,12 @@ # The default client to be used by the repositories. # # @since 6.0.0 -DEFAULT_CLIENT = Elasticsearch::Client.new(host: ELASTICSEARCH_URL, +DEFAULT_CLIENT = OpenSearch::Client.new(host: OPENSEARCH_URL, tracer: (ENV['QUIET'] ? nil : ::Logger.new(STDERR))) class MyTestRepository - include Elasticsearch::Persistence::Repository - include Elasticsearch::Persistence::Repository::DSL + include OpenSearch::Persistence::Repository + include OpenSearch::Persistence::Repository::DSL client DEFAULT_CLIENT end @@ -49,9 +49,9 @@ class MyTestRepository # @since 6.0.0 DEFAULT_REPOSITORY = MyTestRepository.new(index_name: 'my_test_repository', document_type: 'test') -# Get the Elasticsearch server version. +# Get the OpenSearch server version. # -# @return [ String ] The version of Elasticsearch. +# @return [ String ] The version of OpenSearch. # # @since 7.0.0 def server_version(client = nil) diff --git a/elasticsearch-rails/.gitignore b/opensearch-rails/.gitignore similarity index 100% rename from elasticsearch-rails/.gitignore rename to opensearch-rails/.gitignore diff --git a/opensearch-rails/CHANGELOG.md b/opensearch-rails/CHANGELOG.md new file mode 100644 index 000000000..4e3adb6d2 --- /dev/null +++ b/opensearch-rails/CHANGELOG.md @@ -0,0 +1 @@ +## 0.1.0 (Initial Version) diff --git a/elasticsearch-rails/Gemfile b/opensearch-rails/Gemfile similarity index 79% rename from elasticsearch-rails/Gemfile rename to opensearch-rails/Gemfile index 90572cba1..535f4de15 100644 --- a/elasticsearch-rails/Gemfile +++ b/opensearch-rails/Gemfile @@ -17,15 +17,15 @@ source 'https://rubygems.org' -# Specify your gem's dependencies in elasticsearch-rails.gemspec +# Specify your gem's dependencies in opensearch-rails.gemspec gemspec -gem 'elasticsearch-model', - path: File.expand_path('../elasticsearch-model', __dir__), +gem 'opensearch-model', + path: File.expand_path('../opensearch-model', __dir__), require: false -gem 'elasticsearch-persistence', - path: File.expand_path('../elasticsearch-persistence', __dir__), +gem 'opensearch-persistence', + path: File.expand_path('../opensearch-persistence', __dir__), require: false group :development, :testing do diff --git a/elasticsearch-rails/LICENSE.txt b/opensearch-rails/LICENSE.txt similarity index 100% rename from elasticsearch-rails/LICENSE.txt rename to opensearch-rails/LICENSE.txt diff --git a/elasticsearch-rails/README.md b/opensearch-rails/README.md similarity index 59% rename from elasticsearch-rails/README.md rename to opensearch-rails/README.md index 375f379f5..7597238e8 100644 --- a/elasticsearch-rails/README.md +++ b/opensearch-rails/README.md @@ -1,39 +1,34 @@ -# Elasticsearch::Rails +# OpenSearch::Rails -The `elasticsearch-rails` library is a companion for the -the [`elasticsearch-model`](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-model) +The `opensearch-rails` library is a companion for the +the [`opensearch-model`](https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-model) library, providing features suitable for Ruby on Rails applications. ## Compatibility This library is compatible with Ruby 1.9.3 and higher. -The library version numbers follow the Elasticsearch major versions, and the `main` branch -is compatible with the Elasticsearch `master` branch, therefore, with the next major version. +The library version numbers follow the OpenSearch major versions, and the `main` branch +is compatible with the OpenSearch `master` branch, therefore, with the next major version. -| Rubygem | | Elasticsearch | +| Rubygem | | OpenSearch | |:-------------:|:-:| :-----------: | -| 0.1 | → | 1.x | -| 2.x | → | 2.x | -| 5.x | → | 5.x | -| 6.x | → | 6.x | -| 7.x | → | 7.x | | main | → | master | ## Installation Install the package from [Rubygems](https://rubygems.org): - gem install elasticsearch-rails + gem install opensearch-rails To use an unreleased version, either add it to your `Gemfile` for [Bundler](http://bundler.io): - gem 'elasticsearch-rails', git: 'git://github.com/elastic/elasticsearch-rails.git', branch: '5.x' + gem 'opensearch-rails', git: 'git://github.com/compliance-innovations/opensearch-rails.git', branch: '5.x' or install it from a source code checkout: - git clone https://github.com/elastic/elasticsearch-rails.git - cd elasticsearch-rails/elasticsearch-rails + git clone https://github.com/compliance-innovations/opensearch-rails.git + cd opensearch-rails/opensearch-rails bundle install rake install @@ -41,17 +36,17 @@ or install it from a source code checkout: ### Rake Tasks -To facilitate importing data from your models into Elasticsearch, require the task definition in your application, -eg. in the `lib/tasks/elasticsearch.rake` file: +To facilitate importing data from your models into OpenSearch, require the task definition in your application, +eg. in the `lib/tasks/opensearch.rake` file: ```ruby -require 'elasticsearch/rails/tasks/import' +require 'opensearch/rails/tasks/import' ``` To import the records from your `Article` model, run: ```bash -$ bundle exec rake environment elasticsearch:import:model CLASS='Article' +$ bundle exec rake environment opensearch:import:model CLASS='Article' ``` To limit the imported records to a certain @@ -59,13 +54,13 @@ ActiveRecord [scope](http://guides.rubyonrails.org/active_record_querying.html#s pass it to the task: ```bash -$ bundle exec rake environment elasticsearch:import:model CLASS='Article' SCOPE='published' +$ bundle exec rake environment opensearch:import:model CLASS='Article' SCOPE='published' ``` Run this command to display usage instructions: ```bash -$ bundle exec rake -D elasticsearch +$ bundle exec rake -D opensearch ``` ### ActiveSupport Instrumentation @@ -74,25 +69,25 @@ To display information about the search request (duration, search definition) du and to include the information in the Rails log file, require the component in your `application.rb` file: ```ruby -require 'elasticsearch/rails/instrumentation' +require 'opensearch/rails/instrumentation' ``` You should see an output like this in your application log in development environment: - Article Search (321.3ms) { index: "articles", type: "article", body: { query: ... } } + Article Search (321.3ms) { index: "articles", body: { query: ... } } -Also, the total duration of the request to Elasticsearch is displayed in the Rails request breakdown: +Also, the total duration of the request to OpenSearch is displayed in the Rails request breakdown: - Completed 200 OK in 615ms (Views: 230.9ms | ActiveRecord: 0.0ms | Elasticsearch: 321.3ms) + Completed 200 OK in 615ms (Views: 230.9ms | ActiveRecord: 0.0ms | OpenSearch: 321.3ms) There's a special component for the [Lograge](https://github.com/roidrage/lograge) logger. Require the component in your `application.rb` file (and set `config.lograge.enabled`): ```ruby -require 'elasticsearch/rails/lograge' +require 'opensearch/rails/lograge' ``` -You should see the duration of the request to Elasticsearch as part of each log event: +You should see the duration of the request to OpenSearch as part of each log event: method=GET path=/search ... status=200 duration=380.89 view=99.64 db=0.00 es=279.37 @@ -101,30 +96,30 @@ You should see the duration of the request to Elasticsearch as part of each log You can generate a fully working example Ruby on Rails application, with an `Article` model and a search form, to play with (it generates the application skeleton and leaves you with a _Git_ repository to explore the steps and the code) with the -[`01-basic.rb`](https://github.com/elastic/elasticsearch-rails/blob/main/elasticsearch-rails/lib/rails/templates/01-basic.rb) template: +[`01-basic.rb`](https://github.com/compliance-innovations/opensearch-rails/blob/main/opensearch-rails/lib/rails/templates/01-basic.rb) template: ```bash -rails new searchapp --skip --skip-bundle --template https://raw.github.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/01-basic.rb +rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/01-basic.rb ``` Run the same command again, in the same folder, with the -[`02-pretty`](https://github.com/elastic/elasticsearch-rails/blob/main/elasticsearch-rails/lib/rails/templates/02-pretty.rb) +[`02-pretty`](https://github.com/compliance-innovations/opensearch-rails/blob/main/opensearch-rails/lib/rails/templates/02-pretty.rb) template to add features such as a custom `Article.search` method, result highlighting and [_Bootstrap_](http://getbootstrap.com) integration: ```bash -rails new searchapp --skip --skip-bundle --template https://raw.github.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/02-pretty.rb +rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/02-pretty.rb ``` -Run the same command with the [`03-expert.rb`](https://github.com/elastic/elasticsearch-rails/blob/main/elasticsearch-rails/lib/rails/templates/03-expert.rb) +Run the same command with the [`03-expert.rb`](https://github.com/compliance-innovations/opensearch-rails/blob/main/opensearch-rails/lib/rails/templates/03-expert.rb) template to refactor the application into a more complex use case, with couple of hundreds of The New York Times articles as the example content. -The template will extract the Elasticsearch integration into a `Searchable` "concern" module, +The template will extract the OpenSearch integration into a `Searchable` "concern" module, define complex mapping, custom serialization, implement faceted navigation and suggestions as a part of a complex query, and add a _Sidekiq_-based worker for updating the index in the background. ```bash -rails new searchapp --skip --skip-bundle --template https://raw.github.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/03-expert.rb +rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/03-expert.rb ``` ## License diff --git a/elasticsearch-rails/Rakefile b/opensearch-rails/Rakefile similarity index 100% rename from elasticsearch-rails/Rakefile rename to opensearch-rails/Rakefile diff --git a/elasticsearch-rails/lib/elasticsearch/rails.rb b/opensearch-rails/lib/opensearch/rails.rb similarity index 93% rename from elasticsearch-rails/lib/elasticsearch/rails.rb rename to opensearch-rails/lib/opensearch/rails.rb index 1f6bac36f..53f52463b 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails.rb +++ b/opensearch-rails/lib/opensearch/rails.rb @@ -15,9 +15,9 @@ # specific language governing permissions and limitations # under the License. -require "elasticsearch/rails/version" +require "opensearch/rails/version" -module Elasticsearch +module OpenSearch module Rails # Your code goes here... end diff --git a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation.rb b/opensearch-rails/lib/opensearch/rails/instrumentation.rb similarity index 77% rename from elasticsearch-rails/lib/elasticsearch/rails/instrumentation.rb rename to opensearch-rails/lib/opensearch/rails/instrumentation.rb index ca210066a..010f53a9d 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation.rb +++ b/opensearch-rails/lib/opensearch/rails/instrumentation.rb @@ -15,10 +15,10 @@ # specific language governing permissions and limitations # under the License. -require 'elasticsearch/rails/instrumentation/railtie' -require 'elasticsearch/rails/instrumentation/publishers' +require 'opensearch/rails/instrumentation/railtie' +require 'opensearch/rails/instrumentation/publishers' -module Elasticsearch +module OpenSearch module Rails # This module adds support for displaying statistics about search duration in the Rails application log @@ -28,21 +28,21 @@ module Rails # # Require the component in your `application.rb` file: # - # require 'elasticsearch/rails/instrumentation' + # require 'opensearch/rails/instrumentation' # # You should see an output like this in your application log in development environment: # # Article Search (321.3ms) { index: "articles", type: "article", body: { query: ... } } # - # Also, the total duration of the request to Elasticsearch is displayed in the Rails request breakdown: + # Also, the total duration of the request to OpenSearch is displayed in the Rails request breakdown: # - # Completed 200 OK in 615ms (Views: 230.9ms | ActiveRecord: 0.0ms | Elasticsearch: 321.3ms) + # Completed 200 OK in 615ms (Views: 230.9ms | ActiveRecord: 0.0ms | OpenSearch: 321.3ms) # - # @note The displayed duration includes the HTTP transfer -- the time it took Elasticsearch + # @note The displayed duration includes the HTTP transfer -- the time it took OpenSearch # to process your request is available in the `response.took` property. # - # @see Elasticsearch::Rails::Instrumentation::Publishers - # @see Elasticsearch::Rails::Instrumentation::Railtie + # @see OpenSearch::Rails::Instrumentation::Publishers + # @see OpenSearch::Rails::Instrumentation::Railtie # # @see http://api.rubyonrails.org/classes/ActiveSupport/Notifications.html # diff --git a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/controller_runtime.rb b/opensearch-rails/lib/opensearch/rails/instrumentation/controller_runtime.rb similarity index 62% rename from elasticsearch-rails/lib/elasticsearch/rails/instrumentation/controller_runtime.rb rename to opensearch-rails/lib/opensearch/rails/instrumentation/controller_runtime.rb index a26765c54..80c034302 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/controller_runtime.rb +++ b/opensearch-rails/lib/opensearch/rails/instrumentation/controller_runtime.rb @@ -17,11 +17,11 @@ require 'active_support/core_ext/module/attr_internal' -module Elasticsearch +module OpenSearch module Rails module Instrumentation - # Hooks into ActionController to display Elasticsearch runtime + # Hooks into ActionController to display OpenSearch runtime # # @see https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/controller_runtime.rb # @@ -30,25 +30,25 @@ module ControllerRuntime protected - attr_internal :elasticsearch_runtime + attr_internal :opensearch_runtime def cleanup_view_runtime - elasticsearch_rt_before_render = Elasticsearch::Rails::Instrumentation::LogSubscriber.reset_runtime + opensearch_rt_before_render = OpenSearch::Rails::Instrumentation::LogSubscriber.reset_runtime runtime = super - elasticsearch_rt_after_render = Elasticsearch::Rails::Instrumentation::LogSubscriber.reset_runtime - self.elasticsearch_runtime = elasticsearch_rt_before_render + elasticsearch_rt_after_render - runtime - elasticsearch_rt_after_render + opensearch_rt_after_render = OpenSearch::Rails::Instrumentation::LogSubscriber.reset_runtime + self.opensearch_runtime = opensearch_rt_before_render + opensearch_rt_after_render + runtime - opensearch_rt_after_render end def append_info_to_payload(payload) super - payload[:elasticsearch_runtime] = (elasticsearch_runtime || 0) + Elasticsearch::Rails::Instrumentation::LogSubscriber.reset_runtime + payload[:opensearch_runtime] = (opensearch_runtime || 0) + OpenSearch::Rails::Instrumentation::LogSubscriber.reset_runtime end module ClassMethods def log_process_action(payload) - messages, elasticsearch_runtime = super, payload[:elasticsearch_runtime] - messages << ("Elasticsearch: %.1fms" % elasticsearch_runtime.to_f) if elasticsearch_runtime + messages, opensearch_runtime = super, payload[:opensearch_runtime] + messages << ("OpenSearch: %.1fms" % opensearch_runtime.to_f) if opensearch_runtime messages end end diff --git a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/log_subscriber.rb b/opensearch-rails/lib/opensearch/rails/instrumentation/log_subscriber.rb similarity index 81% rename from elasticsearch-rails/lib/elasticsearch/rails/instrumentation/log_subscriber.rb rename to opensearch-rails/lib/opensearch/rails/instrumentation/log_subscriber.rb index c388961c0..a925dcc24 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/log_subscriber.rb +++ b/opensearch-rails/lib/opensearch/rails/instrumentation/log_subscriber.rb @@ -15,21 +15,21 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Rails module Instrumentation - # A log subscriber to attach to Elasticsearch related events + # A log subscriber to attach to OpenSearch related events # # @see https://github.com/rails/rails/blob/master/activerecord/lib/active_record/log_subscriber.rb # class LogSubscriber < ActiveSupport::LogSubscriber def self.runtime=(value) - Thread.current["elasticsearch_runtime"] = value + Thread.current["opensearch_runtime"] = value end def self.runtime - Thread.current["elasticsearch_runtime"] ||= 0 + Thread.current["opensearch_runtime"] ||= 0 end def self.reset_runtime @@ -37,7 +37,7 @@ def self.reset_runtime rt end - # Intercept `search.elasticsearch` events, and display them in the Rails log + # Intercept `search.opensearch` events, and display them in the Rails log # def search(event) self.class.runtime += event.duration @@ -55,4 +55,4 @@ def search(event) end end -Elasticsearch::Rails::Instrumentation::LogSubscriber.attach_to :elasticsearch +OpenSearch::Rails::Instrumentation::LogSubscriber.attach_to :opensearch diff --git a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/publishers.rb b/opensearch-rails/lib/opensearch/rails/instrumentation/publishers.rb similarity index 88% rename from elasticsearch-rails/lib/elasticsearch/rails/instrumentation/publishers.rb rename to opensearch-rails/lib/opensearch/rails/instrumentation/publishers.rb index 2c36d91bd..4670f2604 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/publishers.rb +++ b/opensearch-rails/lib/opensearch/rails/instrumentation/publishers.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Rails module Instrumentation module Publishers @@ -39,9 +39,9 @@ def self.included(base) # Wrap `Search#execute!` and perform instrumentation # def execute_with_instrumentation! - ActiveSupport::Notifications.instrument "search.elasticsearch", + ActiveSupport::Notifications.instrument "search.opensearch", name: 'Search', - klass: (self.klass.is_a?(Elasticsearch::Model::Proxy::ClassMethodsProxy) ? self.klass.target.to_s : self.klass.to_s), + klass: (self.klass.is_a?(OpenSearch::Model::Proxy::ClassMethodsProxy) ? self.klass.target.to_s : self.klass.to_s), search: self.definition do execute_without_instrumentation! end diff --git a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/railtie.rb b/opensearch-rails/lib/opensearch/rails/instrumentation/railtie.rb similarity index 59% rename from elasticsearch-rails/lib/elasticsearch/rails/instrumentation/railtie.rb rename to opensearch-rails/lib/opensearch/rails/instrumentation/railtie.rb index 38fdbc6f1..3584f3fda 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/instrumentation/railtie.rb +++ b/opensearch-rails/lib/opensearch/rails/instrumentation/railtie.rb @@ -15,26 +15,26 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Rails module Instrumentation - # Rails initializer class to require Elasticsearch::Rails::Instrumentation files, - # set up Elasticsearch::Model and hook into ActionController to display Elasticsearch-related duration + # Rails initializer class to require OpenSearch::Rails::Instrumentation files, + # set up OpenSearch::Model and hook into ActionController to display OpenSearch-related duration # # @see http://edgeguides.rubyonrails.org/active_support_instrumentation.html # class Railtie < ::Rails::Railtie - initializer "elasticsearch.instrumentation" do |app| - require 'elasticsearch/rails/instrumentation/log_subscriber' - require 'elasticsearch/rails/instrumentation/controller_runtime' + initializer "opensearch.instrumentation" do |app| + require 'opensearch/rails/instrumentation/log_subscriber' + require 'opensearch/rails/instrumentation/controller_runtime' - Elasticsearch::Model::Searching::SearchRequest.class_eval do - include Elasticsearch::Rails::Instrumentation::Publishers::SearchRequest - end if defined?(Elasticsearch::Model::Searching::SearchRequest) + OpenSearch::Model::Searching::SearchRequest.class_eval do + include OpenSearch::Rails::Instrumentation::Publishers::SearchRequest + end if defined?(OpenSearch::Model::Searching::SearchRequest) ActiveSupport.on_load(:action_controller) do - include Elasticsearch::Rails::Instrumentation::ControllerRuntime + include OpenSearch::Rails::Instrumentation::ControllerRuntime end end end diff --git a/elasticsearch-rails/lib/elasticsearch/rails/lograge.rb b/opensearch-rails/lib/opensearch/rails/lograge.rb similarity index 56% rename from elasticsearch-rails/lib/elasticsearch/rails/lograge.rb rename to opensearch-rails/lib/opensearch/rails/lograge.rb index d2bd06467..61269bc63 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/lograge.rb +++ b/opensearch-rails/lib/opensearch/rails/lograge.rb @@ -15,39 +15,39 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Rails module Lograge - # Rails initializer class to require Elasticsearch::Rails::Instrumentation files, - # set up Elasticsearch::Model and add Lograge configuration to display Elasticsearch-related duration + # Rails initializer class to require OpenSearch::Rails::Instrumentation files, + # set up OpenSearch::Model and add Lograge configuration to display OpenSearch-related duration # # Require the component in your `application.rb` file and enable Lograge: # - # require 'elasticsearch/rails/lograge' + # require 'opensearch/rails/lograge' # - # You should see the full duration of the request to Elasticsearch as part of each log event: + # You should see the full duration of the request to OpenSearch as part of each log event: # # method=GET path=/search ... status=200 duration=380.89 view=99.64 db=0.00 es=279.37 # # @see https://github.com/roidrage/lograge # class Railtie < ::Rails::Railtie - initializer "elasticsearch.lograge" do |app| - require 'elasticsearch/rails/instrumentation/publishers' - require 'elasticsearch/rails/instrumentation/log_subscriber' - require 'elasticsearch/rails/instrumentation/controller_runtime' + initializer "opensearch.lograge" do |app| + require 'opensearch/rails/instrumentation/publishers' + require 'opensearch/rails/instrumentation/log_subscriber' + require 'opensearch/rails/instrumentation/controller_runtime' - Elasticsearch::Model::Searching::SearchRequest.class_eval do - include Elasticsearch::Rails::Instrumentation::Publishers::SearchRequest - end if defined?(Elasticsearch::Model::Searching::SearchRequest) + OpenSearch::Model::Searching::SearchRequest.class_eval do + include OpenSearch::Rails::Instrumentation::Publishers::SearchRequest + end if defined?(OpenSearch::Model::Searching::SearchRequest) ActiveSupport.on_load(:action_controller) do - include Elasticsearch::Rails::Instrumentation::ControllerRuntime + include OpenSearch::Rails::Instrumentation::ControllerRuntime end config.lograge.custom_options = lambda do |event| - { es: event.payload[:elasticsearch_runtime].to_f.round(2) } + { es: event.payload[:opensearch_runtime].to_f.round(2) } end end end diff --git a/elasticsearch-rails/lib/elasticsearch/rails/tasks/import.rb b/opensearch-rails/lib/opensearch/rails/tasks/import.rb similarity index 71% rename from elasticsearch-rails/lib/elasticsearch/rails/tasks/import.rb rename to opensearch-rails/lib/opensearch/rails/tasks/import.rb index 91f4441ea..a0bdf4c82 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/tasks/import.rb +++ b/opensearch-rails/lib/opensearch/rails/tasks/import.rb @@ -15,26 +15,26 @@ # specific language governing permissions and limitations # under the License. -# A collection of Rake tasks to facilitate importing data from your models into Elasticsearch. +# A collection of Rake tasks to facilitate importing data from your models into OpenSearch. # -# Add this e.g. into the `lib/tasks/elasticsearch.rake` file in your Rails application: +# Add this e.g. into the `lib/tasks/opensearch.rake` file in your Rails application: # -# require 'elasticsearch/rails/tasks/import' +# require 'opensearch/rails/tasks/import' # # To import the records from your `Article` model, run: # -# $ bundle exec rake environment elasticsearch:import:model CLASS='MyModel' +# $ bundle exec rake environment opensearch:import:model CLASS='MyModel' # # Run this command to display usage instructions: # -# $ bundle exec rake -D elasticsearch +# $ bundle exec rake -D opensearch # STDOUT.sync = true STDERR.sync = true begin; require 'ansi/progressbar'; rescue LoadError; end -namespace :elasticsearch do +namespace :opensearch do task :import => 'import:model' @@ -42,19 +42,19 @@ import_model_desc = <<-DESC.gsub(/ /, '') Import data from your model (pass name as CLASS environment variable). - $ rake environment elasticsearch:import:model CLASS='MyModel' + $ rake environment opensearch:import:model CLASS='MyModel' Force rebuilding the index (delete and create): - $ rake environment elasticsearch:import:model CLASS='Article' FORCE=y + $ rake environment opensearch:import:model CLASS='Article' FORCE=y Customize the batch size: - $ rake environment elasticsearch:import:model CLASS='Article' BATCH=100 + $ rake environment opensearch:import:model CLASS='Article' BATCH=100 Set target index name: - $ rake environment elasticsearch:import:model CLASS='Article' INDEX='articles-new' + $ rake environment opensearch:import:model CLASS='Article' INDEX='articles-new' Pass an ActiveRecord scope to limit the imported records: - $ rake environment elasticsearch:import:model CLASS='Article' SCOPE='published' + $ rake environment opensearch:import:model CLASS='Article' SCOPE='published' DESC desc import_model_desc task :model do @@ -70,14 +70,14 @@ unless ENV['DEBUG'] begin - klass.__elasticsearch__.client.transport.logger.level = Logger::WARN + klass.__opensearch__.client.transport.logger.level = Logger::WARN rescue NoMethodError; end begin - klass.__elasticsearch__.client.transport.tracer.level = Logger::WARN + klass.__opensearch__.client.transport.tracer.level = Logger::WARN rescue NoMethodError; end end - total_errors = klass.__elasticsearch__.import force: ENV.fetch('FORCE', false), + total_errors = klass.__opensearch__.import force: ENV.fetch('FORCE', false), batch_size: ENV.fetch('BATCH', 1000).to_i, index: ENV.fetch('INDEX', nil), type: ENV.fetch('TYPE', nil), @@ -95,7 +95,7 @@ desc <<-DESC.gsub(/ /, '') Import all indices from `app/models` (or use DIR environment variable). - $ rake environment elasticsearch:import:all DIR=app/models + $ rake environment opensearch:import:all DIR=app/models DESC task :all do dir = ENV['DIR'].to_s != '' ? ENV['DIR'] : Rails.root.join("app/models") @@ -112,14 +112,14 @@ require(path) ? retry : raise(RuntimeError, "Cannot load class '#{klass}'") end - # Skip if the class doesn't have Elasticsearch integration - next unless klass.respond_to?(:__elasticsearch__) + # Skip if the class doesn't have OpenSearch integration + next unless klass.respond_to?(:__opensearch__) puts "[IMPORT] Processing model: #{klass}..." ENV['CLASS'] = klass.to_s - Rake::Task["elasticsearch:import:model"].invoke - Rake::Task["elasticsearch:import:model"].reenable + Rake::Task["opensearch:import:model"].invoke + Rake::Task["opensearch:import:model"].reenable puts end end diff --git a/elasticsearch-rails/lib/elasticsearch/rails/version.rb b/opensearch-rails/lib/opensearch/rails/version.rb similarity index 94% rename from elasticsearch-rails/lib/elasticsearch/rails/version.rb rename to opensearch-rails/lib/opensearch/rails/version.rb index 07d084dae..90142a6c2 100644 --- a/elasticsearch-rails/lib/elasticsearch/rails/version.rb +++ b/opensearch-rails/lib/opensearch/rails/version.rb @@ -15,8 +15,8 @@ # specific language governing permissions and limitations # under the License. -module Elasticsearch +module OpenSearch module Rails - VERSION = "7.2.1" + VERSION = "1.0.0" end end diff --git a/elasticsearch-rails/lib/rails/templates/01-basic.rb b/opensearch-rails/lib/rails/templates/01-basic.rb similarity index 77% rename from elasticsearch-rails/lib/rails/templates/01-basic.rb rename to opensearch-rails/lib/rails/templates/01-basic.rb index 5e07e14a4..d7555aef6 100644 --- a/elasticsearch-rails/lib/rails/templates/01-basic.rb +++ b/opensearch-rails/lib/rails/templates/01-basic.rb @@ -16,11 +16,11 @@ # under the License. # ===================================================================================================== -# Template for generating a no-frills Rails application with support for Elasticsearch full-text search +# Template for generating a no-frills Rails application with support for OpenSearch full-text search # ===================================================================================================== # -# This file creates a basic, fully working Rails application with support for Elasticsearch full-text -# search via the `elasticsearch-rails` gem; https://github.com/elasticsearch/elasticsearch-rails. +# This file creates a basic, fully working Rails application with support for OpenSearch full-text +# search via the `opensearch-rails` gem; https://github.com/compliance-innovations/opensearch-rails. # # Requirements: # ------------- @@ -32,7 +32,7 @@ # Usage: # ------ # -# $ rails new searchapp --skip --skip-bundle --template https://raw.github.com/elasticsearch/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/01-basic.rb +# $ rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/01-basic.rb # # ===================================================================================================== @@ -40,30 +40,30 @@ require 'net/http' require 'json' -$elasticsearch_url = ENV.fetch('ELASTICSEARCH_URL', 'http://localhost:9200') +$OPENSEARCH_URL = ENV.fetch('OPENSEARCH_URL', 'http://localhost:9200') -# ----- Check for Elasticsearch ------------------------------------------------------------------- +# ----- Check for OpenSearch ------------------------------------------------------------------- -required_elasticsearch_version = '7' +required_opensearch_version = '1' docker_command =<<-CMD.gsub(/\s{1,}/, ' ').strip docker run \ - --name elasticsearch-rails-searchapp \ + --name opensearch-rails-searchapp \ --publish 9200:9200 \ --env "discovery.type=single-node" \ - --env "cluster.name=elasticsearch-rails" \ + --env "cluster.name=opensearch-rails" \ --env "cluster.routing.allocation.disk.threshold_enabled=false" \ --rm \ - docker.elastic.co/elasticsearch/elasticsearch-oss:7.6.0 + opensearchproject/opensearch:1.3.0 CMD begin - cluster_info = Net::HTTP.get(URI.parse($elasticsearch_url)) + cluster_info = Net::HTTP.get(URI.parse($OPENSEARCH_URL)) rescue Errno::ECONNREFUSED => e - say_status "ERROR", "Cannot connect to Elasticsearch on <#{$elasticsearch_url}>\n\n", :red - say_status "", "The application requires an Elasticsearch cluster running, " + - "but no cluster has been found on <#{$elasticsearch_url}>." - say_status "", "The easiest way of launching Elasticsearch is by running it with Docker (https://www.docker.com/get-docker):\n\n" + say_status "ERROR", "Cannot connect to OpenSearch on <#{$OPENSEARCH_URL}>\n\n", :red + say_status "", "The application requires an OpenSearch cluster running, " + + "but no cluster has been found on <#{$OPENSEARCH_URL}>." + say_status "", "The easiest way of launching OpenSearch is by running it with Docker (https://www.docker.com/get-docker):\n\n" say_status "", docker_command + "\n" exit(1) rescue StandardError => e @@ -74,15 +74,15 @@ cluster_info = JSON.parse(cluster_info) unless cluster_info['version'] - say_status "ERROR", "Cannot determine Elasticsearch version from <#{$elasticsearch_url}>", :red + say_status "ERROR", "Cannot determine OpenSearch version from <#{$OPENSEARCH_URL}>", :red say_status "", JSON.dump(cluster_info), :red exit(1) end -if cluster_info['version']['number'] < required_elasticsearch_version +if cluster_info['version']['number'] < required_opensearch_version say_status "ERROR", - "The application requires Elasticsearch version #{required_elasticsearch_version} or higher, found version #{cluster_info['version']['number']}.\n\n", :red - say_status "", "The easiest way of launching Elasticsearch is by running it with Docker (https://www.docker.com/get-docker):\n\n" + "The application requires OpenSearch version #{required_opensearch_version} or higher, found version #{cluster_info['version']['number']}.\n\n", :red + say_status "", "The easiest way of launching OpenSearch is by running it with Docker (https://www.docker.com/get-docker):\n\n" say_status "", docker_command + "\n" exit(1) end @@ -106,13 +106,13 @@ remove_file 'README.md' create_file 'README.md', <<-README -# Ruby on Rails and Elasticsearch: Example application +# Ruby on Rails and OpenSearch: Example application -This application is an example of integrating the {Elasticsearch}[https://www.elastic.co] +This application is an example of integrating the {OpenSearch}[https://opensearch.org/] search engine with the {Ruby On Rails}[http://rubyonrails.org] web framework. It has been generated by application templates available at -https://github.com/elasticsearch/elasticsearch-rails/tree/main/elasticsearch-rails/lib/rails/templates. +https://github.com/compliance-innovations/opensearch-rails/tree/main/opensearch-rails/lib/rails/templates. ## [1] Basic @@ -153,12 +153,12 @@ # ----- Add gems into Gemfile --------------------------------------------------------------------- puts -say_status "Rubygems", "Adding Elasticsearch libraries into Gemfile...\n", :yellow +say_status "Rubygems", "Adding OpenSearch libraries into Gemfile...\n", :yellow puts '-'*80, ''; sleep 0.75 -gem 'elasticsearch' -gem 'elasticsearch-model', git: 'https://github.com/elasticsearch/elasticsearch-rails.git' -gem 'elasticsearch-rails', git: 'https://github.com/elasticsearch/elasticsearch-rails.git' +gem 'opensearch-ruby', '~> 2.0' +gem 'opensearch-model', git: 'https://github.com/compliance-innovations/opensearch-rails.git' +gem 'opensearch-rails', git: 'https://github.com/compliance-innovations/opensearch-rails.git' git add: "Gemfile*" @@ -197,7 +197,7 @@ git add: "." git commit: "-m 'Added the generated Article resource'" -# ----- Add Elasticsearch integration into the model ---------------------------------------------- +# ----- Add OpenSearch integration into the model ---------------------------------------------- puts say_status "Model", "Adding search support into the Article model...", :yellow @@ -206,15 +206,15 @@ run "rm -f app/models/article.rb" file 'app/models/article.rb', <<-CODE class Article < ActiveRecord::Base - include Elasticsearch::Model - include Elasticsearch::Model::Callbacks + include OpenSearch::Model + include OpenSearch::Model::Callbacks #{'attr_accessible :title, :content, :published_on' if Rails::VERSION::STRING < '4'} end CODE -git commit: "-a -m 'Added Elasticsearch support into the Article model'" +git commit: "-a -m 'Added OpenSearch support into the Article model'" -# ----- Add Elasticsearch integration into the interface ------------------------------------------ +# ----- Add OpenSearch integration into the interface ------------------------------------------ puts say_status "Controller", "Adding controller action, route, and HTML for searching...", :yellow @@ -265,8 +265,8 @@ def search setup do @article = articles(:one) - Article.__elasticsearch__.import force: true - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.import force: true + Article.__opensearch__.refresh_index! end CODE @@ -323,7 +323,7 @@ def search end } -run "rails runner 'Article.__elasticsearch__.create_index! force: true'" +run "rails runner 'Article.__opensearch__.create_index! force: true'" rake "db:seed" git add: "db/seeds.rb" diff --git a/elasticsearch-rails/lib/rails/templates/02-pretty.rb b/opensearch-rails/lib/rails/templates/02-pretty.rb similarity index 93% rename from elasticsearch-rails/lib/rails/templates/02-pretty.rb rename to opensearch-rails/lib/rails/templates/02-pretty.rb index fb88e0c47..81bd2d52d 100644 --- a/elasticsearch-rails/lib/rails/templates/02-pretty.rb +++ b/opensearch-rails/lib/rails/templates/02-pretty.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# $ rails new searchapp --skip --skip-bundle --template https://raw.github.com/elasticsearch/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/02-pretty.rb +# $ rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/02-pretty.rb unless File.read('README.md').include? '## [1] Basic' say_status "ERROR", "You have to run the 01-basic.rb template first.", :red @@ -49,7 +49,7 @@ puts '-'*80, ''; sleep 0.25 insert_into_file 'config/application.rb', - "\n\nrequire 'elasticsearch/rails/instrumentation'", + "\n\nrequire 'opensearch/rails/instrumentation'", after: /Bundler\.require.+$/ git add: "config/application.rb" @@ -61,11 +61,11 @@ say_status "Rubygems", "Adding Rubygems into Gemfile...\n", :yellow puts '-'*80, ''; sleep 0.25 -# NOTE: Kaminari has to be loaded before Elasticsearch::Model so the callbacks are executed +# NOTE: Kaminari has to be loaded before OpenSearch::Model so the callbacks are executed # -insert_into_file 'Gemfile', <<-CODE, before: /gem ["']elasticsearch["'].+$/ +insert_into_file 'Gemfile', <<-CODE, before: /gem ["']opensearch-ruby["'].+$/ -# NOTE: Kaminari has to be loaded before Elasticsearch::Model so the callbacks are executed +# NOTE: Kaminari has to be loaded before OpenSearch::Model so the callbacks are executed gem 'kaminari' CODE @@ -81,11 +81,11 @@ say_status "Model", "Adding a `Article.search` class method...\n", :yellow puts '-'*80, ''; sleep 0.5 -insert_into_file 'app/models/article.rb', <<-CODE, after: 'include Elasticsearch::Model::Callbacks' +insert_into_file 'app/models/article.rb', <<-CODE, after: 'include OpenSearch::Model::Callbacks' def self.search(query) - __elasticsearch__.search( + __opensearch__.search( { query: { multi_match: { @@ -109,15 +109,15 @@ def self.search(query) insert_into_file "#{Rails::VERSION::STRING > '4' ? 'test/models' : 'test/unit' }/article_test.rb", <<-CODE, after: /class ArticleTest < ActiveSupport::TestCase$/ teardown do - Article.__elasticsearch__.unstub(:search) + Article.__opensearch__.unstub(:search) end CODE gsub_file "#{Rails::VERSION::STRING > '4' ? 'test/models' : 'test/unit' }/article_test.rb", %r{# test "the truth" do.*?# end}m, <<-CODE - test "has a search method delegating to __elasticsearch__" do - Article.__elasticsearch__.expects(:search).with do |definition| + test "has a search method delegating to __opensearch__" do + Article.__opensearch__.expects(:search).with do |definition| assert_equal 'foo', definition[:query][:multi_match][:query] true end @@ -314,7 +314,7 @@ def self.search(query) say_status "Database", "Creating 1,000 articles...", :yellow puts '-'*80, ''; -run "rails runner 'Article.__elasticsearch__.create_index! force: true'" +run "rails runner 'Article.__opensearch__.create_index! force: true'" rake "db:seed COUNT=1_000" # ----- Print Git log ----------------------------------------------------------------------------- diff --git a/elasticsearch-rails/lib/rails/templates/03-expert.rb b/opensearch-rails/lib/rails/templates/03-expert.rb similarity index 80% rename from elasticsearch-rails/lib/rails/templates/03-expert.rb rename to opensearch-rails/lib/rails/templates/03-expert.rb index 5715eb0d6..1f9d35c47 100644 --- a/elasticsearch-rails/lib/rails/templates/03-expert.rb +++ b/opensearch-rails/lib/rails/templates/03-expert.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# $ rails new searchapp --skip --skip-bundle --template https://raw.github.com/elasticsearch/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/03-expert.rb +# $ rails new searchapp --skip --skip-bundle --template https://raw.github.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/03-expert.rb unless File.read('README.md').include? '## [2] Pretty' say_status "ERROR", "You have to run the 01-basic.rb and 02-pretty.rb templates first.", :red @@ -46,13 +46,13 @@ The `expert` template changes to a complex database schema with model relationships: article belongs to a category, has many authors and comments. -* The Elasticsearch integration is refactored into the `Searchable` concern +* The OpenSearch integration is refactored into the `Searchable` concern * A complex mapping for the index is defined * A custom serialization is defined in `Article#as_indexed_json` * The `search` method is amended with facets and suggestions * A [Sidekiq](http://sidekiq.org) worker for handling index updates in background is added * A custom `SearchController` with associated view is added -* A Rails initializer is added to customize the Elasticsearch client configuration +* A Rails initializer is added to customize the OpenSearch client configuration * Seed script and example data from New York Times is added README @@ -181,7 +181,7 @@ class Article < ActiveRecord::Base gsub_file "test/models/article_test.rb", %r{assert_equal 'foo', definition\[:query\]\[:multi_match\]\[:query\]}, "assert_equal 'foo', definition.to_hash[:query][:bool][:should][0][:multi_match][:query]" # copy_file File.expand_path('../searchable.rb', __FILE__), 'app/models/concerns/searchable.rb' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/searchable.rb', 'app/models/concerns/searchable.rb' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/searchable.rb', 'app/models/concerns/searchable.rb' insert_into_file "app/models/article.rb", after: "ActiveRecord::Base" do <<-CODE @@ -196,7 +196,7 @@ class Article < ActiveRecord::Base end git add: "app/models/ test/models" -git commit: "-m 'Refactored the Elasticsearch integration into a concern\n\nSee:\n\n* http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns\n* http://joshsymonds.com/blog/2012/10/25/rails-concerns-v-searchable-with-elasticsearch/'" +git commit: "-m 'Refactored the OpenSearch integration into a concern\n\nSee:\n\n* http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns\n* http://joshsymonds.com/blog/2012/10/25/rails-concerns-v-searchable-with-elasticsearch/'" # ----- Add Sidekiq indexer ----------------------------------------------------------------------- @@ -209,14 +209,14 @@ class Article < ActiveRecord::Base run "bundle install" # copy_file File.expand_path('../indexer.rb', __FILE__), 'app/workers/indexer.rb' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/indexer.rb', 'app/workers/indexer.rb' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/indexer.rb', 'app/workers/indexer.rb' insert_into_file "test/test_helper.rb", "require 'sidekiq/testing'\n\n", before: "class ActiveSupport::TestCase\n" git add: "Gemfile* app/workers/ test/test_helper.rb" -git commit: "-m 'Added a Sidekiq indexer\n\nRun:\n\n $ bundle exec sidekiq --queue elasticsearch --verbose\n\nSee http://sidekiq.org'" +git commit: "-m 'Added a Sidekiq indexer\n\nRun:\n\n $ bundle exec sidekiq --queue opensearch --verbose\n\nSee http://sidekiq.org'" # ----- Add SearchController ----------------------------------------------------------------------- @@ -244,16 +244,16 @@ def index end # copy_file File.expand_path('../search_controller_test.rb', __FILE__), 'test/controllers/search_controller_test.rb' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/search_controller_test.rb', 'test/controllers/search_controller_test.rb' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/search_controller_test.rb', 'test/controllers/search_controller_test.rb' route "get '/search', to: 'search#index', as: 'search'" gsub_file 'config/routes.rb', %r{root to: 'articles#index'$}, "root to: 'search#index'" # copy_file File.expand_path('../index.html.erb', __FILE__), 'app/views/search/index.html.erb' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/index.html.erb', 'app/views/search/index.html.erb' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/index.html.erb', 'app/views/search/index.html.erb' # copy_file File.expand_path('../search.css', __FILE__), 'app/assets/stylesheets/search.css' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/search.css', 'app/assets/stylesheets/search.css' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/search.css', 'app/assets/stylesheets/search.css' git add: "app/controllers/ test/controllers/ config/routes.rb" git add: "app/views/search/ app/assets/stylesheets/search.css" @@ -274,55 +274,55 @@ def index # ----- Add initializer --------------------------------------------------------------------------- puts -say_status "Application", "Adding Elasticsearch configuration in an initializer...\n", :yellow +say_status "Application", "Adding OpenSearch configuration in an initializer...\n", :yellow puts '-'*80, ''; sleep 0.5 -create_file 'config/initializers/elasticsearch.rb', <<-CODE -# Connect to specific Elasticsearch cluster -ELASTICSEARCH_URL = ENV['ELASTICSEARCH_URL'] || 'http://localhost:9200' +create_file 'config/initializers/opensearch.rb', <<-CODE +# Connect to specific OpenSearch cluster +OPENSEARCH_URL = ENV['OPENSEARCH_URL'] || 'http://localhost:9200' -Elasticsearch::Model.client = Elasticsearch::Client.new host: ELASTICSEARCH_URL +OpenSearch::Model.client = OpenSearch::Client.new host: OPENSEARCH_URL # Print Curl-formatted traces in development into a file # if Rails.env.development? - tracer = ActiveSupport::Logger.new('log/elasticsearch.log') + tracer = ActiveSupport::Logger.new('log/opensearch.log') tracer.level = Logger::DEBUG - Elasticsearch::Model.client.transport.tracer = tracer + OpenSearch::Model.client.transport.tracer = tracer end CODE git add: "config/initializers" -git commit: "-m 'Added Rails initializer with Elasticsearch configuration'" +git commit: "-m 'Added Rails initializer with OpenSearch configuration'" # ----- Add Rake tasks ---------------------------------------------------------------------------- puts -say_status "Application", "Adding Elasticsearch Rake tasks...\n", :yellow +say_status "Application", "Adding OpenSearch Rake tasks...\n", :yellow puts '-'*80, ''; sleep 0.5 -create_file 'lib/tasks/elasticsearch.rake', <<-CODE -require 'elasticsearch/rails/tasks/import' +create_file 'lib/tasks/opensearch.rake', <<-CODE +require 'opensearch/rails/tasks/import' CODE git add: "lib/tasks" -git commit: "-m 'Added Rake tasks for Elasticsearch'" +git commit: "-m 'Added Rake tasks for OpenSearch'" # ----- Insert and index data --------------------------------------------------------------------- puts -say_status "Database", "Re-creating the database with data and importing into Elasticsearch...", :yellow +say_status "Database", "Re-creating the database with data and importing into OpenSearch...", :yellow puts '-'*80, ''; sleep 0.25 # copy_file File.expand_path('../articles.yml.gz', __FILE__), 'db/articles.yml.gz' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/articles.yml.gz', 'db/articles.yml.gz' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/articles.yml.gz', 'db/articles.yml.gz' remove_file 'db/seeds.rb' # copy_file File.expand_path('../seeds.rb', __FILE__), 'db/seeds.rb' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/seeds.rb', 'db/seeds.rb' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/seeds.rb', 'db/seeds.rb' rake "db:reset" -rake "environment elasticsearch:import:model CLASS='Article' BATCH=100 FORCE=y" +rake "environment opensearch:import:model CLASS='Article' BATCH=100 FORCE=y" git add: "db/seeds.rb db/articles.yml.gz" git commit: "-m 'Added a seed script and source data'" diff --git a/elasticsearch-rails/lib/rails/templates/04-dsl.rb b/opensearch-rails/lib/rails/templates/04-dsl.rb similarity index 88% rename from elasticsearch-rails/lib/rails/templates/04-dsl.rb rename to opensearch-rails/lib/rails/templates/04-dsl.rb index d4bd598a0..b6007339b 100644 --- a/elasticsearch-rails/lib/rails/templates/04-dsl.rb +++ b/opensearch-rails/lib/rails/templates/04-dsl.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# $ rails new searchapp --skip --skip-bundle --template https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/04-dsl.rb +# $ rails new searchapp --skip --skip-bundle --template https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/04-dsl.rb unless File.read('README.md').include? '## [3] Expert' say_status "ERROR", "You have to run the 01-basic.rb, 02-pretty.rb and 03-expert.rb templates first.", :red @@ -27,7 +27,7 @@ ## [4] DSL The `dsl` template refactors the search definition in SearchController#index -to use the [`elasticsearch-dsl`](https://github.com/elastic/elasticsearch-ruby/tree/dsl/elasticsearch-dsl) +to use the [`opensearch-dsl`](https://github.com/opensearch-project/opensearch-ruby/tree/main/opensearch-dsl) Rubygem for better expresivity and readability of the code. README @@ -44,10 +44,10 @@ say_status "Rubygems", "Adding Rubygems into Gemfile...\n", :yellow puts '-'*80, ''; sleep 0.25 -gem "elasticsearch-dsl", git: "git://github.com/elastic/elasticsearch-ruby.git" +gem "opensearch-dsl", git: "git://github.com/opensearch-project/opensearch-ruby.git" git add: "Gemfile*" -git commit: "-m 'Added the `elasticsearch-dsl` gem'" +git commit: "-m 'Added the `opensearch-dsl` gem'" # ----- Run bundle install ------------------------------------------------------------------------ @@ -56,10 +56,10 @@ # ----- Change the search definition implementation and associated views and tests ---------------- # copy_file File.expand_path('../searchable.dsl.rb', __FILE__), 'app/models/concerns/searchable.rb', force: true -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/searchable.dsl.rb', 'app/models/concerns/searchable.rb', force: true +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/searchable.dsl.rb', 'app/models/concerns/searchable.rb', force: true # copy_file File.expand_path('../index.html.dsl.erb', __FILE__), 'app/views/search/index.html.erb', force: true -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/index.html.dsl.erb', 'app/views/search/index.html.erb', force: true +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/index.html.dsl.erb', 'app/views/search/index.html.erb', force: true gsub_file "test/controllers/search_controller_test.rb", %r{test "should return facets" do.*?end}m, <<-CODE test "should return aggregations" do diff --git a/elasticsearch-rails/lib/rails/templates/05-settings-files.rb b/opensearch-rails/lib/rails/templates/05-settings-files.rb similarity index 82% rename from elasticsearch-rails/lib/rails/templates/05-settings-files.rb rename to opensearch-rails/lib/rails/templates/05-settings-files.rb index 989895445..f12ce0e77 100644 --- a/elasticsearch-rails/lib/rails/templates/05-settings-files.rb +++ b/opensearch-rails/lib/rails/templates/05-settings-files.rb @@ -15,7 +15,7 @@ # specific language governing permissions and limitations # under the License. -# $ rails new searchapp --skip --skip-bundle --template https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/05-settings-files.rb +# $ rails new searchapp --skip --skip-bundle --template https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/05-settings-files.rb # (See: 01-basic.rb, 02-pretty.rb, 03-expert.rb, 04-dsl.rb) @@ -31,22 +31,22 @@ git add: "README.md" git commit: "-m '[05] Updated the application README'" -# ----- Setup the Searchable module to load settings from config/elasticsearch/articles_settings.json +# ----- Setup the Searchable module to load settings from config/opensearch/articles_settings.json gsub_file "app/models/concerns/searchable.rb", /index: { number_of_shards: 1, number_of_replicas: 0 }/, - "File.open('config/elasticsearch/articles_settings.json')" + "File.open('config/opensearch/articles_settings.json')" git add: "app/models/concerns/searchable.rb" git commit: "-m 'Setup the Searchable module to load settings from file'" # ----- Copy the articles_settings.json file ------------------------------------------------------- -# copy_file File.expand_path('../articles_settings.json', __FILE__), 'config/elasticsearch/articles_settings.json' -get 'https://raw.githubusercontent.com/elastic/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/articles_settings.json', - 'config/elasticsearch/articles_settings.json', force: true +# copy_file File.expand_path('../articles_settings.json', __FILE__), 'config/opensearch/articles_settings.json' +get 'https://raw.githubusercontent.com/compliance-innovations/opensearch-rails/main/opensearch-rails/lib/rails/templates/articles_settings.json', + 'config/opensearch/articles_settings.json', force: true -git add: "config/elasticsearch/articles_settings.json" +git add: "config/opensearch/articles_settings.json" git commit: "-m 'Create the articles settings file'" # ----- Run bundle install ------------------------------------------------------------------------ @@ -55,7 +55,7 @@ # ----- Recreate the index ------------------------------------------------------------------------ -rake "environment elasticsearch:import:model CLASS='Article' BATCH=100 FORCE=y" +rake "environment opensearch:import:model CLASS='Article' BATCH=100 FORCE=y" # ----- Print Git log ----------------------------------------------------------------------------- diff --git a/elasticsearch-rails/lib/rails/templates/articles.yml.gz b/opensearch-rails/lib/rails/templates/articles.yml.gz similarity index 100% rename from elasticsearch-rails/lib/rails/templates/articles.yml.gz rename to opensearch-rails/lib/rails/templates/articles.yml.gz diff --git a/elasticsearch-rails/lib/rails/templates/articles_settings.json b/opensearch-rails/lib/rails/templates/articles_settings.json similarity index 100% rename from elasticsearch-rails/lib/rails/templates/articles_settings.json rename to opensearch-rails/lib/rails/templates/articles_settings.json diff --git a/elasticsearch-rails/lib/rails/templates/index.html.dsl.erb b/opensearch-rails/lib/rails/templates/index.html.dsl.erb similarity index 100% rename from elasticsearch-rails/lib/rails/templates/index.html.dsl.erb rename to opensearch-rails/lib/rails/templates/index.html.dsl.erb diff --git a/elasticsearch-rails/lib/rails/templates/index.html.erb b/opensearch-rails/lib/rails/templates/index.html.erb similarity index 100% rename from elasticsearch-rails/lib/rails/templates/index.html.erb rename to opensearch-rails/lib/rails/templates/index.html.erb diff --git a/elasticsearch-rails/lib/rails/templates/indexer.rb b/opensearch-rails/lib/rails/templates/indexer.rb similarity index 79% rename from elasticsearch-rails/lib/rails/templates/indexer.rb rename to opensearch-rails/lib/rails/templates/indexer.rb index 1ea1d9b6c..ddaf10b12 100644 --- a/elasticsearch-rails/lib/rails/templates/indexer.rb +++ b/opensearch-rails/lib/rails/templates/indexer.rb @@ -19,14 +19,14 @@ # # Run me with: # -# $ bundle exec sidekiq --queue elasticsearch --verbose +# $ bundle exec sidekiq --queue opensearch --verbose # class Indexer include Sidekiq::Worker - sidekiq_options queue: 'elasticsearch', retry: false, backtrace: true + sidekiq_options queue: 'opensearch', retry: false, backtrace: true Logger = Sidekiq.logger.level == Logger::DEBUG ? Sidekiq.logger : nil - Client = Elasticsearch::Client.new host: (ENV['ELASTICSEARCH_URL'] || 'http://localhost:9200'), logger: Logger + Client = OpenSearch::Client.new host: (ENV['OPENSEARCH_URL'] || 'http://localhost:9200'), logger: Logger def perform(operation, klass, record_id, options={}) logger.debug [operation, "#{klass}##{record_id} #{options.inspect}"] @@ -34,8 +34,8 @@ def perform(operation, klass, record_id, options={}) case operation.to_s when /index|update/ record = klass.constantize.find(record_id) - record.__elasticsearch__.client = Client - record.__elasticsearch__.__send__ "#{operation}_document" + record.__opensearch__.client = Client + record.__opensearch__.__send__ "#{operation}_document" when /delete/ Client.delete index: klass.constantize.index_name, type: klass.constantize.document_type, id: record_id else raise ArgumentError, "Unknown operation '#{operation}'" diff --git a/elasticsearch-rails/lib/rails/templates/search.css b/opensearch-rails/lib/rails/templates/search.css similarity index 100% rename from elasticsearch-rails/lib/rails/templates/search.css rename to opensearch-rails/lib/rails/templates/search.css diff --git a/elasticsearch-rails/lib/rails/templates/search_controller_test.dsl.rb b/opensearch-rails/lib/rails/templates/search_controller_test.dsl.rb similarity index 97% rename from elasticsearch-rails/lib/rails/templates/search_controller_test.dsl.rb rename to opensearch-rails/lib/rails/templates/search_controller_test.dsl.rb index fd10ad9e1..8ec93da86 100644 --- a/elasticsearch-rails/lib/rails/templates/search_controller_test.dsl.rb +++ b/opensearch-rails/lib/rails/templates/search_controller_test.dsl.rb @@ -48,10 +48,10 @@ class SearchControllerTest < ActionController::TestCase Article.find_by_title('Article Three').comments.create body: 'One' - Sidekiq::Queue.new("elasticsearch").clear + Sidekiq::Queue.new("opensearch").clear - Article.__elasticsearch__.import force: true - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.import force: true + Article.__opensearch__.refresh_index! end test "should return search results" do diff --git a/elasticsearch-rails/lib/rails/templates/search_controller_test.rb b/opensearch-rails/lib/rails/templates/search_controller_test.rb similarity index 98% rename from elasticsearch-rails/lib/rails/templates/search_controller_test.rb rename to opensearch-rails/lib/rails/templates/search_controller_test.rb index d627ae528..d597d4a1a 100644 --- a/elasticsearch-rails/lib/rails/templates/search_controller_test.rb +++ b/opensearch-rails/lib/rails/templates/search_controller_test.rb @@ -49,8 +49,8 @@ class SearchControllerTest < ActionController::TestCase Sidekiq::Worker.clear_all - Article.__elasticsearch__.import force: true - Article.__elasticsearch__.refresh_index! + Article.__opensearch__.import force: true + Article.__opensearch__.refresh_index! end test "should return search results" do diff --git a/elasticsearch-rails/lib/rails/templates/searchable.dsl.rb b/opensearch-rails/lib/rails/templates/searchable.dsl.rb similarity index 94% rename from elasticsearch-rails/lib/rails/templates/searchable.dsl.rb rename to opensearch-rails/lib/rails/templates/searchable.dsl.rb index a0efeb997..eb44f4661 100644 --- a/elasticsearch-rails/lib/rails/templates/searchable.dsl.rb +++ b/opensearch-rails/lib/rails/templates/searchable.dsl.rb @@ -19,7 +19,7 @@ module Searchable extend ActiveSupport::Concern included do - include Elasticsearch::Model + include OpenSearch::Model # Customize the index name # @@ -70,7 +70,7 @@ module Searchable after_commit lambda { Indexer.perform_async(:delete, self.class.to_s, self.id) }, on: :destroy after_touch lambda { Indexer.perform_async(:update, self.class.to_s, self.id) } - # Customize the JSON serialization for Elasticsearch + # Customize the JSON serialization for OpenSearch # def as_indexed_json(options={}) hash = self.as_json( @@ -85,10 +85,10 @@ def as_indexed_json(options={}) # and implement a "cross" faceted navigation # # @param q [String] The user query - # @return [Elasticsearch::Model::Response::Response] + # @return [OpenSearch::Model::Response::Response] # def self.search(q, options={}) - @search_definition = Elasticsearch::DSL::Search.search do + @search_definition = OpenSearch::DSL::Search.search do query do # If a user query is present... @@ -146,7 +146,7 @@ def self.search(q, options={}) aggregation :categories do # Filter the aggregation with any selected `author` and `published_week` # - f = Elasticsearch::DSL::Search::Filters::Bool.new + f = OpenSearch::DSL::Search::Filters::Bool.new f.must { match_all } f.must { term 'authors.full_name.raw' => options[:author] } if options[:author] f.must { range published_on: { gte: options[:published_week], lte: "#{options[:published_week]}||+1w" } } if options[:published_week] @@ -163,7 +163,7 @@ def self.search(q, options={}) aggregation :authors do # Filter the aggregation with any selected `category` and `published_week` # - f = Elasticsearch::DSL::Search::Filters::Bool.new + f = OpenSearch::DSL::Search::Filters::Bool.new f.must { match_all } f.must { term categories: options[:category] } if options[:category] f.must { range published_on: { gte: options[:published_week], lte: "#{options[:published_week]}||+1w" } } if options[:published_week] @@ -180,7 +180,7 @@ def self.search(q, options={}) aggregation :published do # Filter the aggregation with any selected `author` and `category` # - f = Elasticsearch::DSL::Search::Filters::Bool.new + f = OpenSearch::DSL::Search::Filters::Bool.new f.must { match_all } f.must { term 'authors.full_name.raw' => options[:author] } if options[:author] f.must { term categories: options[:category] } if options[:category] @@ -228,7 +228,7 @@ def self.search(q, options={}) end end - __elasticsearch__.search(@search_definition) + __opensearch__.search(@search_definition) end end end diff --git a/elasticsearch-rails/lib/rails/templates/searchable.rb b/opensearch-rails/lib/rails/templates/searchable.rb similarity index 97% rename from elasticsearch-rails/lib/rails/templates/searchable.rb rename to opensearch-rails/lib/rails/templates/searchable.rb index cf7e4e800..6317702b3 100644 --- a/elasticsearch-rails/lib/rails/templates/searchable.rb +++ b/opensearch-rails/lib/rails/templates/searchable.rb @@ -19,7 +19,7 @@ module Searchable extend ActiveSupport::Concern included do - include Elasticsearch::Model + include OpenSearch::Model # Customize the index name # @@ -70,7 +70,7 @@ module Searchable after_commit lambda { Indexer.perform_async(:delete, self.class.to_s, self.id) }, on: :destroy after_touch lambda { Indexer.perform_async(:update, self.class.to_s, self.id) } - # Customize the JSON serialization for Elasticsearch + # Customize the JSON serialization for OpenSearch # def as_indexed_json(options={}) hash = self.as_json( @@ -84,7 +84,7 @@ def as_indexed_json(options={}) # Search in title and content fields for `query`, include highlights in response # # @param query [String] The user query - # @return [Elasticsearch::Model::Response::Response] + # @return [OpenSearch::Model::Response::Response] # def self.search(query, options={}) @@ -218,7 +218,7 @@ def self.search(query, options={}) } end - __elasticsearch__.search(@search_definition) + __opensearch__.search(@search_definition) end end end diff --git a/elasticsearch-rails/lib/rails/templates/seeds.rb b/opensearch-rails/lib/rails/templates/seeds.rb similarity index 86% rename from elasticsearch-rails/lib/rails/templates/seeds.rb rename to opensearch-rails/lib/rails/templates/seeds.rb index 7b7294d2d..44b569f50 100644 --- a/elasticsearch-rails/lib/rails/templates/seeds.rb +++ b/opensearch-rails/lib/rails/templates/seeds.rb @@ -20,7 +20,7 @@ Zlib::GzipReader.open(File.expand_path('../articles.yml.gz', __FILE__)) do |gzip| puts "Reading articles from gzipped YAML..." - @documents = YAML.respond_to?(:load_documents) ? YAML.load_documents(gzip.read) : + @documents = YAML.respond_to?(:load_documents) ? YAML.load_documents(gzip.read) : YAML.load_stream(gzip.read) end @@ -36,9 +36,9 @@ end end -# Reduce verbosity and truncate the request body of Elasticsearch logger -Article.__elasticsearch__.client.transport.tracer.level = Logger::INFO -Article.__elasticsearch__.client.transport.tracer.formatter = lambda do |s, d, p, message| +# Reduce verbosity and truncate the request body of OpenSearch logger +Article.__opensearch__.client.transport.tracer.level = Logger::INFO +Article.__opensearch__.client.transport.tracer.formatter = lambda do |s, d, p, message| "\n\n" + (message.size > 105 ? message[0..105].concat("...}'") : message) + "\n\n" end @@ -69,7 +69,7 @@ article.save! end -# Remove any jobs from the "elasticsearch" Sidekiq queue +# Remove any jobs from the "opensearch" Sidekiq queue # require 'sidekiq/api' -Sidekiq::Queue.new("elasticsearch").clear +Sidekiq::Queue.new("opensearch").clear diff --git a/elasticsearch-rails/elasticsearch-rails.gemspec b/opensearch-rails/opensearch-rails.gemspec similarity index 71% rename from elasticsearch-rails/elasticsearch-rails.gemspec rename to opensearch-rails/opensearch-rails.gemspec index 9b2b34781..0f0fe7367 100644 --- a/elasticsearch-rails/elasticsearch-rails.gemspec +++ b/opensearch-rails/opensearch-rails.gemspec @@ -18,22 +18,22 @@ # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'elasticsearch/rails/version' +require 'opensearch/rails/version' Gem::Specification.new do |s| - s.name = 'elasticsearch-rails' - s.version = Elasticsearch::Rails::VERSION - s.authors = ['Karel Minarik'] - s.email = ['karel.minarik@elasticsearch.org'] - s.description = 'Ruby on Rails integrations for Elasticsearch.' - s.summary = 'Ruby on Rails integrations for Elasticsearch.' - s.homepage = 'https://github.com/elasticsearch/elasticsearch-rails/' + s.name = 'opensearch-rails' + s.version = OpenSearch::Rails::VERSION + s.authors = ['CDD Solutions B.V.'] + s.email = ['developers@compliance-innovations.com'] + s.description = 'Ruby on Rails integrations for OpenSearch.' + s.summary = 'Ruby on Rails integrations for OpenSearch.' + s.homepage = 'https://github.com/compliance-innovations/opensearch-rails/' s.license = 'Apache 2' s.metadata = { 'homepage_uri' => 'https://www.elastic.co/guide/en/elasticsearch/client/ruby-api/current/ruby_on_rails.html', - 'changelog_uri' => 'https://github.com/elastic/elasticsearch-rails/blob/main/CHANGELOG.md', - 'source_code_uri' => 'https://github.com/elastic/elasticsearch-rails/', - 'bug_tracker_uri' => 'https://github.com/elastic/elasticsearch-rails/issues' + 'changelog_uri' => 'https://github.com/compliance-innovations/opensearch-rails/blob/main/CHANGELOG.md', + 'source_code_uri' => 'https://github.com/compliance-innovations/opensearch-rails/', + 'bug_tracker_uri' => 'https://github.com/compliance-innovations/opensearch-rails/issues' } s.files = `git ls-files`.split($/) @@ -44,7 +44,7 @@ Gem::Specification.new do |s| s.extra_rdoc_files = ['README.md', 'LICENSE.txt'] s.rdoc_options = ['--charset=UTF-8'] - s.required_ruby_version = '>= 2.4' + s.required_ruby_version = '>= 2.5' s.add_development_dependency 'bundler' s.add_development_dependency 'cane' @@ -52,7 +52,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'minitest' s.add_development_dependency 'mocha' s.add_development_dependency 'pry' - s.add_development_dependency 'rails', '> 3.1' + s.add_development_dependency 'rails', '> 6.1' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency 'require-prof' s.add_development_dependency 'shoulda-context' diff --git a/elasticsearch-rails/spec/instrumentation_spec.rb b/opensearch-rails/spec/instrumentation_spec.rb similarity index 88% rename from elasticsearch-rails/spec/instrumentation_spec.rb rename to opensearch-rails/spec/instrumentation_spec.rb index 3fcbc5916..39c2ade1e 100644 --- a/elasticsearch-rails/spec/instrumentation_spec.rb +++ b/opensearch-rails/spec/instrumentation_spec.rb @@ -21,7 +21,7 @@ before(:all) do class DummyInstrumentationModel - extend Elasticsearch::Model::Searching::ClassMethods + extend OpenSearch::Model::Searching::ClassMethods def self.index_name; 'foo'; end def self.document_type; 'bar'; end @@ -40,7 +40,7 @@ def self.document_type; 'bar'; end end let(:search) do - Elasticsearch::Model::Searching::SearchRequest.new(DummyInstrumentationModel, 'foo') + OpenSearch::Model::Searching::SearchRequest.new(DummyInstrumentationModel, 'foo') end let(:client) do @@ -49,7 +49,7 @@ def self.document_type; 'bar'; end before do allow(DummyInstrumentationModel).to receive(:client).and_return(client) - Elasticsearch::Rails::Instrumentation::Railtie.run_initializers + OpenSearch::Rails::Instrumentation::Railtie.run_initializers end context 'SearchRequest#execute!' do @@ -63,12 +63,11 @@ def self.document_type; 'bar'; end context 'Model#search' do before do - expect(ActiveSupport::Notifications).to receive(:instrument).with('search.elasticsearch', + expect(ActiveSupport::Notifications).to receive(:instrument).with('search.opensearch', { klass: 'DummyInstrumentationModel', name: 'Search', search: { body: query, - index: 'foo', - type: 'bar' } }).and_return({}) + index: 'foo'} }).and_return({}) end let(:query) do diff --git a/elasticsearch-rails/spec/lograge_spec.rb b/opensearch-rails/spec/lograge_spec.rb similarity index 88% rename from elasticsearch-rails/spec/lograge_spec.rb rename to opensearch-rails/spec/lograge_spec.rb index 980aa9f1b..e2eee69e4 100644 --- a/elasticsearch-rails/spec/lograge_spec.rb +++ b/opensearch-rails/spec/lograge_spec.rb @@ -35,17 +35,17 @@ require 'spec_helper' require 'action_pack' require 'lograge' -require 'elasticsearch/rails/lograge' +require 'opensearch/rails/lograge' describe 'ActiveSupport::Instrumentation integration' do before do - Elasticsearch::Rails::Lograge::Railtie.run_initializers + OpenSearch::Rails::Lograge::Railtie.run_initializers end it 'customizes the Lograge configuration' do - expect(Elasticsearch::Rails::Lograge::Railtie.initializers - .select { |i| i.name == 'elasticsearch.lograge' } + expect(OpenSearch::Rails::Lograge::Railtie.initializers + .select { |i| i.name == 'opensearch.lograge' } .first).not_to be_nil end end diff --git a/elasticsearch-rails/spec/spec_helper.rb b/opensearch-rails/spec/spec_helper.rb similarity index 81% rename from elasticsearch-rails/spec/spec_helper.rb rename to opensearch-rails/spec/spec_helper.rb index e0a299964..d6d94ad6b 100644 --- a/elasticsearch-rails/spec/spec_helper.rb +++ b/opensearch-rails/spec/spec_helper.rb @@ -17,14 +17,14 @@ require 'pry-nav' require 'active_record' -require 'elasticsearch/model' -require 'elasticsearch/rails' +require 'opensearch/model' +require 'opensearch/rails' require 'rails/railtie' -require 'elasticsearch/rails/instrumentation' +require 'opensearch/rails/instrumentation' -unless defined?(ELASTICSEARCH_URL) - ELASTICSEARCH_URL = ENV['ELASTICSEARCH_URL'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" +unless defined?(OPENSEARCH_URL) + OPENSEARCH_URL = ENV['OPENSEARCH_URL'] || "localhost:#{(ENV['TEST_CLUSTER_PORT'] || 9200)}" end RSpec.configure do |config| @@ -35,9 +35,9 @@ require 'ansi' tracer = ::Logger.new(STDERR) tracer.formatter = lambda { |s, d, p, m| "#{m.gsub(/^.*$/) { |n| ' ' + n }.ansi(:faint)}\n" } - Elasticsearch::Model.client = Elasticsearch::Client.new host: ELASTICSEARCH_URL, + OpenSearch::Model.client = OpenSearch::Client.new host: OPENSEARCH_URL, tracer: (ENV['QUIET'] ? nil : tracer) - puts "Elasticsearch Version: #{Elasticsearch::Model.client.info['version']}" + puts "OpenSearch Version: #{OpenSearch::Model.client.info['version']}" unless ActiveRecord::Base.connected? ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => ":memory:" )