Expand multiple rows result of `jsonb_array_elements` to tsvector inside a PL/pgSQL procedure

試著忘記壹切 提交于 2019-12-13 06:33:09

问题


overflowers,

I have a JSON array items like this (PostgreSQL 9.4):

[{name: "foo"},
 {name: "bar"},
 {name: "baz"}]

What I want is to concatenate all item's name into a tsvector-typed column so that I can create index on that column.

And if I run:

SELECT to_tsvector(array_to_string(array(SELECT jsonb_array_elements(items)->>'name' FROM store), ','))

I can get an expected result: 'foo': 1 'bar': 2 'baz': 3

But I got stuck at something like this:

CREATE OR REPLACE FUNCTION update_tsv()
RETURNS TRIGGER AS $$
BEGIN
    NEW.tsv = to_tsvector(jsonb_array_elements(NEW.items)->>'name');
    RETURN NEW;
END;
$$ language 'plpgsql';

The to_tsvector complains about multiple rows.

A sqlfiddle is attached.

Any help will be extremely appreciated!


回答1:


Would you try like this:

CREATE OR REPLACE FUNCTION update_tsv()
RETURNS TRIGGER AS $$
BEGIN
    NEW.tsv = to_tsvector(array_to_string(array( select json_array_elements(NEW.items)->>'name' ),' '));
    RETURN NEW;
END;
$$ language 'plpgsql';


来源:https://stackoverflow.com/questions/31699645/expand-multiple-rows-result-of-jsonb-array-elements-to-tsvector-inside-a-pl-pg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!