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?

已提問 1 年前檢視次數 825 次
1 個回答
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!

專家
已回答 1 年前
  • 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.

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南