0%

Django:Postgresql BTree索引

使用db_index参数创建btree索引,当字段类型是varchartext时会额外创建like index, 具体参见:DatabaseSchemaEditor._create_like_index_sql

1
2
class BTreeIdx(models.Model):
content = models.CharField(max_length=200, db_index=True)
1
2
3
4
5
6
7
8
9
CREATE INDEX btree_idx_btreeidx_content_511ce749
ON public.btree_idx_btreeidx USING btree
(content COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;

CREATE INDEX btree_idx_btreeidx_content_511ce749_like
ON public.btree_idx_btreeidx USING btree
(content COLLATE pg_catalog."default" varchar_pattern_ops ASC NULLS LAST)
TABLESPACE pg_default;

创建btree索引:

1
2
3
4
5
6
7
class BTreeIdx(models.Model):
content = models.CharField(max_length=200)

class Meta:
indexes = [
BTreeIndex(fields=['content'])
]
1
2
3
4
CREATE INDEX btree_idx_b_content_93bf39_btree
ON public.btree_idx_btreeidx USING btree
(content COLLATE pg_catalog."default" ASC NULLS LAST)
TABLESPACE pg_default;

创建btree索引,opclass=varchar_pattern_ops

1
2
3
4
5
6
7
class BTreeIdx(models.Model):
content = models.CharField(max_length=200)

class Meta:
indexes = [
BTreeIndex(name='btree_idx_like_idx', fields=['content'], opclasses=['varchar_pattern_ops'])
]
1
2
3
4
CREATE INDEX btree_idx_like_idx
ON public.btree_idx_btreeidx USING btree
(content COLLATE pg_catalog."default" varchar_pattern_ops ASC NULLS LAST)
TABLESPACE pg_default;