select 在 postgresql 中查询 >= jsonb 列值

select query for >= jsonb column value in postgresql

我有一个带有 jsonb 格式列 tags in table 的 postgres 数据库。我正在尝试查询 confidence >= 50.

所在的行

我不确定如何索引到预测列表以检查置信度。我试过下面的查询,它执行时没有错误,但没有 return 任何行。

select * from mytable where (tags->>'confidence')::int >= 50;

这是一个示例行 jsonb

{
    "predictions": [
        {
            "label": "Shopping",
            "confidence": 91
        },
        {
            "label": "Entertainment",
            "confidence": 4
        },
        {
            "label": "Events",
            "confidence": 2
        }
    ]
}

您需要通过取消嵌套数组来规范化数据,然后您可以

select p.d
from mytable mt
  cross join lateral jsonb_array_elements(mt.tags -> 'predictions') as p(d)
where (p.d ->> 'confidence')::int >= 50;

对于上面的样本数据,即returns:

{"label": "Shopping", "confidence": 91}

在线示例:http://rextester.com/CBIAR76462