Search code examples
elixirets

ETS table select all records matching id


Hey I have an ets table transactions, part of the table is looking like this.

[
  {"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"
   }}
]

I would like to select all records that are matching account_id and I'm doing something like this

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)
[]

but the query is not working properly. What will be a proper way of selecting all records matching account_id?


Solution

  • Your approach works but your pattern doesn't match the shape of the data: it expects records of the shape {"txn_05h0f14877a091yj7358a", {"acc_f5f3f6y7t8s7a5htj78ty"}}.

    You need to lookup the map :account_id key:

    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,
        ...
      }
    ]
    

    Note: The when transaction.account_id == guard needs Elixir >= 1.11, you can also use when :erlang.map_get(:account_id, transaction) == if you are on an older version.