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

我有一个表,结构看起来像这样:

DynamoDB document

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

这是我到目前为止所拥有的:

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 中指定比较。

谢谢!


答案 1

尝试比较地图属性而不是整个地图结构: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. 确保变量具有表示为 的正确表名。tableNamestring

  2. 确保将字符串替换为表示 .HashKeyAttributeHash Key

  3. 请确保将字符串替换为表示要匹配的哈希键的值。HashKeyAttributeValue

  4. 确保匹配的记录具有比较表达式中提供的值。在示例中,提供了该值。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());
}

答案 2

推荐