6

Does anyone know how to create index on JSON data in PostgreSQL 9.2?

Example data:

[
  {"key" : "k1", "value" : "v1"},
  {"key" : "k2", "value" : "v2"}
]

Say if I want to index on all the keys how to do that?

Thanks.

3
  • Is there a reason why you're storing plain JSON and not separating into table columns? And any reason you don't accept answers? Commented Sep 25, 2012 at 4:57
  • I am evaluating the JSON type support PostgreSQL 9.2 and hence the need. I don't see a setting that disables receiving answers? Is there something like that? Commented Sep 25, 2012 at 5:07
  • Maybe take a look at: people.planetpostgresql.org/andrew/index.php?/archives/… Commented Sep 25, 2012 at 5:12

3 Answers 3

3

You are much better off using hstore for indexed fields, at least for now.

CREATE INDEX table_name_gin_data ON table_name USING GIN(data);

You can also create GIST indexes if you are interested in fulltext search. More info here: http://www.postgresql.org/docs/9.0/static/textsearch-indexes.html

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

Comments

2

Currently there are no built-in functions to index JSON directly. But you can do it with a function based index where the function is written in JavaScript.

See this blog post for details: http://people.planetpostgresql.org/andrew/index.php?/archives/249-Using-PLV8-to-index-JSON.html

There is another blog post from which talks about JSON and how it can be used with JavaScript: http://www.postgresonline.com/journal/archives/272-Using-PLV8-to-build-JSON-selectors.html

3 Comments

But in my case - I need to index everything in the json object. Is there a way to do that?
@ankurvsoni: no, I don't think so.
Note that since 9.3 there are JSON Functions and Operators.
0

This question is a little old but I think the selected answer is not really the ideal one. To index json (the property values inside json text), we can use expression indexes with PLV8 (suggested by @a_horse_with_no_name).

Craig Kerstein does a great job of explaining/demonstrating:

http://www.craigkerstiens.com/2013/05/29/postgres-indexes-expression-or-functional-indexes/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.