Class: Elasticquery::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/elasticquery/query.rb

Constant Summary collapse

DEFAULT =
{query: {filtered: {query: {match_all:{}}}}}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query = DEFAULT) ⇒ Query

Create new query from hash.

Examples:

Elasticsearch::Query.new.to_hash #=> {query: {filtered: {query: {match_all:{}}}}}

Parameters:

  • query (Hash) (defaults to: DEFAULT)

    passed as hash. When it not passed use default es ‘match_all’ query



16
17
18
19
# File 'lib/elasticquery/query.rb', line 16

def initialize(query = DEFAULT)
  @query = query
  @filters = []
end

Instance Attribute Details

#filtersObject (readonly)

Returns the value of attribute filters.



6
7
8
# File 'lib/elasticquery/query.rb', line 6

def filters
  @filters
end

Instance Method Details

#<<(filter) ⇒ Object

Merge filter to query. If current query is ‘matche_all`ed then clear it and use new value. Populate #filters array with given classes

Parameters:

  • filter (Elasticquery::filter::Base)

    passed

See Also:



44
45
46
47
48
# File 'lib/elasticquery/query.rb', line 44

def <<(filter)
  @query = {} if match_all?
  merge filter
  @filters << filter
end

#match_all?Boolean

Ckeck current object to default elasticsearch param

Returns:

  • (Boolean)

    is passed query undefined



53
54
55
# File 'lib/elasticquery/query.rb', line 53

def match_all?
  @query == DEFAULT
end

#to_hashHash

Convery query object ot hash

Returns:

  • (Hash)

    hash presentation of query



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/elasticquery/query.rb', line 24

def to_hash
  q = @query.dup
  if Enumerable === _filters
    flatted_filters = _filters.flat_map do |type, filters|
      filters.flat_map do |key, value|
        {type => {key => value}}
      end
    end
    q[:query][:filtered][:filter][:and] = flatted_filters
  end
  q
end