Skip to content

Instantly share code, notes, and snippets.

@havran
Last active August 29, 2015 14:17
Show Gist options
  • Save havran/a48286c5b6d5bc6fc7d1 to your computer and use it in GitHub Desktop.
Save havran/a48286c5b6d5bc6fc7d1 to your computer and use it in GitHub Desktop.
Simple Ruby on Rails 4 model with ElasticSearch query.
require 'elasticsearch/model'
class Cbr
include ActiveModel::Model
include Elasticsearch::Model
index_name 'cbr'
document_type 'UC_CBR_003'
# Digital Objects per day
def self.do_per_day
# begin ES query
definition = Elasticsearch::DSL::Search.search do
query do
match_all do
end
end
# minimal timestamp value
aggregation :timestamp_min do
min field: 'timestamp'
end
# maximal timestamp value
aggregation :timestamp_max do
max field: 'timestamp'
end
# sum DO per day
aggregation :do_sum_per_day do
date_histogram do
field 'timestamp'
interval 'day'
format 'dd.MM. yyyy'
aggregation :do_sum do
sum field: 'pocet_do'
end
end
end
end
# end ES query
result = search definition.to_hash, search_type: 'count'
end
end
class DoController < ApplicationController
def report_1
@data = {
timestamp_min: 0,
timestamp_max: 0,
data: []
}
data = []
Cbr.do_per_day.response['aggregations']['do_sum_per_day']['buckets'].each do |row|
row = [
row['key'],
row['do_sum']['value']
]
data.push(row)
end
@data['timestamp_min'] = Cbr.do_per_day.response['aggregations']['timestamp_min']['value']
@data['timestamp_max'] = Cbr.do_per_day.response['aggregations']['timestamp_max']['value']
@data['data'] = data
@data = @data.to_json
render 'reports/report'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment