使用Active Record搜索嵌套/多层Postgres JSON类型 [英] Search over a nested / multi-level Postgres JSON type using Active Record

查看:97
本文介绍了使用Active Record搜索嵌套/多层Postgres JSON类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我下面有json对象

Suppose I have the json object below

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

示例搜索:

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


推荐答案

如果您将Postgres用作数据库并且该列确实是json类型,则可以在这样的Rails中使用搜索:

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'")

此#>>将遍历json路径并进行搜索。
如果仅使用#>(仅带有一个>),它将返回剩余的json。

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

另一个示例,如果要获取 c =>确定

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

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

我认为就是这样。

这篇关于使用Active Record搜索嵌套/多层Postgres JSON类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