在 jsonb 数组上使用过滤器进行查询,查找嵌套的键/值

问题描述 投票:0回答:1

我有下表:

create table payment_records (
  id         uuid        not null primary key,
  record     jsonb       not null,
  created_at timestamptz default now() not null
);

典型的条目将包含以下记录列的 json

{
    "records": [{
            "recordId": "5f5d8e39-1b57-4a05-9bdd-cb5e957768fc",
            "payment": {
                "booked": true,
                "errors": [],
                "return": null,
                "status": "Processed"
                "latestStatusChangedTimestamp": "2024-10-30T07:43:40.5+00:00"
            },
            "timestamp": "2024-10-30T07:43:50.557939Z",
        }, {
            "recordId": "c3e049e8-a3e3-4e80-be63-bdf58e121c8a",
            "payment": {
                "booked": true,
                "errors": [],
                "return": null,
                "status": "Processed",
                "latestStatusChangedTimestamp": "2024-10-30T07:43:40.5+00:00"
            },
            "timestamp": "2024-10-30T07:43:50.557941Z"
        }, {
            "recordId": "abf35109-7d5f-4ba3-9f6e-2c6d1a305134",
            "payment": {
                "booked": true,
                "errors": [],
                "return": null,
                "status": "Processed",
                "latestStatusChangedTimestamp": "2024-10-30T07:43:40.5+00:00"
            },
            "timestamp": "2024-10-30T07:43:50.5579416Z"
        }
    ]
}

我需要一个查询来返回

recordId
与我的搜索条件匹配的任何条目,例如
recordId='abf35109-7d5f-4ba3-9f6e-2c6d1a305134'

尝试了一些查询,但没有成功。

arrays postgresql jsonb
1个回答
0
投票

假设

jsonb
柱的内部结构如图所示稳定,带有
@>
的过滤器可以做到这一点:

SELECT *
FROM   payment_records
WHERE  record @> '{"records": [{"recordId":"abf35109-7d5f-4ba3-9f6e-2c6d1a305134"}]}';

或者,在最近的版本中,使用

@?
运算符:

WHERE  record @? '$.records[*] ? (@."recordId" == "abf35109-7d5f-4ba3-9f6e-2c6d1a305134")';

小提琴

都可以使用索引。参见:

© www.soinside.com 2019 - 2024. All rights reserved.