【问题标题】:Index for bit comparisons in postgreSQL (and other databases)postgreSQL(和其他数据库)中位比较的索引
【发布时间】:2015-11-19 10:17:38
【问题描述】:

是否可以通过flags 上的索引来加快如下查找速度,其中5 可以是任意数字?

select * from user where flags & 5 > 0

flags 是一个整数列,其背后的想法是将不同的布尔属性存储在一个列中。所以对于这个例子,它可能是:

flags bit | 1        | 2      | 4                     | 8        | ...
meaning   | is admin | banned | password needs change | whatever | ...

所以可以通过上面的select语句找到需要更改密码的admin用户(即使他也设置了其他标志)。

对于 postgreSQL,我可以为上述查询添加这样的表达式索引:

create index index_name on user ((flags & 5 > 0))

但是我必须为每个标志组合创建一个索引,因为上述索引仅适用于值 flags & 5

那么有没有索引可以加速flags & any_number > 0

我知道我可以为每个标志使用不同的布尔列(我觉得有 > 50 个标志很乱)或 postgreSQL 位数据类型(我假设有一个索引类型),但我特别感兴趣如果有办法在整数列上为上述用例建立索引。

【问题讨论】:

    标签: postgresql indexing boolean bitwise-operators


    【解决方案1】:

    位数据类型用于在单个列中保存多个位,因此这比使用数字类型更合适。

    您可能可以对表达式进行索引:

    create index index_my_table_is_admin
    on my_table (case flags & 5 when 0 then false else true end)
    

    然后查询:

    select ...
    from   ...
    where  (case flags & 5 when 0 then false else true end) = 't';
    

    但我倾向于创建一个视图:

    create view ...
    as
    select ...
           (case flags & 5 when 0 then false else true end) is_admin
           ...
    from   my_table;
    

    我想这是一个有趣的智力练习,但我只想使用一组布尔值。

    【讨论】:

    • 感谢您的回答。我认为在 postgreSQL 中建立索引的方式可以是create index index_name on user ((flags & 5 > 0)) - 还是我错了?然后选择可能就像我的问题一样(不需要case,更简单的语法)。
    猜你喜欢
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 2018-05-20
    • 2013-02-19
    • 2016-11-12
    • 2011-07-05
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多