天天看點

ElasticSearch使用SQL1. 基本安裝2. 安全配置

ElasticSearch一個非常不好的地方,就是查詢語句寫起來太麻煩,這個用過的人都深有體會。比如說,這麼一個簡單的查詢:

在ES裡寫出來的查詢語句能有這麼長:

GET /bonree_net/_search
{
  "size":,
  "query": {
    "range": {
      "@timestamp": {
        "gt": "now-3d/d",
        "lt": "2017-07-08"
      }
    }
  },
  "aggs": {
    "city_code": {
      "terms": {
        "field": "CITY_CODE",
        "size": 
      }
    }
  }
}
           

是不是很坑爹?于是,我們大量的時間被用在了……花括号對齊上=。=

幸運的是,我們有elasticsearch-sql。這是一個ES插件,可以讓我們像剛才那樣用SQL查詢ES,簡直爽的飛起。而且這個項目非常活躍,更新也很及時。插件的安裝使用很簡單,官網也有詳細說明,這裡不再贅述。

除了插件之外,該項目還提供了一個site,用于像Kibana的Dev Tools那樣互動式執行SQL查詢,這個的安裝需要說明一下,以Elastic5.4.0版本為例。

1. 基本安裝

  • 下載下傳es-sql-site-standalone.zip。注意elasticsearch-sql的插件命名是帶版本号的,但是site不帶,是以要到https://github.com/NLPchina/elasticsearch-sql/releases查找自己版本對應的site。
  • 下載下傳完成後解壓安裝并運作:
unzip es-sql-site-standalone.zip
cd site-server
npm install express --save
node node-server.js 
           

預設端口是8080,需要修改的話可以改

site-server/site_configuration.json

檔案。

  • 如果是生産環境,可能無法通過npm安裝依賴,這裡提供一個我安裝完後打包的版本:es-sql-site-standalone-5.4.0-mvpboss1004.zip。

如果ES沒有使用X-Pack,到此就可以使用了。

2. 安全配置

如果使用了X-Pack,那麼還涉及到使用者名密碼等問題。參考以下配置:

  • 修改ES配置檔案

    /etc/elasticsearch/elasticsearch.yml

    ,增加以下幾行:
http.cors.enabled: true
http.cors.allow-credentials: true
http.cors.allow-origin: "/.*/"
http.cors.allow-headers: WWW-Authenticate,X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization
           
  • 重新開機叢集
  • 通路elasticsearch-sql的site時,帶上使用者名、密碼、ES的位址作為參數,例如:

    http://es-sql-site:8080/?username=hello&password=o11eh&base_uri=http://es:9200

  • 為便于大家排障,site的頁面會顯示錯誤原因,這裡列幾個:
    • 未正确配置ES的位址:

      Error: "<!DOCTYPE html>\n<html en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /_sql</pre>\n</body>\n</html>\n"

    • elasticsearch.yml

      中未正确配置http.cors:

      Error: Error occured! response is not avalible.

    • 使用者名或密碼錯誤:

      Error: {"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication token for REST request [/_sql]","header":{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-8\""}}],"type":"security_exception","reason":"missing authentication token for REST request [/_sql]","header":{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-8\""}},"status":401}