3

我有以下观点:

CREATE VIEW public.profiles_search AS
    SELECT
        profiles.id,
        profiles.bio,
        profiles.title,
        (
            setweight(to_tsvector(profiles.search_language::regconfig, profiles.title::text), 'B'::"char") ||
            setweight(to_tsvector(profiles.search_language::regconfig, profiles.bio), 'A'::"char") ||
            setweight(to_tsvector(profiles.search_language::regconfig, profiles.category::text), 'B'::"char") ||
            setweight(to_tsvector(profiles.search_language::regconfig, array_to_string(profiles.tags, ',', '*')), 'C'::"char")
        ) AS document
    FROM profiles
    GROUP BY profiles.id;

但是,如果profiles.tags 为空document,则即使其余字段(标题、简历和类别)包含数据也是如此。

是否有某种方法可以使该字段成为可选字段,以使其具有空数据不会导致空文档?

4

1 回答 1

2

这似乎是常见的字符串连接问题 - 连接一个NULL值会产生整个结果NULL

这里建议您始终为任何输入提供默认值coalesce()

UPDATE tt SET ti =
    setweight(to_tsvector(coalesce(title,'')), 'A')    ||
    setweight(to_tsvector(coalesce(keyword,'')), 'B')  ||
    setweight(to_tsvector(coalesce(abstract,'')), 'C') ||
    setweight(to_tsvector(coalesce(body,'')), 'D');

如果您不想为复杂数据类型提供默认值(如coalesce(profiles.tags, ARRAY[]::text[])@approxiblue 建议的那样),我怀疑您可以简单地执行以下操作:

CREATE VIEW public.profiles_search AS
    SELECT
        profiles.id,
        profiles.bio,
        profiles.title,
        (
            setweight(to_tsvector(profiles.search_language::regconfig, profiles.title::text), 'B'::"char") ||
            setweight(to_tsvector(profiles.search_language::regconfig, profiles.bio), 'A'::"char") ||
            setweight(to_tsvector(profiles.search_language::regconfig, profiles.category::text), 'B'::"char") ||
            setweight(to_tsvector(profiles.search_language::regconfig, coalesce(array_to_string(profiles.tags, ',', '*'), '')), 'C'::"char")
        ) AS document
    FROM profiles
    GROUP BY profiles.id;
于 2018-07-20T08:59:50.717 回答