文档章节

Elasticsearch 6.3 SQL功能使用案例分享

bboss
 bboss
发布于 06/23 01:23
字数 1468
阅读 3761
收藏 0

The best elasticsearch highlevel java rest api-----bboss       

Elasticsearch 6.3 官方新增的SQL功能非常不错,本文以实际案例来介绍其使用方法:

  • 通过sql实现检索功能(代码中直接操作sql,从配置中加载sql)
  • 将sql转换为dsl功能
  • 使用es jdbc
  • 准备工作:集成Elasticsearch Restful API

1.代码中的sql检索

    @Test
	public void testQuery(){
		ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
		String json = clientUtil.executeHttp("/_xpack/sql?format=txt",
				"{\"query\": \"SELECT * FROM dbclobdemo\"}",
				ClientInterface.HTTP_POST
				);
		System.out.println(json);

		json = clientUtil.executeHttp("/_xpack/sql?format=json",
				"{\"query\": \"SELECT * FROM dbclobdemo\"}",
				ClientInterface.HTTP_POST
		);
		System.out.println(json);
	}

执行的结果在本文的最后给出。

2.sql转换为dsl

可以将sql转换为dsl语句

   public void testTranslate(){
		ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
		String json = clientUtil.executeHttp("/_xpack/sql/translate",
				"{\"query\": \"SELECT * FROM dbclobdemo\"}",
				ClientInterface.HTTP_POST
		);
		System.out.println(json);

	}

sql转换为dsl的结果:

{
    "size": 1000,
    "_source": {
        "includes": [
            "author",
            "content",
            "docClass",
            "docabstract",
            "keywords",
            "mediapath",
            "newpicPath",
            "parentDetailTpl",
            "picPath",
            "publishfilename",
            "secondtitle",
            "subtitle",
            "title",
            "titlecolor"
        ],
        "excludes": []
    },
    "docvalue_fields": [
        "auditflag",
        "channelId",
        "count",
        "createtime",
        "createuser",
        "detailtemplateId",
        "docLevel",
        "docsourceId",
        "doctype",
        "documentId",
        "docwtime",
        "flowId",
        "isdeleted",
        "isnew",
        "ordertime",
        "publishtime",
        "seq",
        "status",
        "version"
    ],
    "sort": [
        {
            "_doc": {
                "order": "asc"
            }
        }
    ]
}

3.配置文件管理sql并实现sql检索

定义一个包含sql的dsl配置文件,sql语句中包含一个channelId检索条件:

<properties>
    <!--
        sql query
    -->
    <property name="sqlQuery">
        <![CDATA[
         {"query": "SELECT * FROM dbclobdemo where channelId=#[channelId] and name='#[name,quoted=false]'"} ##加上quoted=false属性,指示框架不要为字符串加""号,因为sql需要''号
        ]]>
    </property>
</properties>

加载配置文件并实现sql检索操作 ,从外部传入检索的条件channelId

    public void testSQLQueryFromDSL(){
		ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/sql.xml");//初始化一个加载sql配置文件的es客户端接口
		//设置sql查询的参数
		Map params = new HashMap();
		params.put("channelId",1);
        params.put("name","乔丹");
		String json = clientUtil.executeHttp("/_xpack/sql","sqlQuery",params,
				ClientInterface.HTTP_POST
		);
		System.out.println(json);//打印检索结果

	}

输出检索的结果为:

