如何解决 NoSQL 语法中拼 key 的主键字段生成的序列为日期序列而不是数字序列?
常见的业务场景中,经常出现拼接 keyFormat 的主键中,且有一个主键对应业务中的实际日期,例如:key_format 为 ${prefix}-${p_date}-${suffix},其中p_date对应业务的实际日期,如20230530,在创建的 API 中,希望查询某一个时间段的数据,例如在 where 条件中 p_date between and 20230530 and 20230602,在这种情况下:
注意
由于date 类型的返回结果是YYYY-MM-DD格式的 string 类型,所以对存量逻辑表进行 date 类型字段的改造是会改变已经发布 API 的返回结果类型!!!
NoSQL 语法中的 Date 类型,在请求参数和返回参数中,需要注意的点如下:
对于逻辑表中的逻辑字段字段来说,如果该字段类型是 Date,并且该逻辑字段对应的物理字段类型是 int 类型(即整数类型)或者 string 类型(即字符串类型),那么:
对于物理表中的物理字段来说,如果该字段类型是 Date,那么在实际的数据源中,该字段类型与 String 类型相同,即在实际的数据源中,Date 类型字段是以 String 类型格式存储。
NoSQL 语法提供函数 date_normalize来归一化 Date 类型的返回格式为想要的类型。
函数签名
date_normalize(param, data_type, date_format)
入参
pattern 格式 | 含义 | 实例 |
|---|---|---|
%Y | 年,4位 | 2022 |
%m | 月,数值(00-12) | 06 |
%d | 日,数值(0-31) | 30 |
出参
特定格式的返回结果。
data_type为int,入参为 bigint 类型
date_normalize(p_date, 'int', '%Y%m%d') // p_date 值为 bigint 类型的 20230418 输出结果 bigint 类型的 20230418
data_type为int,入参为 string 类型
date_normalize(p_date, 'int', '%Y%m%d') // p_date 值为 string 类型的'20230418' 输出结果 bigint 类型的 20230418
data_type为string,入参为 bigint 类型
date_normalize(p_date, 'string', '%Y-%m-%d') // p_date 值为 20230418 输出结果 string 类型的 '2023-04-18'
data_type为string,入参为 string 类型
date_normalize(p_date, 'string', '%Y/%m/%d') // p_date 值为 '20230418' 输出结果 string 类型的 '2023/04/18'
date_normalize(p_date, 'string', '%Y%m%d') // p_date 值为 '20230418' 输出结果 string 类型的 '20230418'