【问题标题】:Ecto query Postgres JSON Array for a valueEcto 查询 Postgres JSON 数组的值
【发布时间】:2017-05-02 14:40:30
【问题描述】:

我有以下架构,这是一个用于 post 表的 JSONB 字段,它将保存所有使用的标签。

schema "posts" do
  ...
  field :tags, {:array, :string}
  ...
end

它有一个“标签”数组作为“字符串”。我想在这个数组中搜索一个字符串值。我试过了:

def search_by_tag(query, tag) do
  from p in query,
    where: fragment("? @> ?", p.tags, ^tag)
end

但是没有成功,我正在寻找的是一种搜索 JSONB 数组并在值存在时找到值的方法。此外,它还应该保持与非 JSONB 查询兼容的查询功能,以继续执行以下操作:

Blog.Post |> Blog.Post.search_by_tag("tag1") |> Blog.User.active()

【问题讨论】:

    标签: arrays json postgresql ecto


    【解决方案1】:

    @> 函数期望第二个操作数是数组,所以:

    def search_by_tag(query, tag) do
      tags = [tag]
      from p in query,
        where: fragment("? @> ?", p.tags, ^tags)
    end
    

    ecto 语法本身也支持这种情况:

    def search_by_tag(query, tag) do
      from p in query,
        where: tag in p.tags
    end
    

    对于可组合查询Blog.Post.search_by_tag("tag1") |> Blog.User.active(),您可以考虑使用"pipe-based syntax"

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 2015-11-28
      • 2016-06-05
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多