2015-12-18 37 views
10

email属性が設定されていないすべての項目を検索するためにDynamoDBテーブルをクエリしようとしています。 emailフィールドを含むテーブルには、EmailPasswordIndexというグローバルセカンダリインデックスが存在します。DynamoDBで存在しない(null)属性をクエリする方法

var params = { 
    "TableName": "Accounts", 
    "IndexName": "EmailPasswordIndex", 
    "KeyConditionExpression": "email = NULL", 
}; 

dynamodb.query(params, function(err, data) { 
    if (err) 
     console.log(JSON.stringify(err, null, 2)); 
    else 
     console.log(JSON.stringify(data, null, 2)); 
}); 

結果:

{ 
    "message": "Invalid KeyConditionExpression: Attribute name is a reserved keyword; reserved keyword: NULL", 
    "code": "ValidationException", 
    "time": "2015-12-18T05:33:00.356Z", 
    "statusCode": 400, 
    "retryable": false 
} 

表の定義:インデックスはスパースであるために

var params = { 
    "TableName": "Accounts", 
    "KeySchema": [ 
     { "AttributeName": "id", KeyType: "HASH" }, // Randomly generated UUID 
    ], 
    "AttributeDefinitions": [ 
     { "AttributeName": "id", AttributeType: "S" }, 
     { "AttributeName": "email", AttributeType: "S" }, // User e-mail. 
     { "AttributeName": "password", AttributeType: "S" }, // Hashed password. 
    ], 
    "GlobalSecondaryIndexes": [ 
     { 
      "IndexName": "EmailPasswordIndex", 
      "ProvisionedThroughput": { 
       "ReadCapacityUnits": 1, 
       "WriteCapacityUnits": 1 
      }, 
      "KeySchema": [ 
       { "AttributeName": "email", KeyType: "HASH" }, 
       { "AttributeName": "password", KeyType: "RANGE" }, 
      ], 
      "Projection": { "ProjectionType": "ALL" } 
     }, 
    ], 
    ProvisionedThroughput: {  
     ReadCapacityUnits: 1, 
     WriteCapacityUnits: 1 
    } 
}; 

dynamodb.createTable(params, function(err, data) { 
    if (err) 
     console.log(JSON.stringify(err, null, 2)); 
    else 
     console.log(JSON.stringify(data, null, 2)); 
}); 
+0

テーブル属性とインデックス属性の定義を指定できますか? – mkobit

+0

@mkobit追加、ありがとう。 –

答えて

15

DynamoDBののグローバルセカンダリインデックスを許可します。つまり、項目のハッシュまたは範囲キーが定義されていないGSIがある場合、その項目はGSIには含まれません。これは、特定のフィールドを含むレコードを直接識別できるため、多くのユースケースで役立ちます。しかし、フィールドの欠如を探している場合、このアプローチはうまくいかないでしょう。

フィールドが設定されていないアイテムをすべて取得するには、フィルタを使用してスキャンすることをお勧めします。この操作は非常に高価になるだろうが、それは次のようなものを探して簡単なコードになります:

var params = { 
    TableName: "Accounts", 
    FilterExpression: "attribute_not_exists(email)" 
}; 

dynamodb.scan(params, { 
    if (err) 
     console.log(JSON.stringify(err, null, 2)); 
    else 
     console.log(JSON.stringify(data, null, 2)); 
}); 
0

フィールドが存在しない場合@jaredHatfieldは正しいですが、提出されたがnullの場合には動作しません。 NULLはキーワードであり、直接使用することはできません。 ExpressionAttributeValuesと一緒に使うことができます。

const params = { 
    TableName: "Accounts", 
    FilterExpression: "attribute_not_exists(email) or email = :null", 
    ExpressionAttributeValues: { 
     ':null': null 
    } 
} 

dynamodb.scan(params, (err, data) => { 
    if (err) 
     console.log(JSON.stringify(err, null, 2)); 
    else 
     console.log(JSON.stringify(data, null, 2)); 
}) 
関連する問題