简体   繁体   English

Elixir Ecto-PostgreSQL jsonb函数

[英]Elixir Ecto - PostgreSQL jsonb Functions

I am in the process of converting a Ruby on Rails API over to Elixir and Phoenix. 我正在将Ruby on Rails API转换为Elixir和Phoenix。 In my Postgres database, I have a table with a jsonb column type. 在我的Postgres数据库中,我有一个带有jsonb列类型的表。 One of the keys in the json is an array of colors. json中的键之一是颜色数组。 For example: 例如:

{"id": 12312312, "colors": ["Red", "Blue", "White"]}

What I am trying to do from Ecto is query my table for all records that contain the colors Red or Blue. 我想从Ecto进行的工作是查询我的表以查找包含红色或蓝色的所有记录。 Essentially, recreate this query: 本质上,重新创建此查询:

select * from mytable where data->'colors' ?| array['Red', 'Blue']

I'm having some difficulties constructing this query with Ecto. 我在用Ecto构造此查询时遇到一些困难。 Here is what I have: 这是我所拥有的:

Note: "value" will be a pipe delimited list of colors 注意:“值”将是管道分隔的颜色列表

  def with_colors(query, value) do
    colors = value 
      |> String.split("|")
      |> Enum.map(fn(x) -> "'#{x}'" end)
      |> Enum.join(", ")

    # colors should look like "'Red', 'Blue'"

    from c in query,
    where: fragment("data->'colors' \\?| array[?]", ^colors))
  end

This is currently not working as expected. 目前,此功能无法正常运行。 I am having issues with the replacement question mark, as it seems to wrap additional quotes around my field. 我在替换问号方面遇到问题,因为它似乎在我的领域周围加上了其他引号。 What is the proper way to do this use fragment? 使用此片段的正确方法是什么? Or maybe there is a better way? 还是有更好的方法?

I'm going to run into this problem again because I'm also going to have to recreate this query: 我将再次遇到这个问题,因为我还将不得不重新创建此查询:

select * from mytable where data->'colors' @> '["Red", "Blue"]'

I have found a solution to my problem. 我已经找到解决问题的办法。

def with_colors(query, value) do
  colors = value 
    |> String.split("|")

  from c in query,
  where: fragment("data->'colors' \\?| ?", ^colors))
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM