Skip to content

Commit d8859ae

Browse files
committed
[MODEL] Allow passing the index settings and mappings as arguments to create_index!
1 parent 844e1fe commit d8859ae

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

elasticsearch-model/lib/elasticsearch/model/indexing.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -220,15 +220,19 @@ def load_settings_from_io(settings)
220220
# Article.__elasticsearch__.create_index! index: 'my-index'
221221
#
222222
def create_index!(options={})
223-
target_index = options.delete(:index) || self.index_name
223+
options = options.clone
224+
225+
target_index = options.delete(:index) || self.index_name
226+
settings = options.delete(:settings) || self.settings.to_hash
227+
mappings = options.delete(:mappings) || self.mappings.to_hash
224228

225229
delete_index!(options.merge index: target_index) if options[:force]
226230

227231
unless index_exists?(index: target_index)
228232
self.client.indices.create index: target_index,
229233
body: {
230-
settings: self.settings.to_hash,
231-
mappings: self.mappings.to_hash }
234+
settings: settings,
235+
mappings: mappings }
232236
end
233237
end
234238

elasticsearch-model/test/unit/indexing_test.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,27 @@ class ::DummyIndexingModelForRecreate
528528
assert_nothing_raised { DummyIndexingModelForRecreate.create_index! }
529529
end
530530

531+
should "get the index settings and mappings from options" do
532+
client = stub('client')
533+
indices = stub('indices')
534+
client.stubs(:indices).returns(indices)
535+
536+
indices.expects(:create).with do |payload|
537+
assert_equal 'foobar', payload[:index]
538+
assert_equal 3, payload[:body][:settings][:index][:number_of_shards]
539+
assert_equal 'bar', payload[:body][:mappings][:foobar][:properties][:foo][:analyzer]
540+
true
541+
end.returns({})
542+
543+
DummyIndexingModelForRecreate.expects(:index_exists?).returns(false)
544+
DummyIndexingModelForRecreate.expects(:client).returns(client).at_least_once
545+
546+
DummyIndexingModelForRecreate.create_index! \
547+
index: 'foobar',
548+
settings: { index: { number_of_shards: 3 } },
549+
mappings: { foobar: { properties: { foo: { analyzer: 'bar' } } } }
550+
end
551+
531552
should "not create the index when it exists" do
532553
client = stub('client')
533554
indices = stub('indices')

0 commit comments

Comments
 (0)