分享一款Elasticsearch-SQL插件--使用SQL語法查詢Elasticsearch

ElasticSearch SQL Mac App Store JSON 瀏覽器 波波說運維 2019-06-09

概述

Elasticsearch-SQL是Elasticsearch的一個插件,它可以讓我們通過類似SQL的方式對Elasticsearch中的數據進行查詢。

項目地址是:https://github.com/NLPchina/elasticsearch-sql
分享一款Elasticsearch-SQL插件--使用SQL語法查詢Elasticsearch


安裝部署

不同Elasticsearch版本需要安裝的插件版本也不同,使用的Elasticsearch版本是2.3.3,對應版本插件安裝方法是(先切換到Elasticsearch目錄下):

./bin/plugin install https://github.com/NLPchina/elasticsearch-sql/releases/download/2.3.3.0/elasticsearch-sql-2.3.3.0.zip

其實在生產環境中很多服務器是不能直接連接外網進行下載的。這裡先將文件下載到本地,然後再上傳到生產環境的服務器中,在上傳到服務器後,從本地文件安裝插件。安裝插件時在install後面加"file:",之後加Elasticsearch-sql.zip文件的絕對路徑:

[root@ceshi202 elasticsearch-2.3.3]# ./bin/plugin installfile:/opt/elasticsearch-2.3.3/elasticsearch-sql-2.3.3.0.zip
-> Installing from file:/opt/elasticsearch-2.3.3/elasticsearch-sql-2.3.3.0.zip...
Trying file:/opt/elasticsearch-2.3.3/elasticsearch-sql-2.3.3.0.zip ...
Downloading .......................................DONE
Verifying file:/opt/elasticsearch-2.3.3/elasticsearch-sql-2.3.3.0.zipchecksums if available ...
NOTE: Unable to verify checksum for downloaded plugin (unable to find .sha1 or .md5 file to verify)
Installed sql into /opt/elasticsearch-2.3.3/plugins/sql
[root@ceshi202 elasticsearch-2.3.3]#

安裝結束後,需要重新啟動Elasticsearch服務,不然在搜索的時候會有下面的報錯:

Invalid index name [sql], must not start with '']; ","status":400}.

我的報錯如下:

分享一款Elasticsearch-SQL插件--使用SQL語法查詢Elasticsearch


基本用法

不同Elasticsearch版本的使用方法不同,1.x / 2.x的方法相似,5.x的使用方法比較特殊,

在elasticsearch 1.x / 2.x上,從瀏覽器訪問:

http://localhost:9200/_plugin/sql/

打開頁面如下:

分享一款Elasticsearch-SQL插件--使用SQL語法查詢Elasticsearch


基本查詢

打開頁面的SQL Query中是最基本的查詢,將"SELECT * FROM myindex"中的myindex改成你的Elasticsearch中索引的名字就可以進行搜索:

分享一款Elasticsearch-SQL插件--使用SQL語法查詢Elasticsearch

同時可增加搜索條件:

SELECT common,page FROM myindex where common.channel = "AppStore" and page.duration > 5000 limit 10

在搜索index時可以使用"*"來同時搜索多個索引:

SELECT common,page FROM myindex-* where common.channel = "AppStore" and page.duration > 5000 limit 10

可以做基本的統計

Select COUNT(*),SUM(page.duration),MIN(page.duration) as m, MAX(page.duration),AVG(page.duration) FROM myindex-* GROUP BY common.device_id ORDER BY SUM(page.duration), m DESC

也可以使用Elasticsearch自帶的一些函數做matchQuery、聚合(Aggregations)、地理位置(Geographic)等。


Elasticsearch的查詢語言(DSL)不太好寫,偏偏查詢的功能千奇百怪,不管是通過封裝JSON還是通過python/java的api進行封裝,都非常不方便。而Elasticsearch-SQL這個插件可以用sql查詢Elasticsearch,整體還是很方便的,建議大家使用。

後面會分享更多devops和DBA方面的內容,感興趣的朋友可以關注一下~

分享一款Elasticsearch-SQL插件--使用SQL語法查詢Elasticsearch

相關推薦

推薦中...