【问题标题】:How to using json fields inside where statement in Sequel?如何在 Sequel 的 where 语句中使用 json 字段?
【发布时间】:2017-12-25 22:52:49
【问题描述】:

我有一张桌子transactions

 id             | bigint                      | NOT NULL DEFAULT nextval('transactions_id_seq'::regclass)
 transaction_id | bigint                      | NOT NULL
 middleware_id  | text                        | 
 opname         | optype                      | NOT NULL
 created_at     | timestamp without time zone | NOT NULL
 finished_at    | timestamp without time zone |
 request        | jsonb                       | NOT NULL
 answer         | jsonb                       | 

请求可以包含以下数据: { plugin_id: string, item_src_id: string, item_dst_id: string, payload: {}} 要么 { plugin_id: string, item_id: string, payload: {}}

我可以为一些item_id 选择事务列表,比如用纯SQL:

SELECT id, request
  FROM transactions
  WHERE 'BEX456'
    IN (request->>'item_id', request->>'item_src_id', request->>'item_dst_id')

但是,当我将该请求与 Sequel 一起使用时,它会警告我

SEQUEL DEPRECATION WARNING:调用数据集过滤方法 多个参数或一个数组,其中第一个参数/元素是 string 已弃用,将在 Sequel 5 中删除。

对于那个请求:

$db[:transactions].
  where("? IN (request->>'item_id', request->>'item_src_id', request->>'item_dst_id')", data[:item_id]).all

我可以在 where 操作中使用 Sequel.lit 作为该字符串,但我的问题是 - 我可以使用原生 Sequel 运算符在字段内选择 json

这对我有用:

$db[:transactions].where(
  data[:item_id] => [
    Sequel.lit("request->>'item_id'"),
    Sequel.lit("request->>'item_dst_id'"),
    Sequel.lit("request->>'item_src_id'") ] ).first

【问题讨论】:

    标签: ruby postgresql sequel sequel-gem


    【解决方案1】:

    pg_json_ops extension 中提供了 Postgres 的 JSON 运算符。

    预先加载:

    Sequel.extension :pg_json_ops
    

    然后,在您的特定情况下:

    # request ->> 'item_id'
    :request.pg_jsonb.get_text('item_id') # WITH core extensions
    Sequel.pg_jsonb_op(:request).get_text('item_id') # or WITHOUT
    

    你也拥有 Ruby 的力量:

    ["item_id", "item_dst_id", "item_src_id"].map { |key| :request.pg_jsonb.get_text(key) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2021-05-29
      • 1970-01-01
      • 2021-10-13
      • 2019-07-14
      相关资源
      最近更新 更多