diff --git a/README.md b/README.md index 629e603..c455c94 100644 --- a/README.md +++ b/README.md @@ -647,6 +647,22 @@ Also supports [additional options](http://www.elasticsearch.org/guide/en/elastic City.search "san", boost_by_distance: {field: :location, origin: [37, -122], function: :linear, scale: "30mi", decay: 0.5} ``` +### Routing + +Searchkick supports elasticsearch's routing feature. + +```ruby +class Contact < ActiveRecord::Base + searchkick routing: :user_id +end +``` + +Reindex and search with: + +```ruby +Contact.search "John", routing: current_user.id +``` + ## Inheritance Searchkick supports single table inheritance. diff --git a/lib/searchkick/index.rb b/lib/searchkick/index.rb index ef8aab5..d659cdd 100644 --- a/lib/searchkick/index.rb +++ b/lib/searchkick/index.rb @@ -423,9 +423,15 @@ module Searchkick } end + routing = {} + if options[:routing] + routing = {required: true, path: options[:routing].to_s} + end + mappings = { _default_: { properties: mapping, + _routing: routing, # https://gist.github.com/kimchy/2898285 dynamic_templates: [ { diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb index 0bac47b..6a21ce9 100644 --- a/lib/searchkick/query.rb +++ b/lib/searchkick/query.rb @@ -379,6 +379,11 @@ module Searchkick if options[:type] || klass != searchkick_klass @type = [options[:type] || klass].flatten.map { |v| searchkick_index.klass_document_type(v) } end + + # routing + if options[:routing] + @routing = options[:routing] + end end @body = payload @@ -407,6 +412,7 @@ module Searchkick body: body } params.merge!(type: @type) if @type + params.merge!(routing: @routing) if @routing params end diff --git a/test/routing_test.rb b/test/routing_test.rb new file mode 100644 index 0000000..1a9aa65 --- /dev/null +++ b/test/routing_test.rb @@ -0,0 +1,14 @@ +require_relative "test_helper" + +class TestRouting < Minitest::Test + + def test_routing_query + query = Store.search("Dollar Tree", routing: "Dollar Tree", execute: false) + assert_equal query.params[:routing], "Dollar Tree" + end + + def test_routing_mappings + index_options = Store.searchkick_index.index_options + assert_equal index_options[:mappings][:_default_][:_routing], {required: true, path: "name"} + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index 642fb65..f451aa5 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -212,12 +212,15 @@ class Product end class Store - searchkick mappings: { - store: { - properties: { - name: {type: "string", analyzer: "keyword"} + searchkick \ + routing: :name, + merge_mappings: true, + mappings: { + store: { + properties: { + name: {type: "string", analyzer: "keyword"}, + } } - } } end -- libgit2 0.21.0