Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way of limiting the number of records under a certain key in mnesia?

I use mnesia to store data for users, and the record is a bag structured like

{ username, field1, filed2, timestamp }

In order not to let the database explode, I want to set a limit for the number of records belonging to a certain user, say, if the number of records for a user reaches 500, then the record with the oldest timestamp is deleted before a new record is inserted.

Is there an efficient way to do this?

Thanks in advance.

like image 706
Chi Zhang Avatar asked Nov 13 '22 14:11

Chi Zhang


1 Answers

Another way might be to have your record be

{username, value_list, timestamp} 

where value_list contains a list of values. Your table can now be a set instead of a bag and you can do this type of thing

{NewList,_ignore}=lists:Split(500, [{NewFld1,NewFld2}|Value_list]),
%mnesia:write(Rec#{value_list=NewList}) type of code goes next

whenever you insert. NewList will contain at most 500 elements and since the oldest elements are on the end, if you have 501 elements the last will be in the _ignore list which you will... Ignore.

Your trading a constant time lookup on your key for some list manipulation, but might be a good trade-off depending on your application. You also may be able to get rid of the timestamp field and associated code to maintain that field.

like image 101
Jr0 Avatar answered Dec 15 '22 04:12

Jr0