今天有一个场景,基于企业标签的数量进行排序。我的实现逻辑是按照企业的标签字符串长度进行排序,在es中这也算一种聚合查询的场景。
id | vipSign | licenses |
---|---|---|
1 | 1 | A |
2 | 0 | A,C |
3 | 1 | A,C |
优先按照vip标签排序,然后再按照licenses的长度排序,期望结果应为:3、1、2。
已知,licenses属性的mapping设置为:
{
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
困难缠身的原因一般是对基础概念或特性的理解不足。
首先text属性的字段在es中存储时,会被自动分词存储;text属性的字段是支持分词,但不支持聚合的。我们可以在kibana的index patterns
中可以查看索引属性的特性。
doc['field_name'].length
或者doc['field_name'].size()
获取字段长度,那么需要修改mappings该属性的类型;doc['field_name.keyword'].value.length()
,但是需要注意,如果doc['field_name.keyword'].value
的值存在为null的情况,需要使用doc['field_name.keyword'].size()
优先判空。最终的脚本为:
POST /lpm-route-v2/_search
{
"from": 0,
"size": 10,
"query": {
"terms": {
"id": [
"66108",
"72221"
]
}
},
"sort": [
{
"store.company.vipSign": {
"order": "desc"
}
},
{
"_script": {
"script": {
"source": "doc['store.company.licenses.keyword'].size()>0 ?doc['store.company.licenses.keyword'].value.length():0",
"lang": "painless"
},
"type": "number",
"order": "desc"
}
}
]
}
错误写法
POST /lpm-route-v2/_search
{
"from": 0,
"size": 10,
"query": {"match_all": {}},
"sort": [
{
"store.company.vipSign": {
"order": "desc"
}
},
{
"_script": {
"script": {
"source": "doc['store.company.licenses'].length",
"lang": "painless"
},
"type": "number",
"order": "desc"
}
}
]
}
提示信息如下,即默认不支持聚合和排序:
“reason” : “Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [store.company.licenses] in order to load field data by uninverting the inverted index. Note that this can use significant memory.”
脚本表达式正确写法为:
doc['store.company.licenses.keyword'].length
,其表达的含义为统计元素的个数,可以理解为数组元素的个数。
命中结果的排序均为:
{
"_index" : "lpm-company-v1",
"_type" : "_doc",
"_id" : "5229",
"_score" : null,
"_source" : {
...
},
"sort" : [
1,
1.0
]
},
也就是说,第二个字段doc['store.company.licenses'].length
的值为1,同:doc['store.company.licenses'].size()
,返回结果为数组的长度,那么如何返回字符串的长度呢?
"caused_by" : {
"type" : "illegal_state_exception",
"reason" : "A document doesn't have a value for a field! Use doc[].size()==0 to check if a document is missing a field!"
}
原因:字符串字段中存储有null值。
解决办法:doc['licenses.keyword'].size() !=0 ?doc['licenses.keyword'].value.length() :0
感谢您的赏读~
您还可以关注我的微信公众号回复“es脑图”,获取我的Elasticsearch学习思维导图哦。,就这么“定”了!