DynamoDB Java SDK如何使用NOT EQUALS查询字符串字段

时间:2017-11-30 02:36:56

标签: java amazon-dynamodb aws-sdk

看起来没有" NOT EQUALS" QuerySpec withKeyConditionExpression或withFilterExpression中的比较运算符。我尝试做类似的事情:

new QuerySpec()
    .withKeyConditionExpression("#name <> :var_name AND #date > :var_date")
    .withNameMap(new NameMap()
        .with("#name", "name")
        .with("#date", "date"))
    .withValueMap(new ValueMap()
        .withString(":var_name","Unknown")
        .withString(":var_date", thirtyDaysAgo));

其中name不等于String&#34; Unknown&#34;。

但是,我得到了&#34; KeyConditionExpress中使用的无效运算符:&lt;&gt;。

有没有解决方法(除了从查询中排除条件并在内存中迭代结果)?

我发现以下文档引用了一个不相等的运算符,但看起来它在查询过滤器中不可用。

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html

Making Comparisons

Use these comparators to compare an operand against a range of values, or an enumerated list of values:

a = b — true if a is equal to b
a <> b — true if a is not equal to b
a < b — true if a is less than b
a <= b — true if a is less than or equal to b
a > b — true if a is greater than b
a >= b — true if a is greater than or equal to b

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

For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions, only the following comparison operators are supported:

EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN

Condition is also used in a QueryFilter, which evaluates the query results and returns only the desired values.

 NE : Not equal. NE is supported for all data types, including lists and maps.

AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. 

1 个答案:

答案 0 :(得分:0)

如果使用KeyConditionExpression,则必须指定单个分区键。 Documentation包括以下内容:

  

[KeyConditionExpression]条件必须对单个分区键值

执行相等性测试      

需要分区键相等性测试,并且必须按以下格式指定:

     

partitionKeyName =:partitionkeyval

您仍然可以执行查询,但使用Scan操作而不是“查询”。默认情况下,扫描会返回表格中的所有项目,因此您可以在过滤器表达式中使用运算符。

编辑:

Map<String, String> attributeNames = new HashMap<String, String >();
attributeNames.put("#name", "name");
attributeNames.put("#date", "date");

Map<String, AttributeValue> attributeValues = new HashMap<String, AttributeValue>();
attributeValues.put(":var_date", new AttributeValue().withN(thirtyDaysAgo));
attributeValues.put(":var_name", new AttributeValue().withS("Unknown"));

ScanRequest scanRequest = new ScanRequest()
        .withTableName(TABLE_NAME)
        .withFilterExpression("#name <> :var_name AND #date > :var_date")
        .withExpressionAttributeNames(attributeNames)
        .withExpressionAttributeValues(attributeValues)