嘿,我有一个ets表transactions
,表的一部分是这样的
[
{"txn_05h0f14877a091yj7358a",
%{
account_id: "acc_f5f3f6y7t8s7a5htj78ty",
amount: 289,
date: ~D[2022-03-16],
details: %{
details: %{
category: "transport",
counterparty: %{name: "UBER", type: "organization"},
processing_status: "complete"
}
},
links: %{
account: "http://localhost:4000/accounts/acc_f5f3f6y7t8s7a5htj78ty",
self: "http://localhost:4000/accounts/acc_f5f3f6y7t8s7a5htj78ty/balances/transactions/txn_f5f3f6y7t8s7a5htj78ty"
},
running_balance: 100000,
status: "posted",
type: "card_payment"
}}
]
我想选择所有与account_id
匹配的记录我正在做这样的事情
iex(23)> fun = :ets.fun2ms(fn {_, {account_id}} when account_id == "acc_f5f3f6y7t8s7a5htj78ty" -> account_id end)
[{{:_, {:"$1"}}, [{:==, :"$1", "acc_f5f3f6y7t8s7a5htj78ty"}], [:"$1"]}]
iex(24)> :ets.select(:transactions, fun)
[]
,但查询不能正常工作。如何选择所有匹配account_id
的记录?
您的方法有效,但您的模式与数据的形状不匹配:它期望形状为{"txn_05h0f14877a091yj7358a", {"acc_f5f3f6y7t8s7a5htj78ty"}}
的记录。
您需要查找映射:account_id
键:
iex> fun = :ets.fun2ms(fn {_, transaction} when transaction.account_id == "acc_f5f3f6y7t8s7a5htj78ty" -> transaction end)
[
{{:_, :"$1"},
[{:==, {:map_get, :account_id, :"$1"}, "acc_f5f3f6y7t8s7a5htj78ty"}],
[:"$1"]}
]
iex> :ets.select(:transactions, fun)
[
%{
account_id: "acc_f5f3f6y7t8s7a5htj78ty",
amount: 289,
...
}
]
注意:when transaction.account_id ==
守卫需要Elixir>= 1.11,如果你使用的是旧版本,你也可以使用when :erlang.map_get(:account_id, transaction) ==
。