天天看点

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}