首页 文章

Dynamodb按排序顺序扫描

提问于
浏览
29

嗨,我有一个dynamodb表 . 我希望服务返回此表中的所有项目,顺序是通过对一个属性进行排序 .

我是否需要为此创建全局二级索引?如果是这种情况,那么散列键应该是什么,范围键是什么? (注意,对gsi的查询必须在GSI的散列键上指定“EQ”比较器 . )

谢谢你的日志!

厄尔本

3 回答

  • 16

    解决这个问题的方法是通过创建如下的全局二级索引 . 不确定这是否是最佳方法,但如果它对某人有用则发布 .

    Hash Key                 | Range Key
    ------------------------------------
    Date value of CreatedAt  | CreatedAt
    

    HTTP API用户的限制是指定检索数据的天数,默认为24小时 .

    这样,我总是可以将HashKey指定为当前日期,RangeKey可以在检索时使用>和<运算符 . 这样,数据也分布在多个分片上 .

  • 0

    如果您知道HashKey,那么任何查询都将返回按Range键排序的项目:

    "Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order use the ScanIndexForward parameter set to false."查询和扫描操作 - Amazon DynamoDB:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html

    现在,如果您需要返回“所有项目”,则表示扫描 . 我不认为你可以订购扫描结果 .

    另一种选择是使用GSI . (例如:https://stackoverflow.com/a/21786544/2959100) . 在这里,您可以看到GSI仅包含HashKey . 结果我猜是按照这个键的排序顺序(我还没在程序中查看这个部分!)

  • 3

    截至目前,dynamoDB scan 无法返回您的排序结果 .

    您需要将 query 与带有hashkey和range字段的新全局二级索引(GSI)一起使用 . 诀窍是使用一个hashkey,为表中的所有数据分配相同的值 .

    我建议为所有数据创建一个新字段并将其命名为“Status”并将值设置为“OK”或类似的东西 .

    然后您的查询以获得所有排序的结果将如下所示:

    {
        TableName: "YourTable",
        IndexName: "Status-YourRange-index",
        KeyConditions: {
            Status: {
                ComparisonOperator: "EQ", 
                AttributeValueList: [ 
                    "OK"
                ]
            }
        },
        ScanIndexForward: false
    }
    

    有关如何编写GSI查询的文档,请访问:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Querying

相关问题