Elixir 如何查询hashmap字段?

Elixir 如何查询hashmap字段?,elixir,phoenix-framework,ecto,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 我如何查找所有在匹配哈希中具有酷键的用户 用户|>其中[u],u.匹配[cool]!=nil |>limit1 |>VideoCha

我有一个模型:

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

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

    timestamps()
  end

  ...
end
我如何查找所有在匹配哈希中具有酷键的用户

用户|>其中[u],u.匹配[cool]!=nil |>limit1 |>VideoChat.Repo.one

:地图字段由Ecto存储为PostgreSQL中的JSONB字段。Ecto不提供任何函数来对这些字段执行特定于映射的操作,但可以使用片段和自定义SQL来完成

SQL查询foo.bar?“baz'将检查foo的列栏是否在键baz中包含值。这可以用如下片段表示:

fragment("? \\? ?", foo.bar, "baz")
因此,您的代码应修改为:

User |> where([u], fragment("? \\? ?", u.matches, "cool")) |> limit(1) |> VideoChat.Repo.one
在一个全新的地图模型中,关键地图类型为: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') []
[]