Querying data in postgresql by applying filter on a JSONB column
Asked Answered
B

1

8

I have a table with 2 columns; ID (int) and EntityData (JSON). I have created a filter object in form of a Dictionary in C#. I want to fetch all rows which satisfy the key-value pair data in my filter.

A sample filter is:

{
    "Name": "mike",
    "Location": "Lagos"
}

and this should fetch me all rows whose EntityData has Name as mike and Location as Lagos.

Backlog answered 30/4, 2018 at 6:51 Comment(0)
I
16

A single query could look like the following:

SELECT * FROM table WHERE json_field->>'Name' = 'mike' AND json_field->>'Location' = 'Lagos'

You can replace 'mike' and 'Lagos' by parameter placeholders (@name, @location) and rerun this query repeatedly on for all entries of your dictionary. For optimal performance you can also prepare the command beforehand, and possibly even batch all queries in one command by concatenating the query several times into the same CommandText.

See here for the full PG docs on JSON operators.

Impregnate answered 30/4, 2018 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.