如何在 Azure 中获得最高价值 Table

How to get the highest value in Azure Table

我想知道群里哪个用户发的消息多

public class UserEntity : TableEntity
{
    public UserEntity()
    {

    }

    public UserEntity(string chatId, string userId) 
        : base(chatId, userId)
    {
    }

    public int Name { get; set; }
    public int MessagesCount { get; set; }
}

当我收到一条新消息时,我会增加该用户的 MessagesCount。在一天结束时,我怎么知道哪一个的 MessagesCount 最高?

谢谢。

您必须枚举 所有 个实体才能找到最大 MessagesCount 的实体。

有关如何设计您的 table 以实现更多场景目标的更多信息,请参阅 Azure Storage Table Design Guide

Update:

I don't know who marked my answer is not useful just now, but it's true that Azure Storage Table service doesn't support server-side sorting. In other words, people have to query ALL the entities from table service and find the minimal/maximal value from client side if the property is not PartitionKey/RowKey, which is what Fei Han's answer actually did. Honestly speaking, such a table scan always means that your table wasn't designed appropriately, that's why I suggested people to read the design guide.

At the end of the day how can I know which one has the highest MessagesCount?

您可以按 MessagesCount 排序并获得 MessagesCount 最高的用户。您可以在计划的 WebJob 中执行以下查询并缓存结果,然后您可以从程序中的缓存中获取结果,而不是从 Table 存储中查询结果。

TableQuery<UserEntity> query = new TableQuery<UserEntity>();

UserEntity user = table.ExecuteQuery(query).OrderBy(a => a.MessagesCount).LastOrDefault();

此外,你的需求类似于实现一个scoreboard,如果可能,你可以将top-one用户信息存储在一个单独的实体,每次更新用户的 MessagesCount 时,您可以将当前用户的 MessagesCount 与该实体进行比较,如果当前用户的 MessagesCount 更高,则更新该实体。这样,您可以通过点查询来查询该(一个)实体,以获取具有最高 MessagesCount 的用户。

这是一种替代方法,不需要您进行 table 扫描。如果您创建了第二个 table,分区键作为倒置消息计数(int.Max - MessageCount),行键作为用户 ID,则查询 table 时没有任何分区键或行键,但使用 Take (1) 应return 项目顶部table。由于 azure table 是按字典顺序排序的,这应该 return 具有最低分区键的项目是具有最高消息计数的实体。这种技术称为 log-tail 模式,当应用于行键时,它绝对适用于分区。我相信它在应用于整个 table 中的分区键时也应该有效。