elasticsearch - 在热门点击聚合中访问脚本排序上下文中的字段
问题描述
我有这个文件,我想这样排序:
- 如果值 1 在字段 id_status_viewed 中,则文档的排序权重为 1
- 如果值 1 在字段 id_status_new 中,则文档的排序权重为 0
我想在热门聚合中根据权重进行排序。例子 :
{
"string_ticket_name": "ticket D",
"object_tasks": [
{
"user_id": 1,
"id_status_viewed": [
1
],
"id_status_new": [0]
}
]
}
这是我尝试过的:
{
"aggs": {
"object_tasks": {
"nested": {
"path": "object_tasks"
},
"aggs": {
"names": {
"top_hits": {
"sort": [
{
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": "for (item in params._source.id_status_viewed) { if (item == 1) {return 2;}} for (item in params._source.id_status_new) { if (item == 1) {return 0;}}"
},
"order": "asc"
}
}
]
}
}
}
}
}
}
但由于某种原因,我无法访问 id_status_viewed
"script_stack": [
"for (item in params._source.id_status_viewed) { ",
" ^---- HERE"
],
"reason": "Cannot invoke \"Object.getClass()\" because \"receiver\" is null"
下面有更多细节(映射)
{
"mappings": {
"properties": {
"object_views": {
"type": "nested",
"properties": {
"number_rank": {
"type": "double"
},
"string_status": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"user_id": {
"type": "long"
}
}
},
"string_ticket_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"object_tasks": {
"type": "nested",
"properties": {
"string_ticket_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"user_id": {
"type": "long"
}
}
}
}
}
}
解决方案
在nested
上下文中,您不能迭代嵌套的父级——您只能访问“当前”嵌套的子文档。也就是说,而不是params._source
你会使用doc[...]
符号:
{
"aggs": {
"object_tasks": {
"nested": {
"path": "object_tasks"
},
"aggs": {
"names": {
"top_hits": {
"sort": [
{
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": """
def status_viewed = doc['object_tasks.id_status_viewed'].empty ? null : doc['object_tasks.id_status_viewed'].value;
def status_new = doc['object_tasks.id_status_new'].empty ? null : doc['object_tasks.id_status_new'].value;
if (status_viewed == 1) { return 2; }
if (status_new == 1) { return 0; }
// fallback
return Long.MAX_VALUE;
"""
},
"order": "asc"
}
}
]
}
}
}
}
}
}
推荐阅读
- mysql - 杀死进程(数字海洋 ubuntu 液滴)
- vue.js - VUE i18n 中长文本段落的国际化
- sql-server - 如何使用来自命令提示符的插入/选择查询执行 SQL Server Management Studio 上可用的存储过程
- python - 无法使用 Flask 在 PostgreSQL 中创建多个表
- python - PyQT5:无法让路径变量在其函数之外工作
- react-native - React-Native:右对齐的选择器数据
- django - 从 django 管理表单中的编辑表单一对一关系中排除分配的对象
- java - 在给定角度和距点的距离的情况下找到坐标
- python - 如何在 SQL 中进行内部联接时添加带有条件的常量列
- hyperledger-indy - libindy 中创建凭证提案的方法是什么?