tanweerdev
Remove all the records from ets table having datestamp older than 10 seconds
I have an ets set table in an elixir app. I need to clean-up records which have their updated_at older than 10 seconds. is there a way I can set expirey or do manually without iterating over all the records(match records based on the timestamps greater than given time)
example record:
key: key_1
record: %{id: key_1, updated_at: ~N[2018-12-19 10:08:47.803075]}
so far I am able to have this code
def clean_stale(previous_key) do
if previous_key == :"$end_of_table" do
:ok
else
device = get(previous_key)
next_key = :ets.next(__MODULE__, previous_key)
if NaiveDateTime.diff(NaiveDateTime.utc_now, device.last_recorded_at) > 10 do
remove(device.id)
end
clean_stale(next_key)
end
end
Marked As Solved
idi527
Ah, it seems like you need to use select_delete to be able to use guards in the match spec.
:ets.insert(:table, {device.id, device.last_recorded_at, device})
:ets.insert(:table, {device_2.id, device_2.last_recorded_at, device_2})
:ets.select_delete(:table, [{{:_, :"$1", :_}, [{:>, :"$1", timestamp}], [true]}])
works for me.
Also Liked
Nicd
You might want to take a look at GitHub - ericmj/ex2ms: :ets.fun2ms for Elixir, translate functions to match specifications · GitHub to make those match specs more readable.
cmkarlsson
idi527
You can try ets — OTP 29.0.2 (stdlib 8.0.1)
It would still iterate over the table, but unlike your current approach it wouldn’t copy any data from it. To make things easier, you might add an additional “column” to the table with updated_at as a timestamp for a simpler match statement.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









