41

Does Amazon DynamoDB scan operation allow you to query on nested attributes of type Array or Object? For example,

{
    Id: 206,
    Title: "20-Bicycle 206",
    Description: "206 description",
    RelatedItems: [
        341, 
        472, 
        649
    ],
    Pictures: {
        FrontView: "123", 
        RearView: "456",
        SideView: "789"
    }
}

Can I query on RelatedItems[2] or Pictures.RearView attributes?

AntoineB
  • 4,535
  • 5
  • 28
  • 61
Hiren
  • 708
  • 1
  • 7
  • 14

4 Answers4

34

Yes, you can use a Filter Expression, which is just like Condition Expression. The section that talks about the functions that you can use in these types of expressions mentions the following:

"For a nested attribute, you must provide its full path; for more information, see Document Paths."

The Document Paths reference has examples on how to reference nested attributes in DynamoDB data types like List (what you are calling an array) and Map (what you are calling an object). Check out that reference for examples on how to do so:

  • MyList[0]
  • AnotherList[12]
  • ThisList[5][11]
  • MyMap.nestedField
  • MyMap.nestedField.deeplyNestedField
readyornot
  • 2,783
  • 2
  • 19
  • 31
  • 1
    A caution that when using nested attributes with ExpressionAttributeNames the syntax is a little different than one might expect - you have to define each part of the path as a separate attribute name and then combine them with a dot in the FilterExpression (e.g. #pr.#1star): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html#Expressions.ExpressionAttributeNames.NestedAttributes – fenix.shadow Nov 02 '21 at 23:42
19

Please note that in DyanomoDB query and scan are quite different (scan is a much costlier operation). So while you can filter on both as pointed out by @coffeeplease; you can only query/index on:

The key schema for the index. Every attribute in the index key schema must be a top-level attribute of type String, Number, or Binary. Other data types, including documents and sets, are not allowed (ref).

Neil
  • 7,482
  • 6
  • 50
  • 56
4

Yes, you can by passing list or value.

data = table.scan(FilterExpression=Attr('RelatedItems').contains([1, 2, 3]) & Attr('Pictures.RearView').eq('1'))
abhimanyu
  • 730
  • 1
  • 10
  • 23
0

Yes, you can query on nested attributes of type array or object using scan or query .

Reference for Python boto3: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html#querying-and-scanning

Example: Suppose you want to find out records for which the RearView" > 500 and second item of RelatedItems" > 200, you can do the following:

data = table.scan(
    FilterExpression=Attr('RelatedItems[1]').gt('200') & Attr('Pictures.RearView').gt('500'))
colidyre
  • 4,170
  • 12
  • 37
  • 53
Sujata
  • 9
  • 1