我有以下视图:
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;
但是,如果profile.tags为空,则document
为空,即使其余字段(标题,简历和类别)包含数据也是如此。
是否有某种方法可以使该字段成为可选字段,以使其具有空数据不会导致文档为空?
答案 0 :(得分:2)
这似乎是常见的字符串连接问题-串联NULL
值会使整个结果NULL
。
Here,建议您始终为使用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');
如果您不想提供复杂数据类型的默认值(例如@approxiblue建议的coalesce(profiles.tags, ARRAY[]::text[])
),我怀疑您可以这样做:
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;