Create index on json field in PostgreSQL 9.2

社会主义新天地 提交于 2019-12-09 18:58:52

问题


I have a few tables with json columns and would like to build an index on these columns. However, I get a default operator class (http://www.postgresql.org/docs/9.2/static/sql-createopclass.html). Has someone already done that or give me an alternative?

To reproduce the problem, try:

>> 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.

The same applies for gist or gil indexes.

Interestingly, I don't get the error when I try the following:

>> 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

Is that because no index is created for the components?

Okay, the main issue is the default operator. Any help or shared experience with that is appreciated. Thanks.


回答1:


There is a workaround for this if you feel like installing the PLV8 JavaScript language:

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




回答2:


The solution that works best for my case is the following:

I simply treat json as text and create an index on the text.

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

A query would then have to be transformed so that it uses the index.

Explain reveals whether the index is used or not.

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



回答3:


there are no internal index type for JSON or XML type. This fields can hold a values, bat it cannot be indexes - you need to auxiliary columns with hstore columns or similar.



来源:https://stackoverflow.com/questions/12406269/create-index-on-json-field-in-postgresql-9-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!