简体   繁体   中英

Not Equal - Range Key android AWS Dynamo DB

Is there a way to query AWS DynamoDB by setting the range key to NOT EQUAL a value.

I have the following code which I hoped would work:

Condition rangeKey = new Condition()
                    .withComparisonOperator(ComparisonOperator.NE)
                    .withAttributeValueList(new 
AttributeValue().withS(TestArray[0]));

            conditionHashMap.put("ID", rangeKey);


        queryExpression
                .withIndexName("Index Key")
                .withHashKeyValues(KEYVALUE)
                .withRangeKeyConditions(conditionHashMap)
                .withConsistentRead(false);

But it always throws the following error:

Attempted conditional constraint is not an indexable operation

tried changing the ComparisonOperator to NOT_CONTAINS but same problem. Looked through a load of articles and it seems that there are a number of restrictions on conditional operators on queries.

The question is. Is there a work around that would give the same result as a not equal or Not Contains?

NOT EQUALS can't be used on KeyConditionExpression for a RANGE key. However, you can use the NOT EQUALS condition on FilterExpression for a RANGE key.

Example:-

In the below example, I am looking for movies with partition key '2014' and range key not equals to 'The Big New Movie'. Similarly, you can do for your scenario.

QuerySpec querySpec = new QuerySpec();

querySpec.withKeyConditionExpression("yearkey = :yearval").withFilterExpression("title <> :titleval")
            .withValueMap(new ValueMap().withNumber(":yearval", 2014).withString(":titleval", "The Big New Movie"));

While @notionquest's statement that Not Equals cannot be used in KeyConditionExpression but CAN be used in FilterExpression is correct, his proposed solution is incorrect. FilterExpressions cannot be used on the hash or range key of the table.

Other solutions:

  1. Create a secondary index with your range key as an attribute (not a key) and use a FilterExpression on that attribute.
  2. Perform an in-code check before using the data to filter out the undesired value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM