3

I have been trying to create an index on a jsonb document all morning but I can't see any benefit from the index.

My table:

CREATE TABLE modelling.triangle(id serial, data JSONB)

Here is my insert:

    INSERT INTO modelling.triangle(data)
    SELECT
    json_build_object(
              'x', generator.x,
              'y', generator.y,
              'array', generator.array_data)::jsonb
    FROM (
        SELECT 
        generate_series(1,10000) x, 
        generate_series(1,10000) y, 
        array_to_json(array_agg(array_elements)) array_data
        FROM (
            SELECT 
            generate_series(1,99) as key, 
            generate_series(1,99) as value
        ) array_elements
    ) as generator

And the index:

CREATE INDEX idxgintags ON modelling.triangle USING gin ((data -> 'x') jsonb_path_ops);

And the select:

EXPLAIN ANALYZE 
SELECT data->'array'
FROM modelling.triangle
WHERE data@>'{"x":10}'

Thank you.

1 Answer 1

1

Your query isn't using the created index because that index was created based on an expression and you do not use the expression. The right query would be:

EXPLAIN ANALYZE 
SELECT data->'array'
FROM modelling.triangle
WHERE data->'x' @> '10'

You can read more about this in JSON Types.

Another way would be to create an index on data field with jsonb_path_ops

CREATE INDEX idxgintags2 ON modelling.triangle USING gin (data  jsonb_path_ops);

This way you can use your query unmodified but the index will be much larger.

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

1 Comment

Ah thank you, I didn't know exactly how to use the indexes. My query has gone from 1000 ms down to .124. Cheers.

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.