Class: Arelastic::Queries::Bool

Inherits:
Query show all
Defined in:
lib/arelastic/queries/bool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Query

#has_child, #has_parent, #negate, #nested

Methods inherited from Nodes::Node

#==, #convert_to_elastic, #hash, #read_option!

Methods included from Arities::Binary

#binary

Methods included from Arities::Polyadic

#polyadic

Methods included from Arities::Unary

#unary

Constructor Details

#initialize(options) ⇒ Bool

Returns a new instance of Bool.



5
6
7
8
9
10
11
# File 'lib/arelastic/queries/bool.rb', line 5

def initialize(options)
  @must     = read_option! options, 'must'
  @filter   = read_option! options, 'filter'
  @should   = read_option! options, 'should'
  @must_not = read_option! options, 'must_not'
  @options  = options
end

Instance Attribute Details

#filterObject

Returns the value of attribute filter.



4
5
6
# File 'lib/arelastic/queries/bool.rb', line 4

def filter
  @filter
end

#mustObject

Returns the value of attribute must.



4
5
6
# File 'lib/arelastic/queries/bool.rb', line 4

def must
  @must
end

#must_notObject

Returns the value of attribute must_not.



4
5
6
# File 'lib/arelastic/queries/bool.rb', line 4

def must_not
  @must_not
end

#optionsObject

Returns the value of attribute options.



4
5
6
# File 'lib/arelastic/queries/bool.rb', line 4

def options
  @options
end

#shouldObject

Returns the value of attribute should.



4
5
6
# File 'lib/arelastic/queries/bool.rb', line 4

def should
  @should
end

Instance Method Details

#as_elasticObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/arelastic/queries/bool.rb', line 13

def as_elastic
  searches = {}

  {
    'must'     => must,
    'filter'   => filter,
    'should'   => should,
    'must_not' => must_not
  }.each do |k, v|
    if v.is_a?(Array)
      v = merge_expression(k, v, klass: Queries::HasParent, merge_test_method: :parent_type)
      v = merge_expression(k, v, klass: Queries::HasChild, merge_test_method: :type)
      v = merge_expression(k, v, klass: Queries::Nested, merge_test_method: :path_and_options)
    end

    searches[k] = convert_to_elastic(v) if v
  end

  { 'bool' => searches.update(options) }
end

#merge_expression(clause, expr, klass:, merge_test_method:) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/arelastic/queries/bool.rb', line 34

def merge_expression(clause, expr, klass:, merge_test_method:)
  mergeable, other = expr.partition { |el| el.is_a?(klass) }
  merged = mergeable.group_by(&merge_test_method).flat_map do |_, group|
    if group.size > 1
      group.first.instance_variable_set("@query", self.class.new(clause => group.map(&:query)))
      group.first
    else
      group
    end
  end
  merged + other
end