如何在 PostgreSQL 中索引多语言实体

How to index a multilanguage entity in PostgreSQL

我在这里创建 table product_feature_text,与 table product 有 1:N 关系。由于应用程序必须支持多种用户语言,因此添加了 lang_code 列以将英语文本与其他语言文本区分开来。

由于我想以每种语言的字母顺序展示产品功能,因此我创建了四个部分索引及其特定 collate。预计所有产品功能在所有四种语言中都具有 title,例如,将有 25% 的行具有 lang_code = 'ES'

这是对真实案例的过度简化,但足以描述情况。

create table product_feature_text (
  id          bigint generated by default as identity primary key,

  -- reference to the parent product
  product_id  bigint not null,

  -- language dependent columns
  lang_code   char(2),
  title       varchar,

  foreign key (product_id) references product (id)
);

create index on product_feature_text (title collate "en-US") where lang_code = 'EN';
create index on product_feature_text (title collate "es-ES") where lang_code = 'ES';
create index on product_feature_text (title collate "fr_FR") where lang_code = 'FR';
create index on product_feature_text (title collate "de_DE") where lang_code = 'DE';

这是该案例的最佳索引方法吗?

来自评论的附录:典型的查询是

select text
from product_feature
where product_id = 1024
   and lang_code = 'FR'
order by title collate "fr_FR"

其中 product_id 可以是任何东西。

这取决于索引的预期用途。

如果您想将它们用于

SELECT ... FROM product_feature_text
WHERE lang_code = 'EN' AND ...
ORDER BY title COLLATE "en-US";

您的索引可能会有用。

此外,如果您的查询看起来像

WHERE product_feature_text > 'bhd'  COLLATE ...

可能会有帮助。

但是,对于我能想到的大多数情况,排序无关紧要的单个索引会更好。

对于附录中的查询,完美索引为:

CREATE INDEX ON product_feature (product_id, title COLLATE "fr_FR")
   WHERE lang_code = FR';