{"id":13484547,"url":"https://github.com/printercu/elastics-rb","last_synced_at":"2025-05-09T01:43:21.741Z","repository":{"id":18981168,"uuid":"22202469","full_name":"printercu/elastics-rb","owner":"printercu","description":"Simple ElasticSearch client for ruby with AR integration","archived":false,"fork":false,"pushed_at":"2017-01-19T09:24:08.000Z","size":73,"stargazers_count":101,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-31T20:44:11.906Z","etag":null,"topics":["elasticsearch","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/printercu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-07-24T06:56:18.000Z","updated_at":"2023-10-22T15:27:35.000Z","dependencies_parsed_at":"2022-07-20T23:28:13.063Z","dependency_job_id":null,"html_url":"https://github.com/printercu/elastics-rb","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/printercu%2Felastics-rb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/printercu%2Felastics-rb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/printercu%2Felastics-rb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/printercu%2Felastics-rb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/printercu","download_url":"https://codeload.github.com/printercu/elastics-rb/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253176439,"owners_count":21866141,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["elasticsearch","ruby"],"created_at":"2024-07-31T17:01:25.971Z","updated_at":"2025-05-09T01:43:21.680Z","avatar_url":"https://github.com/printercu.png","language":"Ruby","readme":"# elastics\n[![Gem Version](https://badge.fury.io/rb/elastics.svg)](http://badge.fury.io/rb/elastics)\n[![Code Climate](https://codeclimate.com/github/printercu/elastics-rb/badges/gpa.svg)](https://codeclimate.com/github/printercu/elastics-rb)\n[![Build Status](https://travis-ci.org/printercu/elastics-rb.svg)](https://travis-ci.org/printercu/elastics-rb)\n\nSimple ElasticSearch client. Everything for deployment \u0026 maintaince included.\n- Basic API only\n- Transparent aliases management \u0026 zero-downtime migrations\n- Capistrano integration\n- Auto refresh in tests\n- Instrumentation\n\nFast and thread-safe [httpclient](https://github.com/nahi/httpclient) is under the hood.\n\n## Install\n\n```ruby\n# Gemfile\ngem 'elastics', '~\u003e 0.3' # use version from the badge above\n# or\ngem 'elastics', github: 'printercu/elastics-rb'\n```\n\n## Usage\n\n### Plain\n\n```ruby\n# initialize client with\nclient = Elastics::Client.new(options)\n# options is hash with\n#   :host   - hostname with port or array with hosts (default 127.0.0.1:9200)\n#   :index  - (default index)\n#   :type   - (default type)\n\n# basic request\nclient.request(params)\n# params is hash with\n#   :method - default :get\n#   :body   - post body\n#   :query  - query string params\n#   :index, :type, :id - query path params to override defaults\n\n# method shortcuts for #put, #post #delete\nclient.delete(params)\n\n# getter/setter shortcuts\nclient.set(id, data)\nclient.get(id)\nclient.get(params) # as usual\n\n# other shortcuts (set method \u0026 id)\nclient.put_mapping(index: index, type: type, body: mapping)\nclient.search(params)\nclient.index(params) # PUT if :id is set, otherwise POST\n\n# utils\nclient.index_exists?(name)\n\n# bulk\nclient.bulk(params) do |bulk|\n  # if first param is not a Hash it's converted to {_id: param}\n  bulk.index override_params, data\n  bulk.create id, data\n  bulk.update id, script\n  bulk.update_doc id, fields\n  bulk.delete id\nend\n```\n\n### Models\nMost of ActiveRecord integration functionality is available for plain ruby.\n\n```ruby\nclass User\n  include Elastics::Model\n\n  # set connection config, check 'configure section' for available options\n  self.elastics_config = {host: 'hostname:port'}\n  # set index base and version manager will manage aliases\n  self.elastics_index_base = 'user'\n  self.elastics_type_name = 'user'\nend\n```\nCheck out available [HelperMethods](https://github.com/printercu/elastics-rb/blob/master/lib/elastics/model/helper_methods.rb).\n\n### ActiveRecord\n\n```ruby\nclass User \u003c ActiveRecord::Base\n  indexed_with_elastics\n  # it'll set after_commit callbacks and add helper methods\n  # optionally pass :index, :type\n\n  # optionally override to export only selected fields\n  def to_elastics\n    serializable_hash(only: [:id, :first_name, :last_name])\n  end\nend\n\nUser.elastics # Elastics::Client instance\nUser.elastics_params # hash with index \u0026 type values for the model\nUser.request_elastics(params) # performs request merging params with elastics_params\n\nsearch = User.search_elastics(data)\n# Returns Elastics::ActiveRecord::SearchResult object with some useful methods\nsearch.relation # User.where(id: found_ids)\nsearch.collection # Array of users sorted as in elastics response\n\n# Set scope applied to relation:\nsearch = Project.search_elastics(data, scope: -\u003e(s) { s.includes(:user) })\nsearch.collection.first.user # eagger-loaded\n\n# Indexing on create/update can be skipped with skip_elastics\nUser.skip_elastics { users.each { |x| x.update_attributes(smth: 'not indexed') } }\nuser.skip_elastics { user.update_attributes(smth: 'not indexed') }\n```\nCheck out [Model::HelperMethods](https://github.com/printercu/elastics-rb/blob/master/lib/elastics/model/helper_methods.rb)\nand [AR::HelperMethods](https://github.com/printercu/elastics-rb/blob/master/lib/elastics/active_record/helper_methods.rb)\nfor more information.\n\n#### Configure\n```yml\n# database.yml\ndevelopment:\n  elastics:\n    # use single index (app_dev/users, app_dev/documents)\n    index: app_dev\n\n    # use index per type (app_dev_users/users, app_dev_documents/documents)\n    index_prefix: app_dev_\n\nproduction:\n  elastics:\n    host: 10.0.0.1:1234\n    # or\n    host:\n      - 10.0.0.1:1234\n      - 10.0.0.2:1234\n\n    index: app\n    # or\n    index_prefix: app_\n```\n\nYAML is passed througn ERB before parsing.\n\n#### Create mappings \u0026 import data\n```\n$ rake elastics:migrate elastics:reindex\n```\n\n#### Mappings \u0026 index settings\nMappings \u0026 index settings `.yml` files are placed in\n`db/elastics/mappings` \u0026 `db/elastics/indices`.\nFor now this files are not related to models and only used by rake tasks.\n\n### Index management\nWhen index is created elastics transparently manages aliases for it.\nInstead of creating `index1` it creates `index1-v0` and create `index1` alias for it.\nWhen you perform normal migration, mappings are applied to the current version.\nLater when you perform full migration `index1-v1` is created, after reindexing\naliases are changed and `index-v0` is droped.\n\nVersions of indices are stored in ElasticSearch in `.elastics` index.\n\n### Rake tasks\nAll rake tasks except `purge` accepts list of indices to process\n(`rake elastics:create[index1,index2]`).\nAlso you can specify index version like this `rake elastics:migrate version=next`.\nVersion can be set to `next` or `current` (default).\n\nRake tasks are just frontend for `Elastics::Tasks`'s methods.\nFor complex migrations, when you need partially reindex data,\nyou may want to write custom scripts using this methods.\n\n- `rake elastics:create` (`.create_indices`)\ncreates index with settings for each file from `indices` folder.\n\n- `rake elastics:migrate` (`.migrate`)\nputs mappings from `mappings` folder.\n\n- `rake elastics:migrate!` (`.migrate!`)\nperforms full migration.\n\n- `rake elastics:reindex` (`.reindex`)\nreindexes data.\n\n#### Using without Rails\nYou need to setup `Elastics::Tasks` yourself. This can be done in `environment` or\n`db:load_config` rake tasks.\n\n```ruby\ntask :environment do\n  Elastics::Tasks.base_paths = '/path/to/your/elastics/folder'\n  Elastics::Tasks.config = your_configuration\nend\n```\n\nAlso you need to install `active_support` to be able to run tasks.\n\n### Auto refresh index\nAdd `Elastics::AutoRefresh.enable!` to your test helper,\nthis will run `POST /:index/_refresh` request after each modifying request.\nYou can also use it for a block or skip auto refresh after it was enabled:\n\n```ruby\n# enable test mode in rspec's around filter\naround { |ex| Elastics::AutoRefresh.enable! { ex.run } }\n\n# disable auto refresh for block \u0026 perform single refresh\n# assume test mode is enabled here\nElastics::AutoRefresh.disable! { Model.reindex_elastics }\nModel.refresh_elastics\n```\n\n### Instrumentation\nInstrumentation works out of box in rails. For pure ruby there is only\nActiveSupport version (remember to install gem).\n\n```ruby\n# Activate instrumentation (no need for rails)\nElastics::Instrumentation::ActiveSupport.install\n\n# Activate body prettifier (off by default)\nElastics::Instrumentation.body_prettifier = true\n# can be\n#   true - JSON.pretty_generate\n#   :ap  - awesome_print\n#   :pp  - pretty_print\n#   Proc - -\u003e(str) { your_prettifier(str) }\n```\n\n### Connecting to cluster\nWhen you pass array in `:host` option to initializer, client will work in cluster mode.\nThere are some options for this mode:\n- `:connect_timeout`    - timeout to mark the host as dead in cluster-mode (default 10)\n- `:resurrect_timeout`  - timeout to mark dead host as alive in cluster-mode (default 60)\n- `:discover`           - enable nodes discovering\n\nIn plain ruby you should also install `thread_safe` gem.\n\n##### Note about nodes discovering\nClient will perform requests to discover nodes with enabled http module. After\ndiscovering hosts will be overwritten with discovered ones.\n\n`discover: true` will keep you from editing config too frequently,\nbut keep in mind that you should set enough hosts explicitly, so that discover\nwill be able to continue if some of hosts are down.\nAlso this is performed automaticaly only once, when client is initialized.\nIt will not track nodes that go online after client was instantiated. Anyway you\nstill can call `.discover_cluster` whenever you want, or just restart app when\nyou add more nodes.\n\n### Thread-safety\nElastics designed to be thread-safe. It should be ok to have single client instance\nfor the whole application.\n\n### Use with capistrano\nAdd following lines to your `deploy.rb` and all rake tasks will be available in cap.\n\n```ruby\nrole :elastics, '%HOSTNAME%', primary: true\n\nrequire 'elastics/capistrano'\n```\n\nIndices \u0026 rake options can be passed like this:\n```\ncap --dry-run elastics:migrate INDICES=index1,index2 ES_OPTIONS='full=true no_drop=true'\n```\n\n## Other versions\n[elastics for node.js](https://github.com/printercu/elastics)\n\n## License\nMIT\n","funding_links":[],"categories":["Ruby","Search"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprintercu%2Felastics-rb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fprintercu%2Felastics-rb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprintercu%2Felastics-rb/lists"}