forked from elastic/elasticsearch-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresults.rb
103 lines (89 loc) · 3.33 KB
/
results.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
module Elasticsearch
module Persistence
module Repository
module Response # :nodoc:
# Encapsulates the domain objects and documents returned from Elasticsearch when searching
#
# Implements `Enumerable` and forwards its methods to the {#results} object.
#
class Results
include Enumerable
attr_reader :repository
attr_reader :raw_response
# The key for accessing the results in an Elasticsearch query response.
#
HITS = 'hits'.freeze
# The key for accessing the total number of hits in an Elasticsearch query response.
#
TOTAL = 'total'.freeze
# The key for accessing the maximum score in an Elasticsearch query response.
#
MAX_SCORE = 'max_score'.freeze
# @param repository [Elasticsearch::Persistence::Repository::Class] The repository instance
# @param response [Hash] The full response returned from the Elasticsearch client
# @param options [Hash] Optional parameters
#
def initialize(repository, response, options={})
@repository = repository
@raw_response = response
@options = options
end
def method_missing(method_name, *arguments, &block)
results.respond_to?(method_name) ? results.__send__(method_name, *arguments, &block) : super
end
def respond_to?(method_name, include_private = false)
results.respond_to?(method_name) || super
end
# The number of total hits for a query
#
def total
raw_response[HITS][TOTAL]
end
# The maximum score for a query
#
def max_score
raw_response[HITS][MAX_SCORE]
end
# Yields [object, hit] pairs to the block
#
def each_with_hit(&block)
results.zip(raw_response[HITS][HITS]).each(&block)
end
# Yields [object, hit] pairs and returns the result
#
def map_with_hit(&block)
results.zip(raw_response[HITS][HITS]).map(&block)
end
# Return the collection of domain objects
#
# @example Iterate over the results
#
# results.map { |r| r.attributes[:title] }
# => ["Fox", "Dog"]
#
# @return [Array]
#
def results
@results ||= raw_response[HITS][HITS].map do |document|
repository.deserialize(document.to_hash)
end
end
# Access the response returned from Elasticsearch by the client
#
# @example Access the aggregations in the response
#
# results = repository.search query: { match: { title: 'fox dog' } },
# aggregations: { titles: { terms: { field: 'title' } } }
# results.response.aggregations.titles.buckets.map { |term| "#{term['key']}: #{term['doc_count']}" }
# # => ["brown: 1", "dog: 1", ...]
#
# @return [Elasticsearch::Model::HashWrapper]
#
def response
@response ||= Elasticsearch::Model::HashWrapper.new(raw_response)
end
end
end
end
end
end