Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index JSON data in PostgreSQL 9.2?

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.

like image 390
ankurvsoni Avatar asked Sep 25 '12 04:09

ankurvsoni


People also ask

How do I query JSON data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

Can you store JSON data in Postgres?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.

Is Jsonb faster than JSON?

Json processes input faster than jsonb as there is no conversion involved in this. Jsonb converts the JSON data into the binary form so it has slightly slower input due to the binary conversion overhead. There is no change in the Schema design while working with JSON.


Video Answer


1 Answers

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

like image 56
Steven Garcia Avatar answered Oct 15 '22 23:10

Steven Garcia