Postgresql 通过EXTO存储jsonb数据

Postgresql 通过EXTO存储jsonb数据,postgresql,elixir,ecto,jsonb,Postgresql,Elixir,Ecto,Jsonb,我正试图通过ecto将jsonb数据传递给postgres。我希望能够获取一个有效的JSON字符串,将其添加为graphql参数,并在表中查看该JSON 迁移 我的理解是,您需要为JSONB定义一个结构,然后在插入时对其进行解码 defmodule Geodatajson do use MyApp, :model embedded_schema do field(:latitude, :float) field(:longitude, :float) end end

我正试图通过ecto将jsonb数据传递给postgres。我希望能够获取一个有效的JSON字符串,将其添加为graphql参数,并在表中查看该JSON

迁移 我的理解是,您需要为JSONB定义一个结构,然后在插入时对其进行解码

defmodule Geodatajson do
  use MyApp, :model

  embedded_schema do
    field(:latitude, :float)
    field(:longitude, :float)
  end
end
现在,模型:

defmodule MyApp.Geodata do
  use MyApp, :model

  alias MyApp.Repo
  alias MyApp.Geodata

  schema "geodata" do
    embeds_one(:json, Geodatajson)

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:json])
  end

  def add_geodata(str) do
    json = str |> Poison.decode!(as: Geodatajson)
    data = %Geodata{json: json}
    Repo.insert(data)
  end
end
我尝试像这样传入数据:

iex> MyApp.Geodata.add_geodata("{\"latitude\": 1.23, \"longitude\": 4.56}")
但是JSONB没有被解码:

{:ok,
 %MyApp.Geodata{
   __meta__: #Ecto.Schema.Metadata<:loaded, "geodata">,
   id: 26,
   inserted_at: ~N[2018-04-28 13:28:42.346382],
   json: %Geodatajson{
     id: "3b22ef94-92eb-4c64-8174-9ce1cb88e8c5",
     latitude: nil,
     longitude: nil
   },
   updated_at: ~N[2018-04-28 13:28:42.346392]
 }}
{:好的,
%MyApp.Geodata{
__meta:#exto.Schema.Metadata,
身份证号码:26,
插入地址:~N[2018-04-28 13:28:42.346382],
json:%Geodatajson{
id:“3b22ef94-92eb-4c64-8174-9ce1cb88e8c5”,
纬度:零,
经度:零
},
更新地址:~N[2018-04-28 13:28:42.346392]
}}

如何将这些数据输入postgres?

Poison的
as:
要求您传递一个结构实例,而不仅仅是模块的名称

json = str |> Poison.decode!(as: Geodatajson)
应该是:

json = str |> Poison.decode!(as: %Geodatajson{})
json = str |> Poison.decode!(as: %Geodatajson{})