c# - 如何使用 jmespath 对 ASC 和 DESC 进行排序
问题描述
我需要有关表达式的帮助,以便对同一数据进行升序和降序排序。
我可以用管道分隔多个表达式,但我似乎找不到任何在同一个调用中同时执行 ASC 和 DESC 的示例。
所以我要找的等于下面的 sql 查询。
select *
from dummyData
order by id, code desc, update_only
这是样本。
[
{
"id": 1,
"code": "y",
"update_only": 0.0
},
{
"id": 2,
"code": "a",
"update_only": 0.0
},
{
"id": 1,
"code": "z",
"update_only": 0.0
},
{
"id": 2,
"code": "b",
"update_only": 0.0
}
]
我可以为订购做以下事情
sort_by(array elements, expression->number|expression->string expr)
我怎样才能用一个电话而不是我的两个电话来做以下事情?
sort_by(myarray, &id | &update_only)[];
reverse(sort_by(myarray, &code))[];
或者通过多次调用,也不想这样做。
result1 = sort_by(myarray, &id)[];
result2 = reverse(sort_by(result1, &code))[];
resilt3 = sort_by(myarray, &update_only)[];
解决方案
你的实际表达是不正确的,你会意识到,如果你改变一个值update_only
那&id | &update_only
不是一回事。
文档中描述的内容:
expression->number|expression->string expr
实际上意味着表达式可以是字符串类型或数字类型,而不是您可以使用管道符号链接多个排序。
对此进行了解释:
JMESPath 具有各种内置函数,可对不同的数据类型进行操作,如下所述。下面的每个函数都有一个签名,定义了输入的预期类型和返回的输出的类型:
return_type function_name(type $argname) return_type function_name2(type1|type2 $argname)
函数支持的数据类型列表有:
- 数字(JSON 中的整数和双精度浮点格式)
- 细绳
- 布尔值(真或假)
- 数组(有序的值序列)
- 对象(键值对的无序集合)
- 无效的
- 表达式(用 & 表示)
除最后一项外,以上所有类型均对应 JSON 提供的类型。
如果函数可以接受输入值的多种类型,则多种类型之间用 . 分隔
|
。如果解析的参数与签名中指定的类型不匹配,则会发生无效类型错误。
资料来源:https ://jmespath.org/specification.html#built-in-functions ,重点,我的
现在,想要实现的目标非常简单。
当您对多列进行排序时,就像链接排序一样,从低优先级到高优先级。
这意味着您可以(在伪代码中):
sort by id (
reverse (
sort by code (
reverse (
// ^--- this is the trick, so when you will reverse it
// again, to have the DESC sorting on `code`, you'll end
// up with the sorting of `update_only` in the "correct" order
sort by update_only
)
)
)
)
因此,翻译成 JEMSPath 表达式:
sort_by(reverse(sort_by(reverse(sort_by(@,&update_only)),&code)),&id)
以下 JSON 上的此表达式(从您的示例中添加了一个额外的案例来展示update_only
排序:
[
{
"id": 1,
"code": "y",
"update_only": 0.0
},
{
"id": 2,
"code": "a",
"update_only": 0.0
},
{
"id": 1,
"code": "z",
"update_only": 0.0
},
{
"id": 2,
"code": "b",
"update_only": 1.0
},
{
"id": 2,
"code": "b",
"update_only": 0.0
}
]
会给:
[
{
"id": 1,
"code": "z",
"update_only": 0
},
{
"id": 1,
"code": "y",
"update_only": 0
},
{
"id": 2,
"code": "b",
"update_only": 0
},
{
"id": 2,
"code": "b",
"update_only": 1
},
{
"id": 2,
"code": "a",
"update_only": 0
}
]
推荐阅读
- html - 没有z-index,父子关系如何影响堆叠顺序?
- sql - 如何找到位置之间的平均距离
- bash - 如何获取已登录 Oracle/设置 ssh 的用户的名称以不需要用户名?
- javascript - 如何在给定总和的数组中找到子数组的数量?
- oracle - 没有得到想要的结果
- r - 传递参数以在 R 中执行 group_by 的函数
- matlab - 在 Matlab 中计算积分
- c# - 实体框架 - 在相关实体上加载相关实体(一对多对一)
- git - gitlab CI中的LFTP:文件不会在FTP服务器上更新,即使它们在最后一次提交中被更改
- docker - 来自 kubernetes 集群的 apt update 给出错误 Clearsigned file is not valid, got 'NOSPLIT' (does the network requires authentication?)