【问题标题】:Querying Postgres 9.6 JSONB array of objects查询 Postgres 9.6 JSONB 对象数组
【发布时间】:2018-03-29 03:08:03
【问题描述】:

我有下表:

CREATE TABLE trip
(
    id SERIAL PRIMARY KEY ,
    gps_data_json jsonb NOT NULL
);

gps_data_json 中的 JSON 包含一个行程对象数组,其中包含以下字段(示例数据如下):

  • 模式
  • 时间戳
  • 纬度
  • 经度

我正在尝试获取包含特定“模式”的所有行。

SELECT * FROM trip
where gps_data_json ->> 'mode' = 'WALK';

我很确定我使用了错误的 ->> 运算符,但我不确定谁告诉查询 JSONB 字段是一个对象数组?

样本数据:

INSERT INTO trip (gps_data_json) VALUES
  ('[
      {
        "latitude": 47.063480377197266,
        "timestamp": 1503056880725,
        "mode": "TRAIN",
        "longitude": 15.450349807739258
      },
      {
        "latitude": 47.06362533569336,
        "timestamp": 1503056882725,
        "mode": "WALK",
        "longitude": 15.450264930725098
      }
    ]');

INSERT INTO trip (gps_data_json) VALUES
  ('[
      {
        "latitude": 47.063480377197266,
        "timestamp": 1503056880725,
        "mode": "BUS",
        "longitude": 15.450349807739258
      },
      {
        "latitude": 47.06362533569336,
        "timestamp": 1503056882725,
        "mode": "WALK",
        "longitude": 15.450264930725098
      }
    ]');

【问题讨论】:

    标签: postgresql jsonb postgresql-9.6


    【解决方案1】:

    问题出现是因为->>操作符不能遍历数组:

    • 首先使用 json_array_elements 函数解除 json 数组的嵌套;
    • 然后使用运算符进行过滤。

    以下查询可以解决问题:

    WITH 
    A AS (
    SELECT
        Id
       ,jsonb_array_elements(gps_data_json) AS point
    FROM trip
    )
    SELECT *
    FROM A
    WHERE (point->>'mode') = 'WALK';
    

    【讨论】:

    【解决方案2】:

    如果您只想要包含查询值的对象,则取消嵌套数组可以正常工作。 以下检查包含并返回完整的 JSONB:

    SELECT * FROM trip
    WHERE gps_data_json @> '[{"mode": "WALK"}]';
    

    另见Postgresql query array of objects in JSONB field

    【讨论】:

      【解决方案3】:
      select *  from
          (select id, jsonb_array_elements(gps_data_json) point from trip where id = 16) t
      where point @> '{"mode": "WALK"}';
      

      在我的表中,id = 16 是为了确保特定行仅是 jsonb-array 数据类型。由于其他行数据只是 JSONB 对象。所以你必须先过滤掉 jsonb-array 数据。否则:ERROR: cannot extract elements from an object

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-03
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多