Permanently Deleting Data Store Key

Hi, so I’m currently wondering if there is any efficient way of permanently deleting a data store key. I have a list of “flights” in a data store with v2 enabled. When a server starts, I get all the keys in this flight data store with ListKeysAsync and get each key’s value. The problem I have is when I want to remove a flight the key is not completely deleted with RemoveAsync since there are past versions of it. This leads to me making unnecessary GetAsync requests. The solution I came up with was to use ListVersionsAsync to get all the versions of the key and then use RemoveVersionAsync to remove them. I’m concerned that I’ll go over the limits using this method.

Is there a better way to do this?

No, there isn’t. The entire point of datastore versioning is that in case you delete something there will be a previous version available.

What does your datastore look like? ListKeysAsync shouldn’t list deleted keys.

I have a DataStore with a list of flights with each key being the flight number like “FN-2” and the value being data about the flight. Here’s what the DevHub says on RemoveAsync:

This function marks the specified key as deleted by creating a new “tombstone” version of the key. Prior to this, it returns the latest version prior to the remove call.

Oh, I see.

local DataStoreService = game:GetService("DataStoreService")

local options = Instance.new("DataStoreOptions")
options:SetExperimentalFeatures({v2 = true})

function partial(f, ...)
    local args = {...}
    return function(...)
        f(unpack(args), ...)
    end
end

function iterKeys(pages: DataStoreKeyPages)
    local keys = {}
    while true do
        local add = pages:GetCurrentPage()
        for i, v in pairs(add) do
            add[i] = v.KeyName
        end
        table.foreachi(add, partial(table.insert, keys))
        if pages.IsFinished then
            break
        end
        pages:AdvanceToNextPageAsync()
    end
    return keys
end

local testStore = DataStoreService:GetDataStore("testStore", "foobar", options)
testStore:SetAsync("fn-1", "a")
testStore:SetAsync("fn-2", "b")
testStore:SetAsync("fn-3", "c")
testStore:SetAsync("fn-4", "d")

print(iterKeys(testStore:ListKeysAsync("", 5)))

testStore:RemoveAsync("fn-2")
testStore:RemoveAsync("fn-4")

print(iterKeys(testStore:ListKeysAsync("", 5)))

image

Have you tried something like this?


One key holds a reference to all the other keys.
To remove a flight, remove it’s entry in meta/flights and then delete its key in the prefix flights.
meta/flights is a JSON array.

1 Like

I haven’t thought of anything like this. Thanks for the very detailed and helpful answer.

1 Like