ElasticSearch脚本按嵌套对象内的日期字段排序



我的映射中有以下字段

"attempts": {
"type": "nested",
"properties": {
"type": {
"type": "keyword"
},
"reason": {
"type": "keyword"
},
"status": {
"type": "keyword"
},
"number": {
"type": "integer"
},
"date": {
"type": "date"
}
}
}

我需要做以下事情:

当从ui提供某个typenumber时,我必须按照字段attempts.date 进行排序

我想这可以用剧本完成,但我做不到。

这就是我尝试的:

sort: [
{
_script: {
nested: {
path: 'attempts',
},
script: {
lang  : 'painless',
source: `if (
doc['attempts.number'].value === params.number 
&& doc['attempts.type'].value === params.attemptType
) {
return doc['attempts.date'].date.getMillis()
}`,
params: { attemptType, number },
},
order : sortType,
type  : 'number',
},
},
{
_id: 'desc'
}
]

它不会给出任何错误,只是每次都以不同的顺序返回记录。

有人能帮忙吗?

我不知道你用哪种语言实现它,但我会这样做(如果我正确理解你的问题(。

这样做的目的是在应用程序中不在查询中保留短规则。您的应用程序将在查询中注入所需的排序。

根据你的地图,我索引了两份文件:

POST idx_test/_doc
{
"attempts": {
"type": "type_a",
"number": 10,
"date": "2020-07-21"
}
}
POST idx_test/_doc
{
"attempts": {
"type": "type_a",
"number": 10,
"date": "2020-07-20"
}
}

当你的前台发送类型和号码时,你会有一个工厂,它会返回你想要的排序。

Front发送type=type_a和number=10。工厂将退回分拣:

"sort": [
{
"attempts.date": {
"order": "asc",
"nested_path": "attempts"
}
}
]

如果没有收到预期的类型和数字,则可以使用默认排序或不在查询中注入排序。

最后,您的排序查询将如下所示:

GET idx_test/_search
{
"query": {
"match_all": {}
}, 
"sort": [
{
"attempts.date": {
"order": "asc",
"nested_path": "attempts"
}
}
]
}

通过此查询,您将获得按日期排序字段。如果日期相同,这对你来说很好,我建议使用你为文档定义的分数或id。

最新更新