{
    "columns": [
        {
            "name": "auditflag",
            "type": "long"
        },
        {
            "name": "author",
            "type": "text"
        },
        {
            "name": "channelId",
            "type": "long"
        },
        {
            "name": "content",
            "type": "text"
        },
        {
            "name": "count",
            "type": "long"
        },
        {
            "name": "createtime",
            "type": "date"
        },
        {
            "name": "createuser",
            "type": "long"
        },
        {
            "name": "detailtemplateId",
            "type": "long"
        },
        {
            "name": "docClass",
            "type": "text"
        },
        {
            "name": "docLevel",
            "type": "long"
        },
        {
            "name": "docabstract",
            "type": "text"
        },
        {
            "name": "docsourceId",
            "type": "long"
        },
        {
            "name": "doctype",
            "type": "long"
        },
        {
            "name": "documentId",
            "type": "long"
        },
        {
            "name": "docwtime",
            "type": "date"
        },
        {
            "name": "flowId",
            "type": "long"
        },
        {
            "name": "isdeleted",
            "type": "long"
        },
        {
            "name": "isnew",
            "type": "long"
        },
        {
            "name": "keywords",
            "type": "text"
        },
        {
            "name": "mediapath",
            "type": "text"
        },
        {
            "name": "newpicPath",
            "type": "text"
        },
        {
            "name": "ordertime",
            "type": "date"
        },
        {
            "name": "parentDetailTpl",
            "type": "text"
        },
        {
            "name": "picPath",
            "type": "text"
        },
        {
            "name": "publishfilename",
            "type": "text"
        },
        {
            "name": "publishtime",
            "type": "date"
        },
        {
            "name": "secondtitle",
            "type": "text"
        },
        {
            "name": "seq",
            "type": "long"
        },
        {
            "name": "status",
            "type": "long"
        },
        {
            "name": "subtitle",
            "type": "text"
        },
        {
            "name": "title",
            "type": "text"
        },
        {
            "name": "titlecolor",
            "type": "text"
        },
        {
            "name": "version",
            "type": "long"
        }
    ],
    "rows": [
        [
            0,
            "不详",
            1,
            "asdfasdfasdfasdfsdf<img name=\"imgs\" src=\"../gencode7.png\" _ewebeditor_pa_src=\"http%3A%2F%2Flocalhost%2Fcms%2FsiteResource%2Ftest%2F_webprj%2Fgencode7.png\"><br>\r\nasdfasdf<img name=\"imgs\" src=\"content_files/20180505101457109.png\" _ewebeditor_pa_src=\"http%3A%2F%2Flocalhost%2Fcms%2FsiteResource%2Ftest%2F_webprj%2Fnews%2Fcontent_files%2F20180505101457109.png\"><br>\r\n<br>",
            0,
            "2018-04-12T14:16:02.000Z",
            1,
            1,
            "普通分类",
            1,
            "无asdfasdf",
            1,
            0,
            1,
            "2018-05-06T03:30:04.000Z",
            2,
            0,
            0,
            "news",
            "uploadfiles/201803/gencode4.png",
            "",
            "2018-04-12T14:06:45.000Z",
            "1",
            "uploadfiles/201803/gencode1.png",
            "asdf.html",
            "2018-04-14T14:36:12.000Z",
            "",
            0,
            11,
            "asdf",
            "adsf",
            "#000000",
            1
        ]
    ]
}

4 使用es jdbc

可以通过jdbc操作es,首先在工程中导入es jdbc maven坐标:

导入elasticsearch jdbc驱动和bboss持久层
<dependency>
  <groupId>org.elasticsearch.plugin</groupId>
  <artifactId>jdbc</artifactId>
  <version>6.3.2</version>
</dependency>
<dependency> 
    <groupId>com.bbossgroups</groupId> 
    <artifactId>bboss-persistent</artifactId> 
    <version>5.0.7.6</version> 
</dependency> 

在pom中添加elastic maven库 

<repositories>
  <repository>
    <id>elastic.co</id>
    <url>https://artifacts.elastic.co/maven</url>
  </repository>
</repositories>

通过jdbc驱动执行elasticsearch sql相关功能

  • 启动es数据源
  • 执行elasticsearch sql相关功能

直接看执行各种sql功能的代码ESJdbcTest

