系列文章目录
前言
如果你还在很着急的查找自己想要的es语句,但是苦苦找不到想要的。
这里给你介绍一下sql语句转es语句的方法(将SQL转换为DSL)
Elasticsearch SQL
Elasticsearch SQL允许执行类SQL的查询,可以使用REST接口、命令行或者是JDBC,都可以使用SQL来进行数据的检索和数据的聚合。
SQL与Elasticsearch对应关系
SQL | ES |
---|---|
column(列) | field(字段) |
row(行) | document(文档) |
table(表) | index(索引) |
schema(模式) | mapping(映射) |
database server(数据库服务器) | Elasticsearch集群实例 |
目前FROM只支持单表。
举例
查询wisdom_search_group 索引中image为null的数据
POST /_xpack/sql/translate?pretty
{
"query": "SELECT * FROM 索引名字 where 索引字段名称 is null"
}
POST /_xpack/sql/translate?pretty
{
"query": "SELECT * FROM wisdom_search_group where image is null"
}
目前Elasticsearch SQL还存在一些限制。例如:不支持JOIN、不支持较复杂的子查询。所以,有一些相对复杂一些的功能,还得借助于DSL方式来实现。
一、从一个简单的查询开始
没有任何条件,查询100条记录
类比
mysql
select * from wisdom_system_msg limit 100;
ES
GET /wisdom_system_msg/_search
{
"size": 100,
"query": {
"match_all": {
}
}
}
二、简单查询带条件的查询
首先需要稍微理解一下这里的条件
Bool查询现在包括四种子句,must,filter,should,must_not。
must,filter,should,must_not这四个条件可以先粗略的理解为并且、并且、后者、取反。
想要深入了解的话可以去查查must和filter的区别。
1.查询某列字段不为null的条件查询
GET /wisdom_system_msg/_search
{
"size": 100,
"query": {
"bool": {
"must": {
"exists": {
"field": "operation"
}
}
}
}
}
2.查询某列字段是否包含指定内容(数字默认是不分词的)
当然用es肯定用到它的模糊查询嘛
GET /wisdom_system_msg/_search
{
"size": 100,
"query": {
"bool": {
"must": [
{ "match": {"type" : 21}}
]
}
}
}
3.多条件查询
GET /wisdom_system_msg/_search
{
"size": 100,
"query": {
"bool": {
"must": [
{ "exists": {"field": "operation"}},
{ "match": { "sendId": 43072 }}
]
}
}
}
4.ES数据库中查找时间范围(时间戳)
{
"query":{
"range":{
"finish_time":{
"gte":"1606212000000",
"lte":"1606226400000"
}
}
}
}
5.term和terms等值查询
terms里边的多个条件是或的关系,而不是且的关系。满足一个条件即可。
GET /wisdom_search_group/_search
{
"query": {
"term": {
"groupId": {
"value": "529"
}
}
}
}
GET /wisdom_search_group/_search
{
"query": {
"terms": {
"groupId": [
"530",
"532"
]
}
}
}
6.复杂一点的查询
正常情况下must和must_not是不能出现在同一级的。
假设有条件A,B,C
C的条件为(C1或C2)
整体关系为A&&B&&C
也就是sql语句 A and B and (C1 or C2)
对应es语句
GET /wisdom_system_msg/_search
{
"query": {
"bool": {
"must": [
{"bool": {
"must": [
{"A": { "字段": "值"}}]
}
},
{
"B": {"字段":"值" }
},
{"bool": {
"should": [{"C1": { "字段": "值"}},
{"C2": { "字段": "值"}}]
}
}
]
}
}
}
举例如下
GET /wisdom_system_msg/_search
{
"query": {
"bool": {
"must": [
{"bool": {
"must": [
{"exists": { "field": "operation"}}
]
}
},
{
"term": {"acceptId":"43129" }
},
{"bool": {
"should": [
{"match_phrase": { "context": "欢迎"}},
{"match_phrase": { "context": "哈哈"}}
]
}
}
]
}
}
}
一些简单查询使用开始的sql转es进行学习吧。本章就先学习会写,不往深入探讨。