sql - 查找所有带有希伯来名字的记录

标签 sql regex postgresql performance hebrew

我有一个带有用户表的 postgresql 数据库,其中每个用户都有一个名称(在 unicode 中)。我想查找名称中至​​少包含一个希伯来字符的所有用户。我想过使用 regex ,例如

select * from users
where name ~ '[א-ת]';

有没有比正则表达式更有效的方法?我在名称列上有一个 B 树索引。

更新

pg_trgm 模块中使用不同的索引作为suggested通过@FuzzyTree

      B-tree GIST  GIN
user  0.04   0.04  0.03
sys   0.02   0.04  0.01
total 0.06   0.08  0.04

关于磁盘大小,GIN 索引是 GIST 的 0.2 倍,B 树的 0.8 倍。所以,我们在这里有一个赢家,至少对于我的用例而言。 YMMV(例如,我没有对索引创建和更新进行基准测试)。版本:postgres 9.6。

最佳答案

一个选项是创建一个 bool 列,即 is_hebrew_name您可以使用正则表达式更新一次并创建一个常规索引。

如果您不想添加另一列并且您运行的是 v9.3 或更高版本,请考虑使用 pg_trgm模块创建 GINGIST索引 name

CREATE EXTENSION pg_trgm;
CREATE INDEX trgm_idx ON users USING GIST (name gist_trgm_ops);

The pg_trgm module provides GiST and GIN index operator classes that allow you to create an index over a text column for the purpose of very fast similarity searches. These index types support the above-described similarity operators, and additionally support trigram-based index searches for LIKE, ILIKE, ~ and ~* queries.

The index search works by extracting trigrams from the regular expression and then looking these up in the index. The more trigrams that can be extracted from the regular expression, the more effective the index search is. Unlike B-tree based searches, the search string need not be left-anchored.

For both LIKE and regular-expression searches, keep in mind that a pattern with no extractable trigrams will degenerate to a full-index scan.

The choice between GiST and GIN indexing depends on the relative performance characteristics of GiST and GIN, which are discussed elsewhere.

有关详细信息,请参阅 https://www.postgresql.org/docs/9.6/static/pgtrgm.html

关于sql - 查找所有带有希伯来名字的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46515082/

相关文章:

sql - 最早的记录差异?

c# - 使用以点开头的正则表达式匹配字符串,不包括 double

mysql - 我有一个 Excel 中的 VBA 将数据传输到 MySQL,但是我对日期有疑问

Mysql从父表中选择条目与子表中的特定条目多对多关系

mysql - 哪个先被删除?主键还是外键?

regex - 删除/替换 bash 中的 html 标签

regex - 使用正则表达式的 Google Analytics(分析)内容分组

sql - 简单的正则表达式来过滤掉前缀和后缀字符

sql - 如何在 PostgreSQL 中快速将二维数组嵌套到一维数组中?

ruby-on-rails - 按关联表的项目计数排序