package com.frameworkset.sqlexecutor;
/*
 *  Copyright 2008 biaoping.yin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import com.frameworkset.common.poolman.SQLExecutor;
import com.frameworkset.common.poolman.util.SQLUtil;
import org.junit.Test;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

public class ESJdbcTest {

	public void initDBSource(){
		SQLUtil.startPool("es",//ES数据源名称
				"org.elasticsearch.xpack.sql.jdbc.jdbc.JdbcDriver",//ES jdbc驱动
				"jdbc:es://http://127.0.0.1:9200/timezone=UTC&page.size=250",//es链接串
				"elastic","changeme",//es x-pack账号和口令
				"SHOW tables 'dbclob%'" //数据源连接校验sql
		);
	}

	/**
	 * 执行一个查询
	 * @throws SQLException
	 */
	@Test
	public void testSelect() throws SQLException {
		initDBSource();//启动数据源
		//执行查询,将结果映射为HashMap集合
		 List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SELECT SCORE() as score,content as content FROM dbclobdemo");
		 System.out.println(data);
	}

	/**
	 * 进行模糊搜索,Elasticsearch 的搜索能力大家都知道,强!在 SQL 里面,可以用 match 关键字来写,如下:
	 * @throws SQLException
	 */
	@Test
	public void testMatchQuery() throws SQLException {
		initDBSource();
		List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SELECT SCORE(), * FROM dbclobdemo WHERE match(content, '_ewebeditor_pa_src') ORDER BY documentId DESC");
		System.out.println(data);

		/**
		 *还能试试 SELECT 里面的一些其他操作,如过滤,别名,如下:
		 */
		data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SELECT SCORE() as score,title as myname FROM dbclobdemo  as mytable WHERE match(content, '_ewebeditor_pa_src') and (title.keyword = 'adsf' OR title.keyword ='elastic') limit 5 ");
		System.out.println(data);
	}
	/**
	 * 分组和函数计算
	 */
	@Test
	public void testGroupQuery() throws SQLException {
		initDBSource();
		List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SELECT title.keyword,max(documentId) as max_id FROM dbclobdemo as mytable group by title.keyword limit 5");
		System.out.println(data);


	}


	/**
	 * 查看所有的索引表
	 * @throws SQLException
	 */
	@Test
	public void testShowTable() throws SQLException {
		initDBSource();
		List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SHOW tables");
		System.out.println(data);
	}

	/**
	 * 如 dbclob 开头的索引,注意通配符只支持 %和 _,分别表示多个和单个字符(什么,不记得了,回去翻数据库的书去!)
	 * @throws SQLException
	 */
	@Test
	public void testShowTablePattern() throws SQLException {
		initDBSource();
		List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SHOW tables 'dbclob_'");
		System.out.println(data);
		data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SHOW tables 'dbclob%'");
		System.out.println(data);
	}
	/**
	 * 查看索引的字段和元数据
	 * @throws SQLException
	 */
	@Test
	public void testDescTable() throws SQLException {
		initDBSource();
		List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","DESC dbclobdemo");
		System.out.println(data);
		data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SHOW COLUMNS IN dbclobdemo");
		System.out.println(data);
	}

	/**
	 * 不记得 ES 支持哪些函数,只需要执行下面的命令,即可得到完整列表
	 * @throws SQLException
	 */
	@Test
	public void testShowFunctin() throws SQLException {
		initDBSource();
		List<HashMap> data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SHOW FUNCTIONS");
		System.out.println(data);
		//同样支持通配符进行过滤:
		data =	SQLExecutor.queryListWithDBName(HashMap.class,"es","SHOW FUNCTIONS 'S__'");
		System.out.println(data);

	}
}

如果执行的时候报错:

可以采用正式的license或者在elasticsearch.yml文件最后添加以下配置即可:

xpack.license.self_generated.type: trial

5.完整的demo

https://gitee.com/bbossgroups/eshelloword-booter

https://github.com/bbossgroups/eshelloword-booter

6.开发交流

elasticsearch sql官方文档:

https://www.elastic.co/guide/en/elasticsearch/reference/current/xpack-sql.html

elasticsearch技术交流群:166471282

elasticsearch微信公众号:

bboss微信公众号:bbossgroups

