ElasticSearch使用SQL

Elasticsearch的SQL插件简化了复杂查询操作,使用户能够以接近传统SQL的方式进行数据检索。本文介绍了该插件的优势及安装过程,并提供了在不同环境下配置插件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ElasticSearch一个非常不好的地方,就是查询语句写起来太麻烦,这个用过的人都深有体会。比如说,这么一个简单的查询:

select count(*) from bonree_web where @timestamp between "now-3d/d" and "2017-07-08" group by CITY_CODE limit 3

在ES里写出来的查询语句能有这么长:

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

是不是很坑爹?于是,我们大量的时间被用在了……花括号对齐上=。=
幸运的是,我们有elasticsearch-sql。这是一个ES插件,可以让我们像刚才那样用SQL查询ES,简直爽的飞起。而且这个项目非常活跃,更新也很及时。插件的安装使用很简单,官网也有详细说明,这里不再赘述。
除了插件之外,该项目还提供了一个site,用于像Kibana的Dev Tools那样交互式执行SQL查询,这个的安装需要说明一下,以Elastic5.4.0版本为例。

1. 基本安装

unzip es-sql-site-standalone.zip
cd site-server
npm install express --save
node node-server.js 

默认端口是8080,需要修改的话可以改site-server/site_configuration.json文件。

如果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 lang=\"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}
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值