对JSON数据进行子字符串搜索(错误:无法从标量中提取元素)

时间:2017-03-14 17:37:31

标签: json regex postgresql jsonb

我一直在寻找this tutorialthis example试图通过JSON(< 9.5)/ JSONB(* 9.5)数据查找子字符串的高效方法。

例如,我有这些数据:

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"并返回任何具有子串"月亮" (在这种情况下,它将是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中的子串?

1 个答案:

答案 0 :(得分:0)

  

我正在寻找一种方法来搜索“text_entry”并返回任何具有子串“月亮”的案例

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)