【问题标题】:does django db_index=True index null value?django db_index=True 索引空值吗?
【发布时间】:2020-04-16 18:55:48
【问题描述】:

例如,如果我有一个字段名称 slug = models.CharField(null=True, db_index=True,max_length=50) 并且如果将 slug 留空,则同时保存数据。数据库会索引这个保存的空值吗?

【问题讨论】:

  • 这取决于数据库。对于 PostgreSQL,据我所知,它确实将其保存在位图中,而不是 btree 中,但是是的,它已被索引,因此应该加强搜索 null 值:patshaughnessy.net/2014/11/11/…
  • @WillemVanOnsem 你对 PostgreSQL 来说是对的,它确实从 8.3 版(12 岁)开始索引 null

标签: django postgresql django-models indexing


【解决方案1】:

是的,Postgresql 确实索引 NULL 值。

这是一个小测试用例:

select version();
                                                  version                                                  
-----------------------------------------------------------------------------------------------------------
 PostgreSQL 9.5.21 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
(1 row)

create table t(c1 serial, c2 text);
CREATE TABLE

insert into t(c2) select generate_series(1,1000000);
INSERT 0 1000000

create index on t(c2);
CREATE INDEX

analyze t;
ANALYZE

update t set c2=null where c1=123456;
UPDATE 1

explain analyze select count(*) from t where c2 is null;
                                                      QUERY PLAN                                                

----------------------------------------------------------------------------------------------------------------
-------
 Aggregate  (cost=5.76..5.77 rows=1 width=0) (actual time=0.009..0.009 rows=1 loops=1)
   ->  Index Only Scan using t_c2_idx on t  (cost=0.42..5.76 rows=1 width=0) (actual time=0.006..0.006 rows=1 lo
ops=1)
         Index Cond: (c2 IS NULL)
         Heap Fetches: 1
 Planning time: 0.271 ms
 Execution time: 0.035 ms
(6 rows)

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 2019-12-30
    • 2019-05-26
    • 1970-01-01
    • 2021-01-10
    • 2017-05-25
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多