如何在一个表中处理跨多种语言的全文搜索索引?

问题描述 投票:0回答:1

我在 Postgres 中有一个表,我在其中存储多种语言的文章。对于全文搜索,我有一个单独的列,可以使用 GIN 索引进行全文搜索。根据文章语言,我存储相应词典的相应正文:德语、英语、西班牙语等

但是,当我想要查询数据库时,我搜索的字典会产生显着的差异。实际上,我想查询所有语言,而不仅仅是特定语言。所以我很好奇如何才能实现这一目标。

这是我的桌子:

create table if not exists public.article
(
    id                        serial constraint "pk_article_id" primary key,
    title                     varchar(1024),
    body                      text,
    lang                      varchar(2),
    fts_dict                  regconfig generated always as (
                                  CASE
                                      WHEN ((lang)::text = 'en'::text) THEN 'english'::regconfig
                                      WHEN ((lang)::text = 'de'::text) THEN 'german'::regconfig
                                      WHEN ((lang)::text = 'es'::text) THEN 'spanish'::regconfig
                                      ELSE 'simple'::regconfig
                                      END) stored,
    fts_body                  tsvector generated always as (
                                  CASE
                                      WHEN ((lang)::text = 'en'::text) THEN to_tsvector('english'::regconfig, body)
                                      WHEN ((lang)::text = 'de'::text) THEN to_tsvector('german'::regconfig, body)
                                      WHEN ((lang)::text = 'es'::text) THEN to_tsvector('spanish'::regconfig, body)
                                      ELSE to_tsvector('simple'::regconfig, body)
                                      END) stored
);

这里是 GIN 索引:

create index if not exists idx_article_fts_body
    on public.article using gin (fts_body);

因此该表包含多种语言的文章。我有一个自动生成的列,根据原始语言,将正文存储为特定字典中的

tsvector

在搜索文章时,我发现字典很重要:

SELECT a.id, a.lang, a.title, a.body
FROM article a
         INNER JOIN summaries s ON a.id = s.article_id
WHERE a.fts_body @@ plainto_tsquery('german', 'Grünheide')

仅提供所有具有德语语言环境的文章,但不提供包含“Grünheide”的英语或西班牙语文章。

如果我想包含所有包含相同单词“grünheide”的英语或西班牙语文章,我需要另外查询相应的词典:

SELECT a.id, a.lang, a.title, a.body
FROM article a
         INNER JOIN summaries s ON a.id = s.article_id
WHERE a.fts_body @@ plainto_tsquery('english', 'Grünheide')

SELECT a.id, a.lang, a.title, a.body
FROM article a
         INNER JOIN summaries s ON a.id = s.article_id
WHERE a.fts_body @@ plainto_tsquery('spanish', 'Grünheide')

在查询中省略字典似乎默认为“simple”或“english”,这使得结果类似于我要求“english”。

我的问题是:我真的需要迭代所有字典类型(语言)并一次又一次地重新查询以获取包含特定术语的所有文章的完整列表吗?

或者还有其他我应该知道的技巧吗?

postgresql full-text-search
1个回答
0
投票

您必须在查询中使用与 ts_vector 相同的语言

SELECT a.id, a.lang, a.title, a.body
FROM article a
         INNER JOIN summaries s ON a.id = s.article_id
WHERE a.fts_body @@ plainto_tsquery(a.fts_dict, 'Grünheide')
© www.soinside.com 2019 - 2024. All rights reserved.