user18163018
user18163018

Reputation: 3

Scan dynamodb table based on filter which is not present in all object

So I'm trying to filter my dynamoDb data based on role as you can see role attribute is present in some of the objects not in all


[
  {
    id: "7",
    email: '[email protected]',
    name: 'test1',
    age: '12',
  },
  {
    id: "8",
    email: '[email protected]',
    name: 'test2',
    age: '12',
  },
  {
    email: '[email protected]',
    name: 'test3',
    age: '12',
    test: 'test',
    role: 'ADMIN'
  },
  {
    email: '[email protected]',
    name: 'test4',
    age: '12',
    test: 'test',
    role: 'ADMIN'
  }
]

if I try to scan with email it works but if I try to scan with role its gives me error: Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: role

I tried with code

let params = {
  TableName: 'tableName',
  FilterExpression: 'role =:role',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  expressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();

and this

let params = {
  TableName: 'tableName',
  FilterExpression: 'attribute_not_exists(role)',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  expressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();

both giving me same error

Upvotes: 0

Views: 1377

Answers (1)

jellycsc
jellycsc

Reputation: 12259

I believe you had a typo in your first code snippet. FilterExpression: 'role =:role', should be FilterExpression: '#role =:role',.

So the following should work,

let params = {
  TableName: 'tableName',
  FilterExpression: '#role =:role',
  ExpressionAttributeValues: { ':role': 'ADMIN' },
  ExpressionAttributeNames: { '#role': 'role' }
}
let result = await this.docClient.scan(params).promise();

Upvotes: 2

Related Questions