请教elasticsearch自定义结果集过滤如何支持
2016-12-03
展开全部
用groovy脚本自定义ElasticSearch查询,来实现以上功能。
例,数据中包含字段birdtyday,记录游客生日:
"birthday": "1992-02-05 00:00:00",
新建文件getAgeByBirthday.groovy,编辑其内容为:
def b = doc[birthday_field].value
def birthday = new Date(b)
def now = new Date()
long age = (now -birthday)/365
age
并把此文件放在es的config/scripts目录下(如果没有此目录就新建一个)。
然后在config/elasticsearch.yml文件中加一行:
script.groovy.sandbox.enabled: true
最后重启es即可。
接下来,我们就可以用以下DSL进行年龄统计了
GET /lovingtrip-report/hotelcustomer/_search?search_type=count
{
"aggs": {
"counts_by_age": {
"terms": {
"script_file": "getAgeByBirthday",
"params": {
"birthday_field": "birthday"
},
"size": 100
}
}
}
}
或者:
GET /lovingtrip-report/hotelcustomer/_search?search_type=count
{
"aggs": {
"histogram_by_age": {
"histogram": {
"script_file": "getAgeByBirdthday",
"params": {
"birdthday_field": "birdthday"
},
"interval": 5
}
}
}
}
不过脚本查询性能不佳,且不能利用es的缓存,所以在大数据量或高性能要求的场景下不适用。。
-------------------------------------
补充一个自定义的年龄range过滤:
range_AgeByBirthday.groovy:
def b = doc[birdthday_field].value
def birdthday = new Date(b)
def now = new Date()
long age = (now -birdthday)/365
gte<=age && age<=lte
DSL:
GET /lovingtrip-report/hotelcustomer/_search?search_type=count
{
"query": {
"filtered": {
"filter": {
"script": {
"script_file": "range_AgeByBirdthday",
"params": {
"birdthday_field": "birdthday",
"gte": 50,
"lte": 60
}
}
}
}
},
"aggs": {
"histogram_by_age": {
"histogram": {
"script_file": "getAgeByBirdthday",
"params": {
"birdthday_field": "birdthday"
},
"interval": 5
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询