Madhusudan Joshi
Madhusudan Joshi

Reputation: 4476

How to do an ets table lookup using a secondary key

I have a table with the following attributes:

SortCode   Index  Created

SortCode is the primary key and Index is secondary key. Given an Index value, how do I get the associated SortCode value?

I have tried ets:lookup/3 but it takes only a primary key.

Upvotes: 2

Views: 1836

Answers (2)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26131

There is not such thing as a secondary index in ets. You can do:

  1. full scan using ets:match or ets:select or
  2. make you own reverse index ets table or
  3. use mnesia with added (secondary) index.

Upvotes: 3

Madhusudan Joshi
Madhusudan Joshi

Reputation: 4476

Adding to what Hynek -Pichi- Vychodil has said.

There is no solution in ets to fetch record using some other attribute apart from the key. It can be done using mnesia:dirty_index_read().

If you want to use ets only then you can do as above suggestion or follwoing code. Assuming your record pattern is omething like : {"one",1,"27092015"} Key is "one" but you have to fetch using 1.

FilterSuspCodeFun = fun ({_,I,_}) when I == 1 -> true ; (_) -> false end,
ListData = ets:tab2list(susp_code),
{SortCode,_,created}= lists:filter(FilterSuspCodeFun,ListData),

Upvotes: -2

Related Questions