从Postgres NOSQL / json数据中搜索并选择

时间:2015-03-14 14:38:50

标签: json postgresql

任何人都可以帮我搜索Postgres数据库的json数据类型。

我有一个表transactions并且包含以下类似值数组:

column: "data" datatype: json

单一演示交易:

{
    "id": "tran_54645bcb98ba7acfe204",
    "amount": 4200,
    ...
    "fees": [
        {
            "type": "application",
            "application": "app_1d70acbf80c8c35ce83680715c06be0d15c06be0d",
            "payment": "pay_917018675b21ca03c4fb",
            "amount": 420,
            "currency": "EUR",
            "billed_at": null
        }
    ]
}

嵌套交易清单:

[
    {
        "id": "tran_54645bcb98ba7acfe204",
        "amount": 4200,
        "fees": [
            {
                "type": "application",
                "application": "app_1d70acbf80c8c35ce83680715c06be0d15c06be0d",
                "payment": "pay_917018675b21ca03c4fb",
                "amount": 420,
                "currency": "EUR",
                "billed_at": null
            }
        ]
    },
    {
        "id": "tran_98645bcb98ba7acfe204",
        "amount": 4200,
        "fees": [
            {
                "type": "application",
                "application": "app_1d70acbf80c8c35ce83680715c06be0d15c06be0d",
                "payment": "pay_917018675b21ca03c4fb",
                "amount": 120,
                "currency": "AUD",
                "billed_at": null
            }
        ]
    }
]

如果我希望获得amount > 300以及currency = EUR的所有交易,我将如何获得这些交易? 我是Postgres的新手,所以需要帮助理解Postgres nosql的查询构建,特别是PHP

1 个答案:

答案 0 :(得分:4)

仅适用于嵌套JSON数组中的单个元素:

SELECT *
FROM   transactions
WHERE (data #>> '{fees,0,amount}')::numeric > '300'
AND   (data #>> '{fees,0,currency}') = 'EUR';

对于具有更多元素的数组,您需要做更多 有关JSON Functions and Operators

的手册

由于您使用的是Postgres 9.4:使用jsonb会有更好的选项,特别是对于多个数组元素:

要在评论中获得您要求的金额:

SELECT sum((data #>> '{fees,0,amount}')::numeric) AS sum_amount
FROM   ...