Home > Software design >  How to load & include sortkey with DynamoDBContext?
How to load & include sortkey with DynamoDBContext?

Time:12-16

Experimenting with dynamodb I had this query:

var request = new QueryRequest
            {
                TableName = "vs-configurator-engine-back-table",
                KeyConditionExpression = "HashKey = :key and begins_with(SortKey, :sortKey)",
                ExpressionAttributeValues = new Dictionary<string, Amazon.DynamoDBv2.Model.AttributeValue>  {
                {":key", new Amazon.DynamoDBv2.Model. AttributeValue { S =  key }},
                {":sortKey", new Amazon.DynamoDBv2.Model. AttributeValue { S =  sort }},
                },
            };

where key and sort:

var key = "modelyear#specialParam#Id#year#metadata";
string sort = "ruleset#";

this worked but I did not like that when reading the data I had to retrive values like:

response.Items[0].TryGetValue("MyProp", out AttributeValue propOut);

Im use to a .net to Mysql world where I can get an object class as a result so I tried this approach:

[DynamoDBTable("myCoolTable")]
public class MyObject
{
    [DynamoDBHashKey]
    public string HashKey { get; set; }
    public string SortKey { get; set; }
    [DynamoDBProperty]
    public DateTime activeFrom { get; set; }
    [DynamoDBProperty]
    public Guid id { get; set; }
}

    public async Task<DateTime> GetData()
    {

        AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();


        AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);

        DynamoDBContext context = new DynamoDBContext(client);
        MyObject obj = context.Load<MyObject>("modelyear#specialParam#Id#year#metadata");
    }

When doing this I get an error saying:

"Message = "Unable to convert range key value for property SortKey"

I am trying to find out how to send the sortkey into the query but also don't quite understand the error message.

I want to send the sorkey into the query but also be able to convert it´s value once it is all retived

CodePudding user response:

The Load method is used to retrieve one single item from your table, therefore you need to provide the entire primary key, hash and range key.

Behind the scenes the Load method actually calls the GetItem operation from the native AWS DynamoDB API. This means you cannot use begins_with or any other function.

You need to use Query, example:

DynamoDBContext context = new DynamoDBContext(client);

string replyId = "DynamoDB#DynamoDB Thread 1"; //Partition key
DateTime twoWeeksAgoDate = DateTime.UtcNow.Subtract(new TimeSpan(14, 0, 0, 0)); // Date to compare.
IEnumerable<Reply> latestReplies = context.Query<Reply>(replyId, QueryOperator.GreaterThan, twoWeeksAgoDate);
  • Related