Search code examples
javaamazon-dynamodbdynamodb-queriesdynamodb-mapper

Ho to use contains function in DynamoDB with DynamoDBMapper Java?


I need to check list of data with contains function is DynamoDB. Following is my Java Code,

List<String> dataList = new ArrayList<>();

I am inserting the above list inside a JSON called Data.

Map<String, AttributeValue> valueMap = new HashMap<>();
valueMap.put(":v", new AttributeValue().withS(String.valueOf(dataList)));

Map<String, String> nameMap = new HashMap<>();
nameMap.put("#list", "Data.list");

DynamoDBQueryExpression<> queryExpression = new DynamoDBQueryExpression<>()
                .withFilterExpression("contains(#list, :v)")
                .withExpressionAttributeNames(nameMap)
                .withExpressionAttributeValues(valueMap)
                .withConsistentRead(false);

I used the above approach but it is not working. What I need is I need to filter data if any of the list values contains in the dynamo db inserted list values. The list data is inside Json. So what I am doing wrong here? can anybody help me? Thanks in advance.


Solution

    1. Your query doesn't has the withKeyConditionExpression as part of building DynamoDBQueryExpression.
    2. FilterExpression is not improving your RCUs consumption. It adds very little value. I prefer having clean query objects ( ddbMapper.query(Object) ) and filtering post getting response.

    From the docs -

    A filter expression is applied after a Query finishes, but before the results are returned. Therefore, a Query consumes the same amount of read capacity, regardless of whether a filter expression is present.

    Note: If still looking to do it in DynamoDB query, you need to ensure that AttributeValue type provided is correct.

    From the docs -

    An attribute of type String Set. For example:
    "SS": ["Giraffe", "Hippo" ,"Zebra"]
    Type: Array of strings

    So, here change from new AttributeValue().withS to new AttributeValue().withSS to apply over list. Note that, you will still need to bring your object down to AttributeValue granularity which DDB understands.

    This doc has more advanced samples.