2017-10-09 33 views
-1

在dynamodb中使用json如何搜索任何项目,其中session.id == "12ghbcyg"在python中使用boto3如何在dynamodb中使用boto3搜索地图列表

{ 
    "name": "John", 
    "sessions": [ 
     { 
      "id": "12ghbcyg", 
      "foo": "bar" 
     } 
    ] 
} 
+0

只需将它无法查询或单独扫描通过会话ID的数据。 DynamoDB没有此功能。您需要seesion id和foo才能找到该值。 – notionquest

+0

@notionquest你能证明吗?这也是可以接受的。 – Aaronepower

回答

1

以下是使用contains进行扫描的示例。请注意,如果表格有数百万个项目,则扫描操作成本很高。通常,如果您不知道分区键值,则使用扫描。即使您不知道分区键值,最推荐的解决方案是使用全局二级索引(GSI)并直接查询索引而不是表格。

您可能需要研究上述选项并确定适合您的用例的方法。

下面的代码是给出一个使用SCAN API使用包含的想法。如果知道分区键值,则可以在QUERY API上同样使用CONTAINS。

扫描使用包含: -

from __future__ import print_function # Python 2/3 compatibility 
import boto3 
from botocore.exceptions import ClientError 
import json 
import decimal 
from boto3.dynamodb.conditions import Key, Attr 

# Helper class to convert a DynamoDB item to JSON. 
class DecimalEncoder(json.JSONEncoder): 
    def default(self, o): 
     if isinstance(o, decimal.Decimal): 
      if o % 1 > 0: 
       return float(o) 
      else: 
       return int(o) 
     return super(DecimalEncoder, self).default(o) 

dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000") 

table = dynamodb.Table('usertable') 

print("Scanning...") 

sessionData = { 
     "id": "12ghbcyg", 
     "foo": "bar" 
     } 

fe = Attr('sessions').contains(sessionData) 

response = table.scan(
     FilterExpression=fe   
    ) 

for i in response['Items']: 

    print(json.dumps(i, cls=DecimalEncoder)) 

while 'LastEvaluatedKey' in response: 
    response = table.scan(  
     FilterExpression=fe,   
     ExclusiveStartKey=response['LastEvaluatedKey'] 
     ) 

    for i in response['Items']: 
     print(json.dumps(i, cls=DecimalEncoder))