【问题标题】:Create index on json field in PostgreSQL 9.2在 PostgreSQL 9.2 中的 json 字段上创建索引
【发布时间】:2012-09-06 12:59:40
【问题描述】:

我有一些带有 json 列的表,并希望在这些列上建立索引。但是,我得到了一个默认的运算符类 (http://www.postgresql.org/docs/9.2/static/sql-createopclass.html)。有人已经这样做了还是给了我一个替代方案?

要重现问题,请尝试:

>> create table foo (json json, id int);
CREATE TABLE
>> create index on foo (id);
CREATE INDEX
>> create index on foo (json);
ERROR:  data type json has no default operator class for access method "btree"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.

这同样适用于gistgil 索引。

有趣的是,当我尝试以下操作时,我没有收到错误消息:

>> create type "nested" as (json json, extra text);
CREATE TYPE
>> create table bar (id int, json nested);
CREATE TABLE
>> create index on bar (json);
CREATE INDEX

是因为没有为组件创建索引吗?

好的,主要问题是默认运算符。感谢您提供任何帮助或共享经验。 谢谢。

【问题讨论】:

    标签: json postgresql indexing postgresql-9.2


    【解决方案1】:

    JSON 或 XML 类型没有内部索引类型。该字段可以保存一个值,但它不能是索引 - 您需要使用 hstore 列或类似的辅助列。

    【讨论】:

      【解决方案2】:

      如果您想安装 PLV8 JavaScript 语言,有一个解决方法:

      http://people.planetpostgresql.org/andrew/index.php?/archives/249-Using-PLV8-to-index-JSON.html

      【讨论】:

        【解决方案3】:

        最适合我的情况的解决方案如下:

        我只是把 json 当作文本,并在文本上创建一个索引。

        >> create index on foo ((json::text));
        

        然后必须转换查询以使用索引。

        解释显示是否使用了索引。

        >> explain select * from foo where json::text = 'foo';
        

        【讨论】:

          猜你喜欢
          • 2012-09-16
          • 1970-01-01
          • 2013-07-22
          • 2021-08-20
          • 2016-03-12
          • 1970-01-01
          • 2015-06-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多