Search code examples
c#azurerandomstore

Retrieving a Random Row from Azure Table Storage?


Although this would seem simple, I can't think of a constant time way to get a random row out of Azure table storage.

I've got elements which have a base64 string as their row key (it's essentially a GUID) and a single partition key (not enough data to justify multiple partitions).

Right now the best thing I can think of for picking a random element is to hold onto one row and to get a 'random' row I simply run a query for a row which is greater than the current one I'm holding on to. Rinse and repeat.

Any thoughts?

Here's the row element, if it helps:

public class PhoneEntity : TableEntity
{
    private PhoneID _id;
    private Uri _pushUri;

    public Uri PushUri
    {
        get { return _pushUri; }
        set { _pushUri = value; }
    }

    public PhoneID Id
    {
        get { return _id; }
        set { _id = value; }
    }

    public PhoneEntity(PhoneID id, Uri pushUri)
    {
        Id = id;
        PushUri = pushUri;

        this.PartitionKey = "PhonePartition";
        this.RowKey = id.Id64;
    }
}

Solution

  • You can simply create a random row key and query for the first row greater than it (.Take(1)). If a row is not found, your random row key is too large, so retry with another random key.

    Assuming that your row keys are well distributed given that you are using a GUID, the retry should not occur too often.