假設有如下數據 Records
rank name desc
1 apple fruit
2 cat animal
3 bike vehicle
如果你想把你的集合拆分成小的分組,chunk
就是你要找的函數:
iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2)
[[1, 2], [3, 4], [5, 6]]
使用~w()
這個魔術符可以將空格分割的字符串轉換為列表:
iex> ~w(1 apple fruit)
["1", "apple", "fruit"]
1. 數據預處理:輸入所有數據到data列表變量
iex> data = ~w(1 apple fruit
...> 2 cat animal
...> 3 bike vehicle)
["1", "apple", "fruit", "2", "cat", "animal", "3", "bike", "vehicle"]
2. 數據分組:使用chunk
函數進行分組
iex> Enum.chunk(data, 3)
[["1", "apple", "fruit"], ["2", "cat", "animal"], ["3", "bike", "vehicle"]]
當然,也可以寫成
data |> Enum.chunk(3)
結果是一樣的
3. 構成結構體
可以使用Enum.zip組合兩個列表
iex> Enum.zip([:rank, :name, :desc], ["1", "apple", "fruit"])
[rank: "1", name: "apple", desc: "fruit"]
如果在后面使用Enum.into就可以構造map類型啦!
iex> Enum.zip([:rank, :name, :desc], ["1", "apple", "fruit"]) |> Enum.into(%{})
%{desc: "fruit", name: "apple", rank: "1"}
4. Map VS Struct
這里我們回顧一下Elixir Map和Struct的區別,map屬于基本結構,形式為%{usernmae: "szy", passwd: "elixir"}
,注意到這里的username拼寫錯誤,在使用時:
iex> user.username
** (KeyError) key :username not found in: %{passwd: "elixir", usernmae: "szy"}
發現提示沒有找到這個key。這說明map只在runtime進行key的驗證,在插入的時候沒有進行驗證。如果希望在插入數據時就對key是否存在進行驗證,則需要使用struct。
Struct本質上也是一個Map,只不過多了一個Key,也就是__struct__
。
iex> user = %User{username: "szy"}
%Elecity.User{__meta__: #Ecto.Schema.Metadata<:built>, description: nil,
email: nil, id: nil, inserted_at: nil, password: nil, password_hash: nil,
updated_at: nil,
user_role_id: nil, username: "szy"}
如果插入時沒有key會立即提示錯誤
iex> user2 = %User{usernmae: "szy"}
** (CompileError) iex:3: unknown key :usernmae for struct Elecity.User
此外,插入時沒有聲明的部分會自動填充默認內容。
5. 綜合
現在我們就來構造結構體吧!同樣使用~w()a
,這里后面的a代表轉換的是atom類型。
iex> key = ~w(rank name desc)a
[:rank, :name, :desc]
iex> data = ~w(1 apple fruit
...> 2 cat animal
...> 3 bike vehicle)
["1", "apple", "fruit", "2", "cat", "animal", "3", "bike", "vehicle"]
iex> data = Enum.chunk(data, 3)
[["1", "apple", "fruit"], ["2", "cat", "animal"], ["3", "bike", "vehicle"]]
iex(19)> for record <- data do
...(19)> Enum.zip(key, record)
...(19)> |> Enum.into(%Record{})
...(19)> |> Repo.insert!()
...(19)> end
當然,使用insert_all
可以大大簡化
MyApp.Repo.insert_all(Post, [[title: "hello", body: "world"], [title: "another", body: "post"]])
第一個data
iex(21)> for rec <- data do
...(21)> Enum.zip(key, rec)
...(21)> end
[[rank: "1", name: "apple", desc: "fruit"],
[rank: "2", name: "cat", desc: "animal"],
[rank: "3", name: "bike", desc: "vehicle"]]
總結一下,就是:
- ~w()a轉換key
- ~w()轉換數據
- Enum.chunk分組數據
- Enum.zip添加key
- Enum.into轉換Struct后逐個插入Ecto 1.x
- 批量 insert_all (Step4) Ecto 2.x
http://blog.plataformatec.com.br/2016/05/ectos-insert_all-and-schemaless-queries/
http://www.elixir-cn.com/posts/136