How do you get all keys in a MemoryStoreSortedMap

Hello Everyone,

I am wondering how I am able to get all of the Keys inside of a MemoryStoreSortedMap. It says “Read all existing keys or a specific range of them.” for MemoryStoreSortedMap:GetRangeAsync() in The Memory Store Article. I need to get all of the keys, I’m just wondering on how I would be able to do this.

From,
Spencer “SpencerDevv”

AFAIK, you can’t. You have to either know the exact keys, or a somewhat templated version that can be used with GetRangeAsync. e.g. if you have keys 0001_abcde, 0002_xyzw, 0003_idk, etc., then you could use a range of “0001” thru “0003” and still get your keys.

To that point, I recommend suffixing your keys with something that you always know, so that you can use GetRangeAsync on them all.

Note: At the time of writing this, the MemoryStoreService is pretty new, and I am still trying to learn the intricacies of it, so perhaps my answer isn’t the best solution.

2 Likes

The following function will naively iterate through all keys. The exclusiveLowerBound argument of GetRangeAsync indicates where the range begins, so the last key of the previous results can be used to continue the next iteration.

local function TraverseAllKeys(sortedMap: MemoryStoreSortedMap, callback: (key: string, value: any)->())
	local lastKey = nil
	while true do
		local entries = sortedMap:GetRangeAsync(Enum.SortDirection.Ascending, 100, lastKey)
		if #entries == 0 then
			break
		end
		for _, entry in ipairs(entries) do
			callback(entry.key, entry.value)
		end
		lastKey = entries[#entries].key
	end
end

Remember that the content of the map can change between calls to GetRangeAsync, so it’s not completely foolproof.

5 Likes

So I have been using UID’s for the keys, which might not be a good idea, but it’s what I thought would be good. Thanks for the info and I hope they add something in the future for getting all keys!