I have very simple table items with the following structure:

struct [[eosio::table]] item
       uint64_t id;
       uint64_t state;
       string description;

       uint64_t primary_key() const { return id; }
       uint64_t by_state() const { return state; }

   typedef eosio::multi_index<"items"_n, item,
       eosio::indexed_by<"bystate"_n, eosio::const_mem_fun<item, uint64_t, &item::by_state>>> items;
    items items_table;

and I have an action within smart contract, where I need to filter the items by particular state and loop the result executing a simple processing for each of the filtered items. Currently I am using the following implementation (simply looping the whole table, searching for the items on specified state):

for (auto iter = items_table.begin(); iter != items_table.end(); iter++)
   if (iter->state == state)
       // handle item record


but it is not sufficient if table contains enormous amount of items.

Does anyone knows is there a way (is EOS) to fetch the item records on specified state using secondary index "bystate" and further loop those records and apply another logic for each of them ?

2 Answers 2


With your current setup, you could do something like this to optimize things a bit:

items_table items(_self, _self.value);

auto idx = items.get_index<"bystate"_n>();
auto itr_start = idx.lower_bound(name("pending").value);
auto itr_end = idx.upper_bound(name("pending").value);

for (itr_start != itr_end; itr_start++)
       // handle item record (they should all be of state "pending")

However, you still have to be aware of the transaction time limit as mentioned above.

  • There is a semicolon missing for the loop for (;itr_start != itr_end; itr_start++)
    – Sigmatics
    Jul 10, 2020 at 15:28

This is a very common question, because the transaction time limit is going to kick in. At the moment I am using deferred transactions to trigger a search action that takes an additional argument.

You could also save the state of your search in another table as well.

I discussed this in a thread with the deletion of elements, you can adapt the code to use it to search.

Delete all multi_index records without iterator?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.