0

If I have a table called configurations where rows contain a jsonb column called data with values similar to the following:

{
    "US": {
        "1234": {
            "id": "ABCD"
        }
    },
    "CA": {
        "5678": {
            "id": "WXYZ"
        }
    }
}

My hope is to be able to write a query akin to the following:

select * from configurations where data->'$.*.*.id' = 'WXYZ'

(Please note: I'm aware that the SQL above is not correct, treat it as pseudo.)

Questions:

  • What is the correct syntax to perform the query I've written above?
  • What type of index would I need to create to ensure I'm not scanning the entire table using any query from my previous question?
2
  • Why not just normalize your data model? Commented Sep 27, 2021 at 16:23
  • Because the values in this column will vary in structure and represent information from external systems. Commented Sep 27, 2021 at 16:28

1 Answer 1

1

You can turn your pseudo code into real jsonpath code:

select * from configurations where data @@ '$.*.*.id == "WXYZ"'

And this can use a default gin index on "data":

create index on configurations using gin (data);
Sign up to request clarification or add additional context in comments.

6 Comments

Neat, I'll give that a shot! Is there any specific syntax I should use to create that gin index?
Thanks for the update! Do you happen to know if the gin index can be combined with other non-json columns?
Hmm, my explain for the query select * from configurations where data @@ '$.*.*.id' is not null; doesn't appear to be using the gin index I create. Still shows "Seq scan".
If the table is small, or if it thinks too many rows will match, it won't find the index enticing to use. Is either of those the case here? In my hands, not only was it used, but it was much more efficient than i thought it would be.
It can combine with other indexes by the use of bitmap scans.
|

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.