How can one get a random key from an UnorderedMap in NEAR Rust SDK?
2 Answers
If performance is not a concern for you, the simplest and most obvious way to do that is to use
the keys_as_vector() method on the map and then get a random element from it via the choose() method in the rand
crate.
Example:
use rand::thread_rng;
use rand::seq::SliceRandom;
let keys = my_map.keys_as_vector();
let random_key = keys.choose(&mut thread_rng());
println!("{:?}", random_key);
Clearly, the bigger your map, the slower this is gonna be.

- 8,726
- 26
- 46
If you know you key space then you can use near_sdk::env::random_seed() to generate a random seed and use that to get any key from the unordered_map.
https://docs.rs/near-sdk/latest/near_sdk/env/fn.random_seed.html
For Example:
If you have a Unordered_map<u64, Some_Struct>
The You generate a seed and convert it from Vec which random_seed() gives to u64
let randomId = u64::from_be_bytes(env::random_seed())
And get this from unordered_map as
unordered_map.get(&randomId).unwrap()
Not the most efficient way but you can try this. Open to better solutions.

- 19
- 1
-
It seems to me you are simply getting a random `u64` value and "blindly" trying to get a map entry with such key? So the chance to find an existing key should be approximately `(the map entries count) / 2^64`. Even for very large maps, you might still need to test billions of random values before you come across an existing one. – at54321 Feb 14 '22 at 11:21
-
That's true but if you know what is the latest index like you are adding from 0 to x, so can take modulus of random number with x , that way it can work. But yes you are correct if you try it in whole keyspace of u64 blindly it won't work. – PRINCE ANURAGI Feb 15 '22 at 12:24