3.5.17.Elasticsearch SQL
创作人:杨智
审稿人:刘帅
一、初步了解
1. Elasticsearch SQL 是什么?
2018年6月,Elasticsearch 6.3 版本 X-Pack 插件中引入新的 SQL 查询功能,虽然一直到现在,有经验的专业人员仍然更加喜欢使用 Elasticsearch DSL 来进行搜索,但是毫无疑问,
Elasticsearch SQL 的查询语法对于新用户更加友好,毕竟大部分程序员并不想从头学习一门新的语言。下面是两条等价的查询语句:
# Elasticsearch SQL 查询语句 POST /_sql?format=txt { "query": """ SELECT AVG(DistanceKilometers) AS AvgDistance, OriginCountry FROM kibana_sample_data_flights WHERE DestWeather='Sunny' AND AvgTicketPrice>=300 GROUP BY OriginCountry ORDER BY OriginCountry ASC LIMIT 5""" } # Elasticsearch DSL 查询语句 GET kibana_sample_data_flights/_search { "size" : 0, "query" : { "bool" : { "must": [ { "term" : { "DestWeather" : { "value" : "Sunny" } } }, { "range" : { "AvgTicketPrice" : { "gte": 300 } } } ] } }, "aggregations" : { "groupby" : { "composite" : { "size": 5, "sources" : [ { "a1" : { "terms" : { "field" : "OriginCountry", "order" : "asc" } } } ] }, "aggregations" : { "a2" : { "avg" : { "field" : "DistanceKilometers" } } } } } }
2. Elasticsearch SQL 不是什么?
Elasticsearch SQL 提供了一个符合 ANSI SQL 规范的只读接口,即通过 Elasticsearch SQL,我们只能进行搜索,无法实现创建、更新、删除 Elasticsearch 的索引或者索引中的文档。
Elasticsearch SQL 的查询功能,相比较于其他关系型数据库的 SQL 查询,有许多独特之处,例如: Elasticsearch SQL 不支持 join 查询语法,但却实现了更加强大的聚合分析函数。更多不同之处,下文将会详细介绍。
3. 环境说明
本文测试环境为 Elasticsearch Cloud 免费试用的 Elasticsearch 集群,其中 Elasticsearch 和 Kibana 版本是 7.14.0,文中查询的索引 test_logs 即是 Kibana 示例索引kibana_sample_data_logs。
# 新建索引别名 POST _aliases { "actions": [ { "add": { "index": "kibana_sample_data_logs", "alias": "test_logs" } } ] }
《Elastic Stack 实战手册》——三、产品能力——3.5 进阶篇——3.5.17.Elasticsearch SQL (2) https://developer.aliyun.com/article/1227076