这是我从常规 DynamoDB 表切换到具有全局二级索引的 DynamoDB2 表的延续**。
所以我创建了如图所示的表 here然后添加以下两个元素:
table.put_item(data={'firstKey': 'key01', 'message': '{"firstKey":"key01", "comments": "mess 1 w/o secondKey"}'})
table.put_item(data={'firstKey': 'key02', 'secondKey':'skey01', 'message': '{"firstKey":"key02", "parentId":"skey01", "comments": "mess 2 w/ secondKey"}'})
我现在想要做的是通过 (i) 唯一的 firstKey
值或 (ii) 唯一的 secondKey
值检索项目。第一个很简单:
res1 = table.get_item(firstKey='key01')
res1['message']
我不知道如何做第二个。这不起作用:
res2 = table.get_item(secondKey='skey01')
生成提供的关键元素与架构不匹配
。好的,这是预期的。当我这样做时:
res2 = table.query(secondKey='skey01',index='secondKeyIndex')
我得到您必须指定多个要过滤的键
。
那么我该如何让它工作呢?请注意,当我拥有某个项目的 secondKey
值时,我不知道其对应的 firstKey
。
===== 更新:以下是我尝试过的其他一些方法:
这个
res2 = table.query(secondKey__eq='skey01',index='secondKeyIndex')
已制作
boto.dynamodb2.exceptions.QueryError: You must specify more than one key to filter on.
在下面的 block 中,查询
语句没有产生任何错误
res2 = table.query(secondKey='skey01',secondKey__eq='skey01',index='secondKeyIndex')
for r in res2:
print res2['secondKey']
但是print
给了我
boto.dynamodb2.exceptions.UnknownFilterTypeError: Operator 'secondKey' from 'secondKey' is not recognized.
最佳答案
可以使用LSI/GSI。
请参阅此处的 boto 教程(搜索 LSI,您将获得示例)。 DynamoDB2 — boto v2.25.0 : http://boto.readthedocs.org/en/latest/ref/dynamodb2.html
添加完整的工作示例(尝试使用本地发电机:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html)
conn = DynamoDBConnection(
host='localhost',
port=8000,
aws_access_key_id='DEVDB', #anything will do
aws_secret_access_key='DEVDB', #anything will do
is_secure=False)
tables = conn.list_tables()
print "Before Creation:", tables
table_name = 'myTable'
if table_name not in tables['TableNames']:
Table.create(table_name
, schema=[HashKey('firstKey')]
, throughput={'read': 5, 'write': 2}
, global_indexes=[
GlobalAllIndex('secondKeyIndex', parts=[HashKey('secondKey')], throughput={'read': 5, 'write': 3})]
, connection=conn
)
#print_table_details(conn, table_name)
table = Table(table_name, connection=conn)
item = Item(table, data={
'firstKey': str(uuid.uuid4()),
'secondKey': 'DUMMY-second'
})
item.save()
results = table.query(secondKey__eq='DUMMY-second', index='secondKeyIndex')
for res in results:
print res['firstKey'], res['secondKey']
执行结果为:
91d4d056-1da3-42c6-801e-5b8e9c42a93f DUMMY-second
15c17b09-4975-419a-b603-427e4c765f03 DUMMY-second
dd947b7d-935e-458f-84d3-ed6cd4f32f5a DUMMY-second
还添加确切的包(由于 Dynamo1/2 - 可能会出错):
from boto.dynamodb2.fields import HashKey, RangeKey, GlobalAllIndex
from boto.dynamodb2.layer1 import DynamoDBConnection
from boto.dynamodb2.table import Table
from boto.dynamodb2.items import Item
关于indexing - 如何仅使用 boto 2.25.0 通过全局二级索引查询 DynamoDB2 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21763312/