简体   繁体   English

如何在我根据键值列表获取记录的地方查询 dynamodb?

[英]How to query dynamodb where I have fetch records based on a list of key values?

I have a dynamodb table on which a GSI is defined with a partition key and sort key.我有一个 dynamodb 表,在该表上使用分区键和排序键定义了 GSI。

Let's say the parition key is name and sort key is ssn for the GSI.假设分区键是name ,排序键是 GSI 的ssn

I have to fetch based upon a name and ssn, below is the query I am using and it works fine.我必须根据名称和 ssn 获取,下面是我正在使用的查询,它工作正常。

table.query(IndexName='lookup-by-name',KeyConditionExpression=Key('name').eq(name)\
                & Key('ssn').eq(ssn))

Now, I have to query based upon a name and a list of ssns.现在,我必须根据名称和 ssns 列表进行查询。

For Example例如

ssns=['ssn1','ss2','ss3',ssn4']
name='Alex'

query all records which has name as 'Alex' and whose ssn is present in ssns list.查询名称为“Alex”且其 ssn 存在于 ssns 列表中的所有记录。

How do I implement something like this?我该如何实施这样的事情?

While DynamoDB native SDK cannot provide the functionality to do this, you can achieve it using PartiQL which provides a SQL like interface for interacting with DynamoDB.虽然 DynamoDB 本机 SDK 无法提供执行此操作的功能,但您可以使用 PartiQL 实现它,它提供了一个类似于 SQL 的接口来与 DynamoDB 进行交互。

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-gettingstarted.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-gettingstarted.html

import boto3
client = boto3.client('dynamodb', region_name="eu-west-1")

name = 'Alex'
ssns = ['ssn1','ssn2','ssn3','ssn4']

response = client.execute_statement(
    Statement = "Select * from \"MyTableTest\".\"lookup-by-name\" where \"name\" = '%s' AND \"ssn\" IN %s" % (name, ssns)
)

print(response['Items'])

It would also require you to use the lower level Client instead of the Table level resource which you are using above.它还会要求您使用较低级别的Client而不是您在上面使用的Table级别资源。

You would have to do multiple queries.您将不得不进行多次查询。

Ended up using just the name as keycondition and then filter out the ssn in python code.最后仅使用名称作为关键条件,然后在 python 代码中过滤掉 ssn。

Below worked for me as the number of records was not a lot.下面对我有用,因为记录的数量不是很多。

response=table.query(IndexName='lookup-by-name',KeyConditionExpression=Key('name').eq(name)
ssns=['ssn1','ss2','ss3',ssn4']
data= response['Items']

data=list(filter(lambda record: record['ssn'] in ssns,data))
return data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM