【问题标题】:PostgreSQL text search with an index within a Jsonb array使用 Jsonb 数组中的索引进行 PostgreSQL 文本搜索
【发布时间】:2020-05-04 20:32:04
【问题描述】:

给定以下数据集:

-- Create random table
CREATE TABLE sample (
    id serial primary key,
    content jsonb
);

-- Insert sample rows
INSERT INTO sample (content)
VALUES 
    ('{"text": ["Lorem ipsum dolor sit amet","consectetur adipiscing elit","sed do eiusmod tempor incididunt","ut labore et dolore magna aliqua"]}'), 
    ('{"text": ["Ut enim ad minim veniam","quis nostrud exercitation ullamco laboris","nisi ut aliquip ex ea commodo consequat","Duis aute irure dolor in reprehenderit","voluptate velit esse cillum dolore"]}'), 
    ('{"text": ["eu fugiat nulla pariatur","Excepteur sint occaecat cupidatat","non proident, sunt in culpa qui","officia deserunt mollit anim id est laborum"]}')
;

content 是一个 JSONB 列,其中包含一个键 text,它是一个 Json 文本数组。

我希望能够使用ILIKE 或使用索引在此文本中的类似功能进行搜索。

从功能上讲,这是可行的,这就是我想做的:

WITH ctr AS (
    SELECT id, jsonb_array_elements_text((content->>'text')::jsonb) as mytext
    FROM sample
)
SELECT id
FROM ctr
WHERE mytext ILIKE '%qui%';

 id 
----
  2
  2
  3
(3 rows)

是否有使用索引获得相同输出的解决方案?我正在寻找一个非常大的数据集。

似乎无法使用三元组索引 (ERROR: operator class "gist_trgm_ops" does not accept data type jsonb)

【问题讨论】:

  • 规范化你的数据,然后你就可以正确索引它

标签: postgresql postgresql-10 trigram


【解决方案1】:

你可以使用正则表达式

create index idx_name on sample ((content->>'text'));

select sample.*
from sample
where content->>'text' ~ ' qui';

select sample.* 
from sample, jsonb_array_elements_text(content->'text') many(elem)
where elem ~ ' qui';

此外,从 Postgresql 版本 12+ 起,您可以使用“like_regex”在您的 JSONB 列中进行搜索。

https://www.postgresql.org/docs/current/functions-json.html

查看Selecting for a Jsonb array contains regex matchHow to create index on json field in Postgres 9.3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 2017-09-11
    • 2015-08-15
    • 2017-04-12
    • 1970-01-01
    • 2019-08-25
    • 2017-10-25
    • 2017-04-23
    相关资源
    最近更新 更多