1
1
module Elasticsearch
2
2
module Persistence
3
3
module Repository
4
- module Response
4
+ module Response # :nodoc:
5
5
6
+ # Encapsulates the domain objects and documents returned from Elasticsearch when searching
7
+ #
8
+ # Implements `Enumerable` and forwards its methods to the {#results} object.
9
+ #
6
10
class Results
7
11
include Enumerable
8
12
9
- attr_reader :repository , :response , :response
13
+ attr_reader :repository
10
14
15
+ # @param repository [Elasticsearch::Persistence::Repository::Class] The repository instance
16
+ # @param response [Hash] The full response returned from the Elasticsearch client
17
+ # @param options [Hash] Optional parameters
18
+ #
11
19
def initialize ( repository , response , options = { } )
12
20
@repository = repository
13
21
@response = Hashie ::Mash . new ( response )
@@ -22,10 +30,14 @@ def respond_to?(method_name, include_private = false)
22
30
results . respond_to? ( method_name ) || super
23
31
end
24
32
33
+ # The number of total hits for a query
34
+ #
25
35
def total
26
36
response [ 'hits' ] [ 'total' ]
27
37
end
28
38
39
+ # The maximum score for a query
40
+ #
29
41
def max_score
30
42
response [ 'hits' ] [ 'max_score' ]
31
43
end
@@ -42,11 +54,35 @@ def map_with_hit(&block)
42
54
results . zip ( response [ 'hits' ] [ 'hits' ] ) . map ( &block )
43
55
end
44
56
57
+ # Return the collection of domain objects
58
+ #
59
+ # @example Iterate over the results
60
+ #
61
+ # results.map { |r| r.attributes[:title] }
62
+ # => ["Fox", "Dog"]
63
+ #
64
+ # @return [Array]
65
+ #
45
66
def results
46
67
@results ||= response [ 'hits' ] [ 'hits' ] . map do |document |
47
68
repository . deserialize ( document . to_hash )
48
69
end
49
70
end
71
+
72
+ # Access the response returned from Elasticsearch by the client
73
+ #
74
+ # @example Access the aggregations in the response
75
+ #
76
+ # results = repository.search query: { match: { title: 'fox dog' } },
77
+ # aggregations: { titles: { terms: { field: 'title' } } }
78
+ # results.response.aggregations.titles.buckets.map { |term| "#{term['key']}: #{term['doc_count']}" }
79
+ # # => ["brown: 1", "dog: 1", ...]
80
+ #
81
+ # @return [Hashie::Mash]
82
+ #
83
+ def response
84
+ @response
85
+ end
50
86
end
51
87
end
52
88
end
0 commit comments