编写dynamoDB"OR"条件查询?

Val*_*ade 10 amazon-dynamodb

我想用boolean或条件查询dynamodb表,例如SQL Get me all the items where attribute1 = "no" or attribute2="no"

我试过scanRequest.withScanFilter但所有条件都是通过布尔运算来执行的.我该如何做布尔ORing.

Erb*_* Mo 8

您可以将ScanRequest的ConditionalOperator设置为"OR".默认值为"AND"

http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html

ScanRequest scanRequest = new ScanRequest("tableName");
scanRequest.setConditionalOperator(ConditionalOperator.OR);

Map<String, Condition> scanFilter = new HashMap<String, Condition>();
scanFilter.put("attribute1", new Condition().withAttributeValueList(new AttributeValue("no")).withComparisonOperator(ComparisonOperator.EQ));
scanFilter.put("attribute2", new Condition().withAttributeValueList(new AttributeValue("no")).withComparisonOperator(ComparisonOperator.EQ));

scanRequest.setScanFilter(scanFilter);
ScanResult scanResult = dynamo.scan(scanRequest);

for(Map<String, AttributeValue> item : scanResult.getItems()) {
    System.out.println(item);
}
Run Code Online (Sandbox Code Playgroud)

  • 小心使用扫描.您将收取扫描的所有行的费用,而不是返回的行.如果表包含大量数据,你真的应该永远不要在生产中使用扫描. (7认同)

bsd*_*bsd 5

如果您碰巧知道该HashKey值,则另一个选择是使用QUERY和FilterExpression。这是Java SDK的示例:

Table table = dynamoDB.getTable(tableName);

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

QuerySpec spec = new QuerySpec()
    .withHashKey("HashKeyAttributeName", "HashKeyValueHere")
    .withFilterExpression("attribute1 = :x  or attribute2 = :y")
    .withValueMap(expressionAttributeValues);


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

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

while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参见使用条件表达式指定条件

  • 请注意,过滤表达式对查询结果进行操作,并且您需要根据查询的大小付费。因此,如果您有大量与每个 hashKey 关联的数据,那么每次运行过滤表达式时您都会付出高昂的代价。 (2认同)

obo*_*zat 5

您还可以在 FilterExpression 中使用括号:

const params = {
  TableName: process.env.PROJECTS_TABLE,
  IndexName: 'teamId-createdAt-index',
  KeyConditionExpression: 'teamId = :teamId',
  ExpressionAttributeValues: {
    ':teamId': verifiedJwt.teamId,
    ':userId': verifiedJwt.userId,
    ':provider': verifiedJwt.provider
  },
  FilterExpression: 'attribute_exists(isNotDeleted) and ((attribute_not_exists(isPrivate)) or (attribute_exists(isPrivate) and userId = :userId and provider = :provider))'
};
Run Code Online (Sandbox Code Playgroud)