首页 > 解决方案 > 查询 DynamoDb 全局二级索引

问题描述

我正在本地试用 dynamodb 并得到下表:

"Table": {
    "AttributeDefinitions": [
        {
            "AttributeName": "hashKey",
            "AttributeType": "S"
        },
        {
            "AttributeName": "sortKey",
            "AttributeType": "S"
        },
        {
            "AttributeName": "full_json",
            "AttributeType": "S"
        }
    ],
    "TableName": "local",
    "KeySchema": [
        {
            "AttributeName": "hashKey",
            "KeyType": "HASH"
        },
        {
            "AttributeName": "sortKey",
            "KeyType": "RANGE"
        }
    ],
    "TableStatus": "ACTIVE",
    "CreationDateTime": "2021-10-01T15:18:04.413000+02:00",
    "ProvisionedThroughput": {
        "LastIncreaseDateTime": "1970-01-01T01:00:00+01:00",
        "LastDecreaseDateTime": "1970-01-01T01:00:00+01:00",
        "NumberOfDecreasesToday": 0,
        "ReadCapacityUnits": 5,
        "WriteCapacityUnits": 1
    },
    "TableSizeBytes": 1066813,
    "ItemCount": 23,
    "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/local",
    "GlobalSecondaryIndexes": [
        {
            "IndexName": "sortKeyIndex",
            "KeySchema": [
                {
                    "AttributeName": "sortKey",
                    "KeyType": "HASH"
                }
            ],
            "Projection": {
                "ProjectionType": "ALL"
            },
            "IndexStatus": "ACTIVE",
            "ProvisionedThroughput": {
                "ReadCapacityUnits": 10,
                "WriteCapacityUnits": 1
            },
            "IndexSizeBytes": 1066813,
            "ItemCount": 23,
            "IndexArn": "arn:aws:dynamodb:ddblocal:000000000000:table/local/index/sortKeyIndex"
        }
    ]
}

我想像这样用Java查询它:

Index index = table.getIndex("sortKeyIndex");
ItemCollection<QueryOutcome> items2 = null;
QuerySpec querySpec = new QuerySpec();
querySpec.withKeyConditionExpression("sortKey > :end_date")
                .withValueMap(new ValueMap().withString(":end_date","2021-06-30T07:49:22.000Z"));
items2 = index.query(querySpec);

但它会引发“不支持查询键条件”的异常。我不明白这一点,因为在文档中,“<”运算符被描述为常规操作。有谁能够帮助我

标签: javaamazon-web-servicesamazon-dynamodbaws-sdk

解决方案


DDB Query()需要一个键条件,其中包括对哈希/分区键的相等性检查。

您必须提供分区键属性的名称和该属性的单个值。查询返回具有该分区键值的所有项目。或者,您可以提供排序键属性并使用比较运算符来优化搜索结果。

换句话说,只有当你有一个复合主键(散列+排序)时,你才能真正使用 Query()。

如果没有将排序键指定为表/GSI 的键的一部分,Query() 的行为就像 GetItem() 返回具有给定哈希键的单个记录一样。


推荐阅读