Skip to content

Instantly share code, notes, and snippets.

@Kallin
Created November 4, 2014 18:42
Show Gist options
  • Save Kallin/dd4430f6a9613d78ea46 to your computer and use it in GitHub Desktop.
Save Kallin/dd4430f6a9613d78ea46 to your computer and use it in GitHub Desktop.
module Elasticsearcher
module QuerybuilderAdapter
def self.included base
base.extend ClassMethods
end
module ClassMethods
QUERYBUILDER_TO_ELASTIC_RANGES = {
'before' => 'lt',
'less' => 'lt',
'less_than' => 'lt',
'less_or_equal' => 'lte',
'after' => 'gt',
'greater' => 'gt',
'greater_than' => 'gt',
'greater_or_equal' => 'gte'
}
def qb_rule_to_elastic_rule(rule)
value = rule.value
field = rule.field
operator = rule.operator
if QUERYBUILDER_TO_ELASTIC_RANGES.key? operator
range_operator = QUERYBUILDER_TO_ELASTIC_RANGES[operator]
elastic_rule = {range: {field => {range_operator => value}}}
elsif operator == 'equal'
elastic_rule = {term: {field => value}}
elsif operator == 'not_equal'
elastic_rule = {not: {filter: {term: {field => value}}}}
else
raise "Unknown filter operator"
end
elastic_rule
end
def qb_condition_to_elastic_condition (qb_condition)
elastic_rules = []
qb_condition.rules.each do |qb_rule|
the_rule = qb_rule[1]
if the_rule.condition
elastic_rules << qb_condition_to_elastic_condition(the_rule)
else
elastic_rules << qb_rule_to_elastic_rule(the_rule)
end
end
elastic_search_filter = Hashie::Mash.new
if qb_condition.condition=='AND'
elastic_search_filter.and!.filters = elastic_rules
else
elastic_search_filter.or!.filters = elastic_rules
end
elastic_search_filter
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment