【问题标题】:Substring search on JSON data (ERROR: cannot extract element from a scalar)对 JSON 数据的子字符串搜索(错误:无法从标量中提取元素)
【发布时间】:2017-03-14 17:37:30
【问题描述】:

我一直在研究 this tutorialthis example 试图找到一种高效的方式来通过 JSON (

例如,我有这样的数据:

CREATE TABLE public.foo
(
  row_id SERIAL PRIMARY KEY,
  data json
);

INSERT INTO foo VALUES (1,
  '{ "name": "Book the First", "author": "Bob", "text_entry": "White Cow Walked Over the Moon" } ');
INSERT INTO foo VALUES (2,
  '{ "name": "Book the Second", "author": "Charles", "text_entry": "Humptey Dumptey sat on the Moon" } ');
INSERT INTO foo VALUES (3,
  '{ "name": "Book the Third", "author": "Jim", "text_entry": "Red Fox jumped over Brown Dog" } ');

我正在寻找一种方法来仅搜索“text_entry”并返回任何具有子字符串“the Moon”的情况(在这种情况下,它将是 id = 1 & 2)。预期回报:

text_entry
"White Cow Walked Over the Moon" ## has the substring "the Moon"
"Humptey Dumptey sat on the Moon" ## has the substring "the Moon"

到目前为止,我的查询如下所示:

    SELECT data->'text_entry'->'%the Moon%' AS query FROM foo;

ERROR:  cannot extract element from a scalar
********** Error **********

有什么优雅的方法可以查询 JSON/B 中的子字符串吗?

【问题讨论】:

    标签: json regex postgresql jsonb


    【解决方案1】:

    我正在寻找一种仅搜索“text_entry”并返回任何具有子字符串“the Moon”的案例的方法

    SELECT data->>'text_entry' as query
    FROM foo
    WHERE data->>'text_entry' LIKE '%the Moon%';
    

    ->

    query              
    ---------------------------------
    White Cow Walked Over the Moon
    Humptey Dumptey sat on the Moon
    (2 rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 2020-10-06
      • 2020-11-07
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多