如何从 jsonb 数组获取产品的最新版本?

How to get latest version of a product from a jsonb array?

使用 PostgreSQL 12.7,我想从嵌套的 JSON 数组中获取产品的最新版本(最大值)。这是 fields 列中 product 'AAA':

的示例值
 "customfield_01":[
      {
         "id":1303,
         "name":"AAA - 1.82.0",
         "state":"closed",
         "boardId":137,
         "endDate":"2021-10-15T10:00:00.000Z",
         "startDate":"2021-10-04T01:00:01.495Z",
         "completeDate":"2021-10-18T03:02:55.824Z"
      },
      {
         "id":1304,
         "name":"AAA - 1.83.0",
         "state":"active",
         "boardId":137,
         "endDate":"2021-10-29T10:00:00.000Z",
         "startDate":"2021-10-18T01:00:24.324Z"
      }
   ],

我试过了:

SELECT product, jsonb_path_query_array(fields, '$.customfield_01.version') AS version
FROM product.issues;

这是输出:

| product | version                                       |
|---------------------------------------------------------|
| CCC     |[]                                             |
| AAA     |["AAA - 1.83.0", "AAA - 1.82.0"]               |
| BBB     |["BBB - 1.83.0", "BBB - 1.82.0", "BBB - 1.84.0]|
| BBB     |["BBB - 1.83.0"]                               |
| BBB     |["BBB - 1.84.0", "BBB - 1.83.0"]               |

预计是:

| product | version                                       |
|---------------------------------------------------------|
| AAA     |["AAA - 1.83.0"                                |
| BBB     |["BBB - 1.84.0]                                |
| BBB     |["BBB - 1.83.0"]                               |
| BBB     |["BBB - 1.84.0"]                               |

已尝试 unnest/Array 但出现错误:

SELECT max(version)
FROM  (SELECT UNNEST(ARRAY [jsonb_path_query_array(fields,'$.customfield_01.version')]) AS version FROM product.issues ) AS version;

确实使用了-1,但它只会得到最右边的数据。

jsonb_path_query_array(fields, '$.customfield_01.version') ->> -1

Postgres & json 非常新。曾尝试阅读文档和 google,但多次尝试都失败了。

假设 product 是您的 table 的主键列。

可以使用SQL/JSON path表达式:

SELECT product, max(version) AS latest_version
FROM   product.issues;
     , jsonb_array_elements_text(jsonb_path_query_array(fields, '$.customfield_01.name')) AS version 
GROUP  BY 1
ORDER  BY 1;

但简单的 jsonb 运算符可以实现相同的效果:

SELECT product, max(version ->> 'name') AS latest_version
FROM   product.issues
     , jsonb_array_elements(fields -> 'customfield_01') AS version
GROUP  BY 1
ORDER  BY 1;

使用jsonb_array_elements()jsonb_array_elements_text()取消嵌套jsonb数组。参见:

unnest()(就像你试过的那样)可用于取消嵌套 Postgres 数组.

当然,max() 仅在“最新版本”按字母顺序最后排序时有效。否则,提取版本部分并将所有部分处理为数字。喜欢:

SELECT i.product, v.*
FROM   issues i
LEFT   JOIN LATERAL (
   SELECT version ->> 'name' AS version, string_to_array(split_part(version ->> 'name', ' - ', 2), '.')::int[] AS numeric_order
   FROM   jsonb_array_elements(i.fields -> 'customfield_01') AS version
   ORDER  BY 2 DESC NULLS LAST
   LIMIT  1
   ) v ON true;

db<>fiddle here

参见: