[英]Create GSI on an attribute which has the value of Set
所以我想創建一個簡單的 Dynamodb 表,稱為提醒,目前有 3 列:
reminder_id
:這是 hash 密鑰reminder_tag
:我想在這個字段上有一個全局二級索引。 但同時我想確保標簽屬性應該具有 Set 的數據類型。 因為提醒上可以有多個標簽。reminder_title
:我也想在這個字段上有一個全局二級索引。 這將是一個字符串字段。我檢查了文檔: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#valid-dynamodb-types ,了解 Boto3 中可用的可能數據類型。
所以我想出了這個腳本:
import boto3
def create_reminders_table():
"""Just create the reminders table."""
session = boto3.session.Session(profile_name='dynamo_local')
dynamodb = session.resource('dynamodb', endpoint_url="http://localhost:8000")
table = dynamodb.create_table(
TableName='Reminders',
KeySchema=[
{
'AttributeName': 'reminder_id',
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': 'reminder_id',
'AttributeType': 'S'
},
{
'AttributeName': 'reminder_tag',
'AttributeType': 'SS'
},
{
'AttributeName': 'reminder_title',
'AttributeType': 'S'
}
],
GlobalSecondaryIndexes=[
{
'IndexName': 'ReminderTagGsi',
'KeySchema': [
{
'AttributeName': 'reminder_tag',
'KeyType': 'HASH'
}
],
'Projection': {
'ProjectionType': 'INCLUDE',
'NonKeyAttributes': [
'reminder_title'
]
}
},
{
'IndexName': 'ReminderTitleGsi',
'KeySchema': [
{
'AttributeName': 'reminder_title',
'KeyType': 'HASH'
}
],
'Projection': {
'ProjectionType': 'KEYS_ONLY'
}
}
],
BillingMode='PAY_PER_REQUEST'
)
return table
if __name__ == '__main__':
movie_table = create_reminders_table()
print("Table status:", movie_table.table_status)
但是當我運行它時,我遇到了以下問題:
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateTable operation: Member must satisfy enum value set: [B, N, S]
我搜索並遇到了有相同問題的人提出的這個問題: https://forums.aws.amazon.com/thread.jspa?messageID=613970
有人可以幫我解決這個問題,因為不提供數據類型的解決方案也不起作用。
也可以在具有 Set 值的屬性上建立索引嗎? 我的意思是我應該讓用戶能夠搜索帶有標簽的提醒,為此我需要一套。
請有人幫助我解決這個問題。
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html
“每個主鍵屬性必須是一個標量(意味着它只能包含一個值)。 主鍵屬性允許的唯一數據類型是字符串、數字或二進制。 對於其他非關鍵屬性則沒有此類限制。”
是否可以在值為 Set 的屬性上建立索引?
不,正如CreateTable文檔所說,“KeySchema 中的屬性也必須在 AttributeDefinitions 中定義”,數據類型為 (S)tring、(N)umber 或 (B)inary。
使用戶能夠搜索帶有標簽的提醒,為此我需要一套。
一對多關系的 DynamoDB 解決方法是復合排序鍵,如urgent#work
。 不過,這只適用於少量固定數量的標簽。
您最不壞的選擇是按用戶查詢(並可能使用某些排序鍵進一步縮小范圍),然后按 DynamoDB 外部的標簽成員資格過濾結果。 (注意IN
運算符不能在查詢的FilterConditionExpression中使用,因此它在這里對您沒有用)。
我想在
reminder_title
上有一個全局二級索引
reminder_title
不適合作為索引主鍵。 索引(和表)的Primary Key
必須確保每條記錄的唯一性。 標題可能不會。 您可能需要 3 個元素的組合,即user_id
、 request_id
和title
,以確保跨記錄的鍵唯一性。
考慮一個復合主鍵,例如, Partition Key
的user_id
(= HASH
) 和連接title#request_id
的新列 ( SK
) 中的復合排序鍵。 然后,您將按用戶按標題搜索:
user_id="Zaphod" AND begins_with(SK, "exercise")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.