DynamoDB:如何使用查询过滤器检查 MAP 中的条件

DynamoDB: How to use a query filter to check for conditions in a MAP

我有一个 table 结构如下:

当我做查询的时候,我希望能够在数据地图上做一个查询过滤;但我不确定如何设置查询。

这是我目前拥有的:

HashMap<String, AttributeValue> map = new HashMap<String, AttributeValue>();
map.put("byUserId", new AttributeValue().withS("vl49uga5ljjcoln65rcaspmg8u"));

queryExpression
    .withQueryFilterEntry("data", new Condition()
        .withAttributeValueList(new AttributeValue().withM(map))
        .withComparisonOperator(ComparisonOperator.CONTAINS));

但是我构建过滤器的方式不正确,我 运行 出现以下错误:

Exception in thread "main" com.amazonaws.AmazonServiceException: One or more parameter values were invalid: ComparisonOperator CONTAINS is not valid for M AttributeValue type (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: CHIOME68L1HVGO81URD7CIOS6BVV4KQNSO5AEMVJF66Q9ASUAAJG)
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
    at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.query(AmazonDynamoDBClient.java:1118)

那么我应该使用什么比较运算符(因为 IN 用于列表类型),以及如何构建查询过滤器以便我可以在 MAP 内指定比较。

谢谢!

尝试比较地图属性 data.byUserId 而不是整个地图结构:

Table table = dynamoDB.getTable(tableName);

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":x", "vl49uga5ljjcoln65rcaspmg8u");


QuerySpec spec = new QuerySpec()
    .withHashKey("HashKeyAttribute", "HashKeyAttributeValue")
    .withFilterExpression("data.byUserId = :x")
    .withValueMap(expressionAttributeValues);


ItemCollection<QueryOutcome> items = table.query(spec);

Iterator<Item> iterator = items.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}

一些重要的指南:

  1. 确保变量 tableName 具有正确的 table 名称,表示为 string.

  2. 确保将字符串 HashKeyAttribute 替换为代表您的 Hash Key.

  3. 的属性名称
  4. 确保将字符串 HashKeyAttributeValue 替换为代表您要匹配的哈希键的值。

  5. 确保匹配的记录具有比较表达式中提供的值的 data.byUserId。在示例中,提供了值 "vl49uga5ljjcoln65rcaspmg8u"

这是另一个将 id 属性作为哈希键的示例:

Table table = dynamoDB.getTable(tableName);

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":x", "vl49uga5ljjcoln65rcaspmg8u");


QuerySpec spec = new QuerySpec()
    .withHashKey("id", "25g77vmummpr4mc5mb9vq36q43")
    .withFilterExpression("data.byUserId = :x")
    .withValueMap(expressionAttributeValues);


ItemCollection<QueryOutcome> items = table.query(spec);

Iterator<Item> iterator = items.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}