elasticsearch_adapter.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. module Blazer
  2. module Adapters
  3. class ElasticsearchAdapter < BaseAdapter
  4. def run_statement(statement, comment)
  5. columns = []
  6. rows = []
  7. error = nil
  8. begin
  9. header, body = statement.gsub(/\/\/.+/, "").strip.split("\n", 2)
  10. body = JSON.parse(body)
  11. body["timeout"] ||= data_source.timeout if data_source.timeout
  12. response = client.msearch(body: [JSON.parse(header), body])["responses"].first
  13. if response["error"]
  14. error = response["error"]
  15. else
  16. hits = response["hits"]["hits"]
  17. source_keys = hits.flat_map { |r| r["_source"].keys }.uniq
  18. hit_keys = (hits.first.try(:keys) || []) - ["_source"]
  19. columns = source_keys + hit_keys
  20. rows =
  21. hits.map do |r|
  22. source = r["_source"]
  23. source_keys.map { |k| source[k] } + hit_keys.map { |k| r[k] }
  24. end
  25. end
  26. rescue => e
  27. error = e.message
  28. end
  29. [columns, rows, error]
  30. end
  31. def tables
  32. client.indices.get_aliases(name: "*").map { |k, v| [k, v["aliases"].keys] }.flatten.uniq.sort
  33. end
  34. def preview_statement
  35. %!// header\n{"index": "{table}"}\n\n// body\n{"query": {"match_all": {}}, "size": 10}!
  36. end
  37. protected
  38. def client
  39. @client ||= Elasticsearch::Client.new(url: settings["url"])
  40. end
  41. end
  42. end
  43. end