Skip to content

Commit f2ca55f

Browse files
committedJun 3, 2014
[MODEL] Added, that "raw" response from Elasticsearch is wrapped in Hashie::Mash for easier access
response = Article.search query: { match: { title: { query: 'test' } } }, aggregations: { dates: { date_histogram: { field: 'created_at', interval: 'hour' } } } assert_equal 2, response.response.aggregations.dates.buckets.first.doc_count # => 2
1 parent 250eb41 commit f2ca55f

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed
 

‎elasticsearch-model/lib/elasticsearch/model/response.rb

+3-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ def initialize(klass, search, options={})
2727
# @return [Hash]
2828
#
2929
def response
30-
@response ||= search.execute!
30+
@response ||= begin
31+
Hashie::Mash.new(search.execute!)
32+
end
3133
end
3234

3335
# Returns the collection of "hits" from Elasticsearch

‎elasticsearch-model/test/integration/active_record_basic_test.rb

+8
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,14 @@ class ::Article < ActiveRecord::Base
164164
assert_equal 'Testing Coding', response.records.order('title DESC').first.title
165165
end
166166
end
167+
168+
should "allow dot access to response" do
169+
response = Article.search query: { match: { title: { query: 'test' } } },
170+
aggregations: { dates: { date_histogram: { field: 'created_at', interval: 'hour' } } }
171+
172+
response.response.respond_to?(:aggregations)
173+
assert_equal 2, response.response.aggregations.dates.buckets.first.doc_count
174+
end
167175
end
168176

169177
end

‎elasticsearch-model/test/unit/response_test.rb

+10
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@ def self.document_type; 'bar'; end
2525
assert_equal 'OK', response.shards.one
2626
end
2727

28+
should "wrap the raw Hash response in Hashie::Mash" do
29+
@search = Elasticsearch::Model::Searching::SearchRequest.new OriginClass, '*'
30+
@search.stubs(:execute!).returns({'hits' => { 'hits' => [] }, 'aggregations' => { 'dates' => 'FOO' }})
31+
32+
response = Elasticsearch::Model::Response::Response.new OriginClass, @search
33+
34+
assert_respond_to response.response, :aggregations
35+
assert_equal 'FOO', response.response.aggregations.dates
36+
end
37+
2838
should "load and access the results" do
2939
@search.expects(:execute!).returns(RESPONSE)
3040

0 commit comments

Comments
 (0)