Ecto + Elixir:如何查询hashmap字段?

时间:2016-12-06 23:16:30

标签: elixir phoenix-framework ecto

我有一个模特:

defmodule VideoChat.User do
  use VideoChat.Web, :model

  schema "users" do
    field :device_identifier, :string
    field :matches, :map

    timestamps()
  end

  ...
end

我如何在matches哈希中找到所有“酷”键的用户?

User |> where([u], u.matches["cool"] != nil) |> limit(1) |> VideoChat.Repo.one

1 个答案:

答案 0 :(得分:4)

fragment字段由Ecto存储在PostgreSQL中作为JSONB字段。 Ecto不提供任何函数来对这些字段进行映射特定操作,但可以使用foo.bar ? 'baz'和自定义SQL来完成。

SQL查询bar将检查foo的{​​{1}}列是否包含密钥"baz"中的值。这可以用fragment表达,如下所示:

fragment("? \\? ?", foo.bar, "baz")

因此,您的代码应修改为:

User |> where([u], fragment("? \\? ?", u.matches, "cool")) |> limit(1) |> VideoChat.Repo.one

使用Map类型为map的全新:map模型:

iex(1)> Repo.insert! %MyApp.Map{map: %{}}
iex(2)> Repo.insert! %MyApp.Map{map: %{foo: 1}}
iex(3)> Repo.insert! %MyApp.Map{map: %{foo: 2}}
iex(4)> Repo.insert! %MyApp.Map{map: %{bar: 1}}
iex(5)> Repo.all MyApp.Map |> where([m], fragment("? \\? ?", m.map, "foo"))
[debug] QUERY OK source="maps" db=1.8ms decode=5.3ms
SELECT m0."id", m0."map", m0."inserted_at", m0."updated_at" FROM "maps" AS m0 WHERE (m0."map" ? 'foo') []
[%MyApp.Map{__meta__: #Ecto.Schema.Metadata<:loaded, "maps">, id: 2,
  inserted_at: #Ecto.DateTime<2016-12-07 10:19:53>, map: %{"foo" => 1},
  updated_at: #Ecto.DateTime<2016-12-07 10:19:53>},
 %MyApp.Map{__meta__: #Ecto.Schema.Metadata<:loaded, "maps">, id: 3,
  inserted_at: #Ecto.DateTime<2016-12-07 10:19:55>, map: %{"foo" => 2},
  updated_at: #Ecto.DateTime<2016-12-07 10:19:55>}]
iex(6)> Repo.all MyApp.Map |> where([m], fragment("? \\? ?", m.map, "bar"))
[debug] QUERY OK source="maps" db=2.9ms queue=0.2ms
SELECT m0."id", m0."map", m0."inserted_at", m0."updated_at" FROM "maps" AS m0 WHERE (m0."map" ? 'bar') []
[%MyApp.Map{__meta__: #Ecto.Schema.Metadata<:loaded, "maps">, id: 4,
  inserted_at: #Ecto.DateTime<2016-12-07 10:19:59>, map: %{"bar" => 1},
  updated_at: #Ecto.DateTime<2016-12-07 10:19:59>}]
iex(7)> Repo.all MyApp.Map |> where([m], fragment("? \\? ?", m.map, "baz"))
[debug] QUERY OK source="maps" db=2.2ms queue=0.1ms
SELECT m0."id", m0."map", m0."inserted_at", m0."updated_at" FROM "maps" AS m0 WHERE (m0."map" ? 'baz') []
[]