194

In PostgreSQL 9.3 Beta 2 (?), how do I create an index on a JSON field? I tried it using the -> operator used for hstore but got the following error:

 CREATE TABLE publishers(id INT, info JSON);
 CREATE INDEX ON publishers((info->'name'));

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.

2
  • 12
    "Where's the question?" - IN the title Commented Jul 23, 2013 at 11:01
  • 3
    In future please take a look at stackoverflow.com/tags/postgresql/info, the "asking better questions" section; it might help get better answers sooner with fewer annoying questions. Commented Jul 23, 2013 at 11:42

1 Answer 1

329

Found:

CREATE TABLE publishers(id INT, info JSON); 
CREATE INDEX ON publishers((info->>'name'));

As stated in the comments, the subtle difference here is ->> instead of ->. The former one returns the value as text, the latter as a JSON object.

Sign up to request clarification or add additional context in comments.

13 Comments

Just in case you are looking for the difference: It is ->> instead of ->. The former one returns the value as text, the latter one returns a JSON object.
The double-parentheses are also important.
@Jac_opo It extracts them as TEXT, though. If you want to do integer comparisons instead of string comparisons, you have to add a cast: ((info->>'name')::INT).
Works also for unique indexes: CREATE UNIQUE INDEX ON publishers((info->>'name'));
If you want to create an index on a field inside a sub-object of your JSON column, thanks to @DanielRikowski I figured out I needed to do create index idx_name on table_name ((json_column->'child_obj'->>'child_obj_field')); We first need to use -> to get the JSON object and then ->> to get the child object value as text.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.