DynamoDB: 提供的主键元素与模式不匹配

2024-07-08 10:20:50 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有方法根据不是哈希键的字段获取项?

示例

我的表用户:id (HashKey), name, email

我想检索电子邮件为'test@mail.com'的用户

怎么做?

我和博托一起试试这个:

user = users.get_item(email='john.doe@gmail.com')

我得到以下错误:

'The provided key element does not match the schema'

Tags: 方法用户nametestcomid示例get
3条回答

以下内容适用于AWS Lambda环境中的Node.js AWS SDK:

对我来说这是一个艰难的决定。我在尝试使用getItem方法时遇到了这个问题。不管我尝试了什么,我都会继续收到这个错误。我终于在AWS论坛上找到了一个解决方案:https://forums.aws.amazon.com/thread.jspa?threadID=208820

令人费解的是,这个明显的解决方案与我能找到的所有AWS文档都有冲突。

这是对我有用的代码:

var doc = require('dynamodb-doc');
var dynamo = new doc.DynamoDB();

var params = { }
params.TableName = "ExampleTable";
var key = { "ExampleHashKey": "1" };
params.Key = key;

dynamo.getItem(params, function(err, data) {
    if (err)
        console.log(err);
    else
        console.log(data)
});

要查询不是哈希键的字段,需要使用全局辅助索引(GSI)。查看this AWS Post了解有关GSI的更多详细信息

更新2015年2月:现在可以将GSI添加到现有表中。有关详细信息,请参见Amazon Docs

很遗憾,you cannot add a GSI to an existing DynamoDB table因此,如果确实需要查询数据,则需要创建一个新表并导入数据。

DynamoDB FAQ

Q: How do I create a global secondary index for a DynamoDB table?

All GSIs associated with a table must be specified at table creation time. At this time, it is not possible to add a GSI after the table has been created. For detailed steps on creating a Table and its indexes, see here. You can create a maximum of 5 global secondary indexes per table.

如果不想移植数据,可以考虑创建第二个DynamoDB表,将电子邮件作为散列键,将父记录的散列用作对主数据表的查找,但正如您所想象的,这并不是一个最佳的解决方案,而且还带来了与主数据表保持同步的麻烦桌子。

当我发送字符串而不是整数时,也出现了这个错误。

当然,这是我写数据库的时候,而不是读数据库的时候。

相关问题 更多 >

    热门问题