Retrieval in ETS

I am storing some data in an ETS table of type bag. Now need the retrieval of data to take place in LIFO fashion i.e. I want the last inserted entry to come first. However the match function of ETS returns tuples in FIFO manner. Is there a way I can get last data first ?

Reverse the list of results…

But aside of that, there is no guaranteed ordering AFAIK. It can change arbitrarily with every new release of the ERTS.

If you really need to have guaranteed ordering, you need to store an insertion index.

3 Likes

No, with a bag the ordering is defined to be preserved. From the docs in http://erlang.org/doc/man/ets.html#lookup-2

“Notice that the time order of object insertions is preserved; the first object inserted with the specified key is the first in the resulting list, and so on.”

3 Likes

Then I had probably next/2 and prev/2 in mind, where it is written that the keys are returned in “internal order”, which I generally interprete as not to be guaranteed.

I do think though, that just using Enum.reverse/1 should be sufficient.

2 Likes

What are you trying to do™️?

2 Likes

Sorry, I was a bit unclear here. With a set, bag or duplicate_bag then order in which you get the keys is internal. This irrespective of whether you use match, select or first and next. I was referring to the ordering of elements of one key in a bag or duplicate_bag returned when doing a lookup, match or select.

The internal ordering of keys is not defined and you can never depend on it because as you say it can change between releases. Except of course for type ordered_set where the ordering is defined.

3 Likes

Thank you for clarrifying this source of confusion.

2 Likes