Ecto 查询 Postgres JSON 数组的值

Ecto query Postgres JSON Array for a value

我有以下架构,它是 post table 的 JSONB 字段,它将保存所有使用的标签。

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

并且它有一个 "tags" 作为 "strings" 的数组。我想在此数组中搜索字符串值。我试过了:

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()

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

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"