© 著作权归作者所有

共有 人打赏支持
bboss

bboss

粉丝 91
博文 54
码字总数 56803
作品 8
长沙
程序员
加载中

评论(4)

JornTang
JornTang
不错不错加油
吐槽的达达仔
吐槽的达达仔
日期怎么处理呢??
光脚满地跑
光脚满地跑
这个新版本的功能真不错,映射sql的方法可以很轻松的构建结果集咯。感谢博主~
bboss
bboss
What's your problem?
bboss elasticsearch v5.0.6.2 发布

The best elasticsearch highlevel java rest api-----bboss bboss elasticsearch v5.0.6.2 发布 v5.0.6.2新增功能及改进: 1.升级最新的bboss版本到5.0.5.7 2.新增bboss es rest boot模块,......

bboss
04/29
0
0
【上海Meetup回放视频+PPT下载整理】Elasticsearch Meetup系列第二期

Elasticsearch Meetup系列第二期活动中,7位来自阿里巴巴、eBay、沪江、携程等知名企业的技术大咖现场分享了集群管理、架构、定制开发、业务支撑的使用经验。以下是此次活动的直播整理。 阿里...

黯灭_邓彬
07/25
0
0
【回放视频+PPT下载整理】Elasticsearch Meetup系列第二期

Elasticsearch Meetup系列第二期活动中,7位来自阿里巴巴、eBay、沪江、携程等知名企业的技术大咖现场分享了集群管理、架构、定制开发、业务支撑的使用经验。以下是此次活动的直播整理。 《利...

a独家记忆
07/24
0
0
当ES赶超Redis,这份ES进修攻略不容错过!

从4月DB-Engines最新发布的全球数据库排名中,我们赫然发现ElasticSearch逆袭超越了Redis,从原先的第9名上升至第8名,而Redis则落后一名,排在了其后。 事实上,这场逆袭并不算太让人意外。...

DBAplus社群
04/15
0
0
bboss v5.0.6.8 发布,持久支持Elasticsearch SQL

bboss v5.0.6.8发布,持久层支持Elasticsearch SQL和Elasticsearch JDBC. v5.0.6.8功能改进 持久层支持支持Elasticsearch SQL,使用参考文档:玩转Elasticsearch SQL功能 解决持久层/elasti...

bboss
07/02
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周四乱弹 —— 毒蛇当辣条

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @ 达尔文:分享花澤香菜/前野智昭/小野大輔/井上喜久子的单曲《ミッション! 健?康?第?イチ》 《ミッション! 健?康?第?イチ》- 花澤香菜/前野智...

小小编辑
46分钟前
4
0
java -jar运行内存设置

java -Xms64m #JVM启动时的初始堆大小 -Xmx128m #最大堆大小 -Xmn64m #年轻代的大小,其余的空间是老年代 -XX:MaxMetaspaceSize=128m # -XX:CompressedClassSpaceSize=6...

李玉长
57分钟前
1
0
Spring | 手把手教你SSM最优雅的整合方式

HEY 本节主要内容为:基于Spring从0到1搭建一个web工程,适合初学者,Java初级开发者。欢迎与我交流。 MODULE 新建一个Maven工程。 不论你是什么工具,选这个就可以了,然后next,直至finis...

冯文议
今天
1
0
RxJS的另外四种实现方式(四)——性能最高的库(续)

接上一篇RxJS的另外四种实现方式(三)——性能最高的库 上一篇文章我展示了这个最高性能库的实现方法。下面我介绍一下这个性能提升的秘密。 首先,为了弄清楚Most库究竟为何如此快,我必须借...

一个灰
今天
1
0
麒麟AI首席科学家现世

8月31日,华为发布了新一代顶级人工智能手机芯片麒麟980,成为全球首款7nm工艺手机芯片,AI方面也实现飞跃,支持人脸识别、物体识别、物体检测、图像分割、智能翻译等。 虽然如今人人都在热议...

问题终结者
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部