Using Postgres 9.4, I want to create an index on a json column that will be used when searching on specific keys within the column.
For example I have an 'farm' table with a json column 'animals'.
The animals column has json objects of the general format:
'{"cow": 2, "chicken": 11, "horse": 3}'
I have tried a number of indexes (separately):
create INDEX animal_index ON farm ((animal ->> 'cow'));
create INDEX animal_index ON farm using gin ((animal ->> 'cow'));
create INDEX animal_index ON farm using gist ((animal ->> 'cow'));
I want to run queries like:
SELECT * FROM farm WHERE (animal ->> 'cow') > 3;
and have that query use the index.
When I run this query:
SELECT * FROM farm WHERE (animal ->> 'cow') is null;
then the (1) index works, but I can't get any of the indexes to work for the inequality.
Is such an index possible?
The farm table contains only ~5000 farms, but some of them contain 100s of animals and the queries simply take too long for my use case. An index like this is the only method I can think of for speeding this query up, but perhaps there is another option.
See Question&Answers more detail:os