Lookup by either part of tuple key in a map


I have a Map with composite key: Map<(&Addr, &Addr), GameData>.

The Map is just a slight variation on a standard HashMap (docs at Map in cw_storage_plus - Rust), Addr is just a wrapper on strings with some check methods (docs at Addr in cosmwasm_std - Rust)

What I am trying to do is look up records by Addr, no matter if it's first or second in that tuple key. I can do a lookup when targeting only the first element in the tuple by using prefix like this:

fn query_games_by_host(deps: Deps, host: Addr) -> StdResult<GamesListResponse> {
    let games_by_host = GAMES
        .range(deps.storage, None, None, Order::Ascending)
        .flat_map(|item| match item {
                    Ok((_, data)) => Some(data),
                    _ => None

    Ok(GamesListResponse { games: games_by_host })

However, prefix targets only the penultimate part of tuple.

Is there a way to look up by the second element of the tuple key, and a way to look up by either element of the tuple key?

Thank you.

One map is just one index in one order. You need to split it into two indexes if you want to look by two things (or a data structure that can do that under the hood).

Simplest solution: put GameData in a slotmap, put Addr -> SlotId in a map/multimap/two-maps. Wrap it all in a struct that has a semi-map API with methods you need.

There might be also a suitable library for it, but I'm not aware of any of the top of my head.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.