F
F
Flaker2015-10-24 21:04:38
PHP
Flaker, 2015-10-24 21:04:38

How to make an index on a JSONB field in PostgreSQL?

There is a jsonb properties field .
Some entries in properties have a price object .
That is, there is such a json object:

{
    price: {
        id: 222,
        val: 150
    }
}

I want to speed up this SELECT:
SELECT * FROM "TABLE_NAME" WHERE (properties #>> '{price, val}')::int BETWEEN '100' AND'200'

I create an index like this:
CREATE INDEX price_btree_idx ON estates USING btree (((properties -> 'price') -> 'val'))

There are no changes, because apparently the base considers that the val field is text.
How to make such an index?
UPD:
The "properties" field itself is already indexed:
CREATE INDEX properties_gin_idx ON estates USING gin (properties jsonb_path_ops)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RedHog, 2018-05-31
@RedHog

I'll be a necroposter
Apparently you need to create an index as described here - https://stackoverflow.com/questions/36075918/postg...
i.e. CREATE INDEX price_btree_idx ON estates ((((properties -> 'price') -> ' val'))::int)

D
Dmitry Donkovtsev, 2015-10-25
@Demetriy

Unfortunately, I don't have postgresql at hand to check, but try to make a functional index on the price field, I think there should be such an opportunity.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question