AWS ProjectionExpression with DynamoDBScanExpression
Matthew Barrera
I have a dynamodb table (named Student) with 17 columns. In this table I have columns like student_id, name, age ... . I want to get students with age > 18. This code snippet is giving List<Student>. But I want only List<String> i.e list containing only student_id's.
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); scanExpression.addFilterCondition("age", new Condition() .withComparisonOperator(ComparisonOperator.GT) .withAttributeValueList(new AttributeValue().withN(age)));I tried this: scanExpression.setProjectionExpression("student_id");
But it throws error. So what wrong am I doing here. And if there is any way to do this task with DynamoDBQueryExpression Also if I want multiple selective cols, suggest a method for the same
1 Answer
Your code sample is not enough for me to see how you execute the scan expression. Is it using a DynamoDBMapper, if so the result of the scan always returns List of Objects of the class to which the table is mapped to. Providing a projection expression will only limit the attributes returned (Refer to this). You still have to extract the student_id into a list after the scan result is returned.
List<Student> result = mapper.scan(Student.class, scanExpression);
List<String> studentIds = result .stream() .map(student -> student.getStudentId()) .collect(Collectors.toList());For more examples on Query and Scan refer to this AWS Documentation.
1