概述
继续跟中华石杉老师学习ES,第五篇
课程地址: https://www.roncoo.com/view/55
range filter已经被range query取代了,所以我们这里直接来看 range query吧
https://www.elastic.co/guide/en/elasticsearch/reference/6.4/query-dsl-range-filter.html
数据准备
为了演示 范围查询 ,我们增加个 浏览量 view_cnt字段,更新DSL如下
POST /forum/article/_bulk {"update":{"_id":"1"}} {"doc":{"view_cnt":30}} {"update":{"_id":"2"}} {"doc":{"view_cnt":50}} {"update":{"_id":"3"}} {"doc":{"view_cnt":100}} {"update":{"_id":"4"}} {"doc":{"view_cnt":80}}
小示例
搜索浏览量在30~60之间的帖子
老版本的写法
GET /forum/article/_search { "query": { "constant_score": { "filter": { "range": { "view_cnt": { "gt": 30, "lt": 60 } } } } } }
新写法 (推荐)
GET /forum/article/_search { "query": { "range": { "view_cnt": { "gt": 30, "lt": 60 } } } }
搜索发帖日期在最近1个月的帖子
为了演示,我们新增一条数据id=5的数据 ,如下
POST /forum/article/_bulk {"index":{"_id":5}} {"articleID":"DHJK-B-1395-#Ky5","userID":3,"hidden":false,"postDate":"2019-06-01","tag":["elasticsearch"],"tag_cnt":1,"view_cnt":10}
今天是5月12号,上面的6月1号搞错了,再把 postDate 改为 2019-05-01
POST /forum/article/_bulk {"update":{"_id":"5"}} {"doc":{"postDate":"2019-05-01"}}
查看下id=5的数据
那 将需求翻译成 es dsl如下
老版本的写法:
GET /forum/article/_search { "query": { "constant_score": { "filter": { "range": { "postDate": { "gt": "2019-05-12||-30d" } } } } } } GET /forum/article/_search { "query": { "constant_score": { "filter": { "range": { "postDate": { "gt": "now-30d" } } } } } }
now-30d
GET /forum/_search { "query": { "range": { "postDate": { "gte": "now-30d" } } } }
2019-05-12||-30d
GET /forum/_search { "query": { "range": { "postDate": { "gte": "2019-05-12||-30d" } } } }
总结一下:
- range,就像sql中的between
- range query 做范围过滤