[英]PynamoDB Error for Local Secondary Index: ValueError('Table table_4 has no index: key1_index',)
我是 pynamodb 的新手,我正在嘗試查詢 LSI(已在 dynamodb 主表中定義)並獲得以下異常。
'exception': ValueError('Table table_4 has no index: key1_index',)
用例:我只想在 LSI 上查詢 hash_key,因為我已經為 key1 (range_key) 提供了默認值,並希望根據 key1 獲取排序后的數據。
大規模集成電路 Model
class LSI_Index(LocalSecondaryIndex):
id = UnicodeAttribute(hash_key=True)
key1 = NumberAttribute(default=int(time.time()), range_key=True)
class Meta:
index = "key1-Index"
projection = IncludeProjection(['id', 'key1', 'key2'])
主表 Model
class MainModel(Model):
id = UnicodeAttribute(hash_key=True)
key2 = UnicodeAttribute(range_key=True, default='')
key1 = NumberAttribute(default=int(time.time()))
key1_index = LSI_Index() # LSI
class Meta:
.....
存儲庫方法代碼
def read_by_LSI(cls, id):
try:
data = []
iterator = MainModel.key1_index.query(hash_key=id,limit=1,scan_index_forward=False, consistent_read=True)
for item in iterator:
data.append(json.loads(json_dumps(item)))
return data
DynamoDB 主表說明:
{
"Table": {
"AttributeDefinitions": [
{
"AttributeName": "id",
"AttributeType": "S"
},
{
"AttributeName": "key1",
"AttributeType": "N"
}
],
"TableName": "table_4",
"KeySchema": [
{
"AttributeName": "id",
"KeyType": "HASH"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": 1647447620.911,
"ProvisionedThroughput": {
"LastIncreaseDateTime": 0.0,
"LastDecreaseDateTime": 0.0,
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 10,
"WriteCapacityUnits": 5
},
"TableSizeBytes": 779,
"ItemCount": 7,
"TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/table_4",
"LocalSecondaryIndexes": [
{
"IndexName": "key1-Index",
"KeySchema": [
{
"AttributeName": "id",
"KeyType": "HASH"
},
{
"AttributeName": "key1",
"KeyType": "RANGE"
}
],
"Projection": {
"ProjectionType": "INCLUDE",
"NonKeyAttributes": [
"key2",
"key1",
]
},
"IndexSizeBytes": 779,
"ItemCount": 7,
"IndexArn": "arn:aws:dynamodb:ddblocal:000000000000:table/table_4/index/key1-Index"
}
]
}
}
請告訴我哪里做錯了,因為我無法調試問題。 提前致謝。!!
所以基本上,在 pynamodb 中定義 LSI Model 時,請確保 Meta class 屬性名稱與文檔中提到的相同 - https://pynamodb.readthedocs.io/en/latest/indexes.html
在上面的例子中,我犯了以下錯誤,導致出現 ValueError('table table_4 doesn't have key1_index') 異常。
在 LSI_Model Class 的 MetaClass 中,我使用了錯誤的屬性名稱 'index' 而不是 'index_name'。 我已經更新了代碼,現在可以正常工作了。
class LSI_Index(LocalSecondaryIndex):
id = UnicodeAttribute(hash_key=True)
key1 = NumberAttribute(default=int(time.time()), range_key=True)
class Meta:
index_name = "key1-Index"
projection = IncludeProjection(['id', 'key1', 'key2'])
注意: LSI Meta Class 屬性應該命名如下(在文檔中提到):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.