使用 Postgres 查询 JSONB

Querying JSONB using Postgres

我正在尝试通过查询获取 JSON 中的一个元素。

我正在使用 Groovy、Postgres 9.4 和 JSONB。

这是我的JSON

{
    "id": "${ID}",
    "team": {
        "id": "123",
        "name": "Shire Soldiers"
    },
    "playersContainer": {
        "series": [
            {
                "id": "1",
                "name": "Nick",
                "teamName": "Shire Soldiers",
                "ratings": [
                    1,
                    5,
                    6,
                    9
                ],
                "assists": 17,
                "manOfTheMatches": 20,
                "cleanSheets": 1,
                "data": [
                    3,
                    2,
                    3,
                    5,
                    6
                ],
                "totalGoals": 19

            },

            {

                "id": "2",
                "name": "Pasty",
                "teamName": "Shire Soldiers",
                "ratings": [
                    6,
                    8,
                    9,
                    10
                ],
                "assists": 25,
                "manOfTheMatches": 32,
                "cleanSheets": 2,
                "data": [
                    3,
                    5,
                    7,
                    9,
                    10
                ],
                "totalGoals": 24

            }
        ]
    }
}

我想通过 ID 获取系列数组中的各个元素,我目前正在使用下面的查询

select content->'playersContainer'->'series' from site_content 
where content->'playersContainer'->'series' @> '[{"id":"1"}]';

然而,这让我又回到了 id 为 1 和 2 的元素

下面是我得到的

"[{"id": "1", "data": [3, 2, 3, 5, 6], "name": "Nick", "assists": 17, "ratings": [1, 5, 6, 9], "teamName": "Shire Soldiers", "totalGoals": 19, "cleanSheets": 1, "manOfTheMatches": 20}, {"id": "2", "data": [3, 5, 7, 9, 10], "name": "Pasty", "assists": 25, "r (...)"

谁能看出我错在哪里?我在这里看到了一些其他问题,但它们对此没有帮助。

content->'playersContainer'->'series' 是一个数组。如果要查找数组中的特定元素,请使用 jsonb_array_elements()

select elem
from site_content,
lateral jsonb_array_elements(content->'playersContainer'->'series') elem
where elem @> '{"id":"1"}';

Test it here.