Class: LogStash::Search::ElasticSearch

Inherits:
Base
  • Object
show all
Defined in:
lib/logstash/search/elasticsearch.rb

Instance Method Summary collapse

Methods inherited from Base

#count, #popular_terms

Constructor Details

#initialize(settings = {}) ⇒ ElasticSearch

Returns a new instance of ElasticSearch.



14
15
16
17
18
# File 'lib/logstash/search/elasticsearch.rb', line 14

def initialize(settings={})
  @host = (settings[:host] || "localhost")
  @port = (settings[:port] || 9200).to_i
  @logger = LogStash::Logger.new(STDOUT)
end

Instance Method Details

#histogram(query, field, interval = nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/logstash/search/elasticsearch.rb', line 95

def histogram(query, field, interval=nil)
  if query.is_a?(String)
    query = LogStash::Search::Query.parse(query)
  end

  # TODO(sissel): only search a specific index?
  http = EventMachine::HttpRequest.new("http://#{@host}:#{@port}/_search")

  @logger.info(["Query", query])
  histogram_settings = {
    "field" => field
  }

  if !interval.nil? && interval.is_a?(Numeric)
    histogram_settings["interval"] = interval
  end

  esreq = {
    "query" => {
      "query_string" => { 
         "query" => query.query_string,
         "default_operator" => "AND"
      } # query_string
    }, # query
    "from" => 0,
    "size" => 0,
    "facets" => {
      "amazingpants" => { # just a name for this histogram...
        "histogram" => histogram_settings,
      },
    },
  } # elasticsearch request

  @logger.info("ElasticSearch Facet Query: #{esreq.to_json}")
  start_time = Time.now
  req = http.get :body => esreq.to_json
  result = LogStash::Search::FacetResult.new
  req.callback do
    data = JSON.parse(req.response)
    result.duration = Time.now - start_time

    @logger.info(["Got search results", 
                 { :query => query.query_string, :duration => data["duration"] }])
    if req.response_header.status != 200
      result.error_message = data["error"] || req.inspect
      @error = data["error"] || req.inspect
    end

    entries = data["facets"]["amazingpants"]["entries"] rescue nil

    if entries.nil? or !data["error"].nil?
      # Use the error message if any, otherwise, return the whole
      # data object as json as the error message for debugging later.
      result.error_message = (data["error"] rescue false) || data.to_json
      yield result
      next
    end
    entries.each do |entry|
      # entry is a hash of keys 'total', 'mean', 'count', and 'key'
      hist_entry = LogStash::Search::FacetResult::Histogram.new
      hist_entry.key = entry["key"]
      hist_entry.count = entry["count"]
      result.results << hist_entry
    end # for each histogram result
    yield result
  end # request callback

  req.errback do 
    @logger.warn(["Query failed", query, req, req.response])
    result.duration = Time.now - start_time
    result.error_message = req.response
    yield result
    #yield({ "error" => req.response })
  end
end

#search(query) ⇒ Object



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
# File 'lib/logstash/search/elasticsearch.rb', line 22

def search(query)
  raise "No block given for search call." if !block_given?
  if query.is_a?(String)
    query = LogStash::Search::Query.parse(query)
  end

  # TODO(sissel): only search a specific index?
  http = EventMachine::HttpRequest.new("http://#{@host}:#{@port}/_search")

  @logger.info(["Query", query])
  esreq = {
    "sort" => [
      { "@timestamp" => "desc" }
    ],
    "query" => {
      "query_string" => { 
         "query" => query.query_string,
         "default_operator" => "AND"
      } # query_string
    }, # query
    "from" => query.offset,
    "size" => query.count
  } # elasticsearch request

  @logger.info("ElasticSearch Query: #{esreq.to_json}")
  start_time = Time.now
  req = http.get :body => esreq.to_json
  result = LogStash::Search::Result.new
  req.callback do
    data = JSON.parse(req.response)
    result.duration = Time.now - start_time

    hits = data["hits"]["hits"] rescue nil

    if hits.nil? or !data["error"].nil?
      # Use the error message if any, otherwise, return the whole
      # data object as json as the error message for debugging later.
      result.error_message = (data["error"] rescue false) || data.to_json
      yield result
      next
    end

    @logger.info(["Got search results", 
                 { :query => query.query_string, :duration => data["duration"],
                   :result_count => hits.size }])
    if req.response_header.status != 200
      result.error_message = data["error"] || req.inspect
      @error = data["error"] || req.inspect
    end

    # We want to yield a list of LogStash::Event objects.
    hits.each do |hit|
      result.events << LogStash::Event.new(hit["_source"])
    end

    # Total hits this search could find if not limited
    result.total = data["hits"]["total"]
    result.offset = query.offset

    yield result
  end

  req.errback do 
    @logger.warn(["Query failed", query, req, req.response])
    result.duration = Time.now - start_time
    result.error_message = req.response

    yield result
  end
end