在 jsonb postgres 中按日期排序

Sort by date in jsonb postgres

我有一个模型,其中数据以 json 格式存储在 postgres 的 jsonb 列中。

我想使用 activerecord 查询按数据字段对输出进行排序。

Model.all.order("json_data -> 'date'")

给了我一个输出,但根据日期字符串按字母顺序排列。

有没有简单的方法可以将其排序为日期?

注意:日期格式如下:

"Fri, 24 Jun 2016 04:13:26 -0700"

Is there an easy way I can sort this as a date?

不作为 jsonb 字段的一部分,因为 JSON doesn't know anything about dates


因此,一个简单的替代方法是将它们存储为单独的 table 列。

如果您真的必须将它们存储为 json 字段的一个元素,那么我会建议以下两个选项之一:

  1. 将您的字段存储为时间戳。因为,postgresql 中的 json 字段支持数值,它可以(可能)优化排序。
  2. 将您的日期存储在 ISO 8601 格式字符串中。 It would sort correctly,即使是字符串。

如果日期格式合理,Postgres 会自动处理。

Model.all.order("(json_data ->> 'date')::timestamp with time zone DESC")

Model.all.order("(json_data ->> 'date')::timestamptz DESC")

如果你的日期字段字符串有点不正统,你可以这样做

Model.all.order("to_timestamp(json_data->>'date','Dy, DD Mon YYYY HH24:MI:SS ') DESC")

详情here

注意 ->> 输出字符串而不是 json 对象。

您当然可以根据@Uzbekjon 下面的回答创建一个额外的列并将您的信息存储在那里。