【问题标题】:Django hstore field and indexDjango hstore 字段和索引
【发布时间】:2016-01-06 02:56:21
【问题描述】:

我正在使用带有新 hstore 字段的 Django 1.8 和 postgresql。我想对我的 hstore 字段中的值应用索引。但是,阅读 postgres 的文档后,我觉得 btree 索引不是要走的路,而 gin 索引更合适,因为我的 hstore 字段中有许多值,都指的是同一条记录。使用 pgAdmin 我注意到如果我将 db_index=True 添加到我的 hstore 字段中,它会创建一个 btree 索引。 我的问题是:

  1. btree 索引在这里真的没用吗?我不应该使用它吗?
  2. 我使用原始 sql(在我的迁移中植入)创建了一个 gin 索引,我想知道这是否足够,以及我的 orm 过滤器/获取方法是否有效,或者我是否也必须覆盖这些方法

原始 SQL 看起来像这样:

SELECT * from transaction WHERE ("transaction"."hstorefield" -> 'service_code') = somevalue

【问题讨论】:

  • 我建议这些天使用jsonb 和 PostgreSQL 9.4。我认为hstore 越来越成为一个遗留功能。至于索引,您需要显示我认为 ORM 运行的实际查询。
  • SELECT * from transaction WHERE ("transaction"."hstorefield" -> 'service_code') = somevalue

标签: python django postgresql indexing hstore


【解决方案1】:

GIN 很好,尽管它确实会大大减慢插入和更新速度。

CREATE INDEX "ix_hsfield" ON "transaction" USING GIN ("hstorefield");

如果您只需要加快对一个 hstore 键的查询,btree 是可能的,并且会更快一些(并且在使用大于/小于运算符的查询上效果更好)

CREATE INDEX "ix_hsfieldkey" ON "transaction" ((hs_data -> 'service_code'));

如果键包含数字数据,并且您想与 where 子句中的数字进行比较(小于/大于),请确保将索引编写为:

CREATE INDEX "ix_hsfieldkey" ON "transaction" ((hs_data -> 'service_code')::numeric);

-- the index won't be used unless the field used in the queries match the index:
SELECT * from transaction WHERE ("transaction"."hstorefield" -> 'service_code')::numeric = somevalue

【讨论】:

    猜你喜欢
    • 2016-12-16
    • 2014-10-15
    • 1970-01-01
    • 2018-01-01
    • 2015-06-15
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2015-05-04
    相关资源
    最近更新 更多