Reputation: 1653
I want to know which user sent more messages in a group.
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; }
}
When I receive a new message, I increase MessagesCount
of that user. At the end of the day how can I know which one has the highest MessagesCount
?
Thanks.
Upvotes: 0
Views: 3710
Reputation: 6467
You have to enumerate ALL the entities to find the one with largest MessagesCount
.
For more information about how to design your table to achieve more scenario targets, please refer to 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.
Upvotes: 4
Reputation: 3384
Here is an alternative way that should not require you to do a table scan. If you created a second table with partition key as inverted message counts (int.Max - MessageCount) and row key as user id, then querying the table without any partition or row key but with Take(1) should return the item at the top of the table. Since azure tables are lexicographicaly sorted this should return you the item with lowest partition key which is the entity with highest message count. This technique is called log-tail pattern and definitely works within a partition when applied to row keys. I believe it should also work when applied to partition keys within an entire table.
Upvotes: 3
Reputation: 27815
At the end of the day how can I know which one has the highest MessagesCount?
You can sort by MessagesCount
and get the user who has the highest MessagesCount. And you can execute the following query in a scheduled WebJob and cache the result, and then you can get result from the cache in your program instead of querying the result from Table storage.
TableQuery<UserEntity> query = new TableQuery<UserEntity>();
UserEntity user = table.ExecuteQuery(query).OrderBy(a => a.MessagesCount).LastOrDefault();
Besides, your requirements is similar to implement a scoreboard, if possible, you can store top-one user information in a separate entity, every time when you update user’s MessagesCount, you can compare current user’s MessagesCount with that entity and update that entity if current user’s MessagesCount is higher. In this way, you can query that (one) entity via point query to get the user who has the highest MessagesCount.
Upvotes: 4