DynamoDB 使用排序键对数据进行排序不起作用

DynamoDB sorting data with sort key not working

我正在使用 dynamoDb 存储一些额外的信息,但我在整理数据时遇到了一些麻烦。

我有以下创建语法,其中有一个 storeIdnumber 键。我将 number 设置为排序键,但问题是数据根本没有排序。

$response = $dynamoDb->createTable([
    'TableName' => 'foo',
    'KeySchema' => [
        [
            'AttributeName' => 'storeId',
            'KeyType' => 'HASH'  //Partition key
        ],
        [
            'AttributeName' => 'number',
            'KeyType' => 'RANGE' // sort Key
        ]
    ],
    'AttributeDefinitions' => [
        [
            'AttributeName' => 'storeId',
            'AttributeType' => 'N'
        ],
        [
            'AttributeName' => 'number',
            'AttributeType' => 'N'
        ]
    ],
    'ProvisionedThroughput' => [
        'ReadCapacityUnits' => 20,
        'WriteCapacityUnits' => 20
    ]
]);

我的扫描参数:

$scanParams = [
    'TableName' => 'foo',
    'ProjectionExpression' => '#storeId, #number',
    'FilterExpression' => '#number >= :n',
    'ExpressionAttributeNames'=> [ '#storeId' => 'storeId', '#number' => 'number'],
    'ExpressionAttributeValues' => [
        ':n' => ['N' => $number]
    ]
];

我的扫描结果:

StoreId number
68001   80000
25000   37000
463501  527000
4800001 5300000
360001  400000
2000001 2600000

如您所见,数据未按数字 属性 排序。

请阅读下面的第一段。排序键用于存储具有相同分区键值的所有项,它们在物理上靠近在一起并默认按升序排序(即重要的一点是数据未跨分区键排序)。也就是说,对于同一个partition key,数据默认是升序排列的。

例子:-

分区键排序键

p1, s1

p1, s2

p1, s3

p2, s1

p2, s2

If the table has a composite primary key (partition key and sort key), DynamoDB calculates the hash value of the partition key in the same way as described in Data Distribution: Partition Key—but it stores all of the items with the same partition key value physically close together, ordered by sort key value.

To write an item to the table, DynamoDB calculates the hash value of the partition key to determine which partition should contain the item. In that partition, there could be several items with the same partition key value, so DynamoDB stores the item among the others with the same partition key, in ascending order by sort key.

To read an item from the table, you must specify its partition key value and sort key value. DynamoDB calculates the partition key's hash value, yielding the partition in which the item can be found.

在查询API中,有一个参数可以按升序或降序获取结果。

ScanIndexForward: true || false

ScanIndexForward —(布尔值)

指定索引遍历的顺序:如果为true(默认),则按升序进行遍历;如果为false,则按降序进行遍历。

具有相同分区键值的项目按排序键排序存储。如果排序键数据类型为数字,则结果按数字顺序存储。对于 String 类型,结果按 ASCII 字符代码值的顺序存储。对于二进制类型,DynamoDB 将二进制数据的每个字节视为无符号。

如果 ScanIndexForward 为 true,DynamoDB returns 结果按存储顺序(按排序键值)排列。这是默认行为。如果 ScanIndexForward 为 false,DynamoDB 按排序键值倒序读取结果,然后 returns 将结果发送给客户端。

Query API