- 最新
- 最多得票
- 最多評論
You'd first need a Global Secondary Index with Id as the sort key value, and a static value as the partition key:
GSI_PK | GSI_SK | Data |
---|---|---|
1 | ID_01 | Data |
1 | ID_02 | Data |
1 | ID_03 | Data |
1 | ID_14 | Data |
Then you would Query
your index with ScanIndexForward=False
(DESC order) with a Limit=1
(return biggest ID).
var client = new AmazonDynamoDBClient();
var request = new QueryRequest
{
TableName = "Table_Name",
IndexName = "Index_Name",
KeyConditionExpression = "#pk = :pk",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":pk", new AttributeValue { N = "1" } }
},
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#pk", "GSI_PK" }
},
ProjectionExpression = "GSI_SK",
Limit = 1
};
var response = await client.QueryAsync(request);
Console.WriteLine(response);
You could scan the whole table, looking for the max value, but I'm assuming you want to avoid that. The best option I can think of is to add a Global Secondary Index (GSI) to your table that has "Id" as a Sort (Range) key, and query that index, e.g.:
# Use the Query operation to retrieve the first item in the index in descending order
response = dynamodb.query(
TableName=table_name,
IndexName=index_name,
Select='SPECIFIC_ATTRIBUTES',
AttributesToGet=[partition_key_name],
Limit=1,
ScanIndexForward=False
)
# Extract the maximum partition key value from the response
max_partition_key_value = response['Items'][0][partition_key_name]
You may need a dummy Hash (Partition) key for the GSI, always set to the same value, if nothing else suits your use case.
I have created a GSI as per the above suggestion but when I am executing above I get the below error
var blogRequest = new QueryRequest { TableName = "MenuItem", IndexName = "CategoryId-Id-index", Select = "SPECIFIC_ATTRIBUTES", AttributesToGet = { "Id" }, ScanIndexForward = false, Limit = 1, };
var result = client.QueryAsync(blogRequest).GetAwaiter().GetResult();
Error:
Amazon.DynamoDBv2.AmazonDynamoDBException: 'Either the KeyConditions or KeyConditionExpression parameter must be specified in the request.'
I am using C# language
相關內容
- AWS 官方已更新 2 年前
- AWS 官方已更新 2 年前
- AWS 官方已更新 4 個月前
This worked for me