How to match_delete from ets based on map pattern

I have this data stored in ets: :ets.tab2list(:my_tab)

[
 {{1, "W", 1}, %{aid: 1, dt_close: nil, dt_open: nil, sid: 1, src: "W", uid: 1}},
 {{2, "T", 1}, %{aid: 1, dt_close: nil, dt_open: nil, sid: 2, src: "T", uid: 2}},
 {{1, "S", 1}, %{aid: 1, dt_close: nil, dt_open: nil, sid: 7, src: "S", uid: 1}},
 {{1, "T", 1}, %{aid: 1, dt_close: nil, dt_open: nil, sid: 5, src: "T", uid: 1}}
]

when I apply this

:ets.match_delete(:my_tab, {:_, %{aid: 1, dt_open: nil}, :"$1"})

I get back true , but there is no change to the ets table

Please what have I missed ?

Where you are using the atom :"$1", I believe this matches on a position, for example used in a look up that would match the first value. I think :_ might work for you.

Edit: there’s some good reference here: https://elixirschool.com/en/lessons/specifics/ets/#simple-matches

1 Like

seems its easier to work with tuples throughout with ets.

I’m unable to get the map pattern to work

Had a little play around:

:ets.match_object(:my_tab, {{:_, "W", :_}, :"$2"})
or
:ets.match_object(:my_tab, {{:_, "W", :_}, :_})
Returns:

[
  {{1, "W", 1},
   %{aid: 1, dt_close: nil, dt_open: nil, sid: 1, src: "W", uid: 1}}
]

:ets.match_delete(:my_tab, {{:_, "W", :_}, :"$2"})
Returns true
:ets.match_object(:my_tab, {{:_, "W", :_}, :"$2"})
Returns []

Hope that’s of some help - admittedly this is probably not idiomatic (I’m far removed from being anything close to knowledgeable enough), but it works :wink:

One little slip up I made was to use :ets.delete_object/2 by mistake before reading the docs, which states it deletes the exact object from the table, but leaves objects with the same key and if I understand correctly it always returns true

1 Like

Thanks!

I have swapped out the maps for tuples. it makes using ETS easier.

1 Like

Glad you got it resolved. I did forget to add that the following worked as a match as well (obviously it’s only matching on the W in the key, but it was just for demonstrative purposes).

{{:_, "W", :_}, %{aid: :_, dt_close: :_, dt_open: :_, sid: :_, src: :_, uid: :_}}

1 Like