Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search over a nested / multi-level Postgres JSON type using Active Record

Suppose I have the json object below

:response_body => {
    "status" => "ok",
    "um" => {
        "a" => "a",
        "b" => {
            "c" => "ok"
        }
    }
}

Example search:

LogService.where(response_body: {"status" => "ok"})
like image 997
user8494 Avatar asked May 12 '14 12:05

user8494


1 Answers

If you are using the Postgres as database and the column really is a json type, you can use a search in Rails like this:

LogService.where("response_body#>>'{status}' = 'ok'")

This #>> will walk over the json path and make the search. If you use only #> (with just one >), it will return the remaing json.

Another example, if you want to get the "c" => "ok"

LogService.where("response_body#>>'{um, b, c}' = 'ok'")

I think that´s it.

like image 180
Arthur Felipe Avatar answered Oct 24 '22 02:10

Arthur Felipe