Skip to content

Commit aa00588

Browse files
committed
[MODEL] Added the ability to import records into a different index/type
Article.import index: 'my-new-index', type: 'my-other-type'
1 parent 6f4a57a commit aa00588

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

elasticsearch-model/lib/elasticsearch/model/importing.rb

+10-6
Original file line numberDiff line numberDiff line change
@@ -60,20 +60,24 @@ module ClassMethods
6060
#
6161
# Article.import refresh: true
6262
#
63+
# @example Import the records into a different index/type than the default one
64+
#
65+
# Article.import index: 'my-new-index', type: 'my-other-type'
6366
#
6467
def import(options={}, &block)
65-
errors = 0
68+
errors = 0
69+
refresh = options.delete(:refresh) || false
70+
target_index = options.delete(:index) || index_name
71+
target_type = options.delete(:type) || document_type
6672

6773
if options.delete(:force)
68-
self.create_index! force: true
74+
self.create_index! force: true, index: target_index
6975
end
7076

71-
refresh = options.delete(:refresh) || false
72-
7377
__find_in_batches(options) do |batch|
7478
response = client.bulk \
75-
index: index_name,
76-
type: document_type,
79+
index: target_index,
80+
type: target_type,
7781
body: batch
7882

7983
yield response if block_given?

elasticsearch-model/test/unit/importing_test.rb

+26
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,33 @@ def importing_mixin
9191
assert_equal true, options[:force]
9292
end
9393

94+
DummyImportingModel.expects(:index_name).returns('foo')
95+
DummyImportingModel.expects(:document_type).returns('foo')
96+
9497
DummyImportingModel.import force: true, foo: 'bar'
9598
end
99+
100+
should "allow passing a different index / type" do
101+
Elasticsearch::Model::Adapter.expects(:from_class)
102+
.with(DummyImportingModel)
103+
.returns(DummyImportingAdapter)
104+
105+
DummyImportingModel.__send__ :include, Elasticsearch::Model::Importing
106+
107+
client = mock('client')
108+
109+
client
110+
.expects(:bulk)
111+
.with do |options|
112+
assert_equal 'my-new-index', options[:index]
113+
assert_equal 'my-other-type', options[:type]
114+
true
115+
end
116+
.returns({'items' => [ {'index' => {} }]})
117+
118+
DummyImportingModel.stubs(:client).returns(client)
119+
120+
DummyImportingModel.import index: 'my-new-index', type: 'my-other-type'
121+
end
96122
end
97123
end

0 commit comments

Comments
 (0)