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 年前826 查看次数
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.

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则

相关内容