Querying DynamoDB - results in the wrong order

0

I have a table where the primary index is keyed on attributes called "PK" and "SK". Currently, there are three items in the table

Enter image description here

When I run a query on the table, using the following C# code (where searchTS = "DASH-20221209-23:32:11") I would expect to get the 3rd item in the table (as that is the one with the value of SK <= the searchTS value). I actually end up with the 2nd item.

            DynamoDBContext context = new DynamoDBContext(_client);

            var searchTS = $"DASH-" + DateTime.Now.ToString("yyyyMMdd-HH:mm:ss");

            QueryFilter qf = new QueryFilter();
            qf.AddCondition("PK", ScanOperator.Equal, "STAT");
            qf.AddCondition("SK", ScanOperator.LessThanOrEqual, searchTS);

            var opConfig = new DynamoDBOperationConfig()
            {
                OverrideTableName = "ClinMod-Analytics",
                BackwardQuery= true
                
            };

            var queryConfig = new QueryOperationConfig()
            {
                Filter = qf,
                Select = SelectValues.AllAttributes,
                Limit= 1,
            };

            var docs = await context.FromQueryAsync<Analytics>(queryConfig, opConfig).GetNextSetAsync();

            return docs[0];

I have tried flipping the value of BackwardQuery but that does not appear to change anything.

What am I doing wrong?

asked a year ago783 views
1 Answer
0

But don't both the 2nd and 3rd item match your condition of <= DASH-20221209-23:32:11? Given you've said LImit =1, it seems reasonable that just the 2nd item is returned?

Sorry if I've misunderstood!

EXPERT
answered a year ago
  • Thanks for the reply. Yes, I was expecting just one record back (as per the LIMIT) but I am trying to control which record I get back. As I am using the index I assumed I would get them back in the order implied by the index, instead, it seems that I am getting the record back in the order they were added to the table.

  • https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html says "Query results are always sorted by the sort key value" so yes, you get the records back in the order implied by the index. You're filtering for less than or equal to "DASH-20221209-23:32:11" and two records match - "DASH-20221209-22:04:01" and "DASH-20221209-22:52:26". In sorted order "DASH-20221209-22:04:01" is first, and this is the one you said you're getting back. Looks OK I think!

    To get the other record first, note that developer guide says "To reverse the order, set the ScanIndexForward parameter to false". You'll have to look up how this is surfaced in the C# SDK though.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions