教你快速从SQL过度到Elasticsearch的DSL查询
参考: https://blog.csdn.net/hellozhxy/article/details/131831897
前言
Elasticsearch太强大了,强大到跟python一样,一种查询能好几种语法。其实我们用到的可能只是其中的一部分,比如:全文搜索。
我们一般是会将mysql的部分字段导入到es,再查询出相应的ID,再根据这些ID去数据库找出来。
问题来了:数据导入到es后,很多人都要面对这个es的json查询语法,也叫DSL,如下

于是一堆新词来了,比如:filter、match、multi_match、query、term、range,容易让没学过的人抵触。
如果正常开发业务的程序员,只关心原先怎么用sql查询出来的数据,在es中查询出来。
sql查询定位,一般常用的是:=、!=、>、<、and、or、in、between等等。
举个例子,原先sql查询一商品是这样的
SELECT * FROM goods WHERE spu_id = "wp123" OR ( spu_id = "wp345" AND min_price = 30 )
对应到es是
{ "query": { "bool": { "should": [ { "term": { "spu_id": "wp123" } }, { "bool": { "must": [ { "term": { "spu_id": "wp345" } }, { "term": { "min_price": 30 } } ] } } ] } } }
sql和dsl是有一定对应关系的,下面把一些常用的总结下,让不熟悉es的童鞋能丝滑能从sql过度
以下内容由chenqionghe倾情提供,祝您es使用愉快
bool-相当于一个括号
用bool包含起来的{},相当用()包含了一个复合查询语句,如上边的
{ "bool": { "must": [ { "term": { "spu_id": "wp345" } }, { "term": { "min_price": 30 } } ] } }
相当于

看到没有就是这么简单
should-相当于or

must-相当于and:

must_not-相当于 ! and
这个就相当于and取反了,
例如:
SELECT * FROM goods WHERE !(shop_id =79)
相当于:
{ "query": { "bool": { "must_not": [ { "term": { "shop_id": "79" } } ] } } }
term-相当于=
例如: SELECT * FROM goods WHERE shop_id =79
相当于:
{ "query": { "bool": { "must": [ { "term": {"shop_id": "79"} } ] } } }
terms-相当于in
例如: SELECT * FROM goods WHERE shop_id in (79,80,81)
{ "query": { "bool": { "must": [ { "terms": { "shop_id": [79, 80, 81] } } ] } } }
range-相当于between
例如: SELECT * FROM goods WHERE id between 1000 and 10005
相当于:
{ "query": { "bool": { "must": [ { "range": { "id": { "gte": 1000, "lte": 10005 } } } ] } } }
exist相当于is not null
例如 : SELECT * FROM goods WHERE id is not null
{ "query": { "bool": { "must_not": [ { "exists": { "field": "id" } } ] } } }

浙公网安备 33010602011771号