在Boto3的DynamoDB中使用IN运算符 [英] Using IN operator in DynamoDB from Boto3

查看:135
本文介绍了在Boto3的DynamoDB中使用IN运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是DynamoDB的新手,它试图根据某个字段的某些值列表的存在来查询表。

I'm new to DynamoDB and trying to query a table based off the presence of a list of certain values for a field.

我有一个字段 doc_id ,它也是二级索引,我想返回所有结果其中 doc_id 包含在值列表中。

I have a field doc_id, which is also a secondary index, and I'd like to return all results where doc_id is contained in a list of values.

我正在尝试如下操作:

response = table.query(
IndexName='doc_id-index',
FilterExpression=In(['27242226'])
)

但显然这是不正确的。

But clearly that is not correct.

有人可以指出我正确的方向吗?

Can anyone point me in the right direction?

谢谢!

推荐答案


具有查询操作


with Query operation


FilterExpression可以不允许使用关键属性。您不能基于分区键或排序键定义过滤器表达式。

A FilterExpression does not allow key attributes. You cannot define a filter expression based on a partition key or a sort key.

因此,您的 doc_id 字段是 doc_id-index 的分区键,不能在FilterExpression中使用。

So, Your doc_id field is the partition key of the doc_id-index and cannot be used in FilterExpression.


注意

已读取项目后,将应用FilterExpression;

Note
A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units.

我假设您还有另一个字段,例如 userId ,只是为了演示如何实现IN操作。(查询)

I'm assuming you have another field like userId, just to show how to implement IN operation.(Query)

var params = {
    TableName: 'tbl',
    IndexName: 'doc_id-index',
    KeyConditionExpression: 'doc_id= :doc_id', 
    FilterExpression: 'userId IN (:userId1,:userId2)',//you can add more userId here

    ExpressionAttributeValues: {
         ':doc_id':100,
         ':userId1':11,
         ':userId2':12
                                 }

};



如果您有更多userId,则应动态传递给FilterExpression。


If you have more userId you should pass to FilterExpression dynamically.


但您可以使用扫描操作


but in your case, you can use Scan operation

var params = {
    TableName : "tbl",
    FilterExpression : "doc_id IN (:doc_id1, :doc_id2)",
    ExpressionAttributeValues : {
                   ":doc_id1" :100,
                   ":doc_id2" :101
                                 }
                    };

甚至像下面

var documentsId = ["100", "101","200",...];
var documentsObj = {};
var index = 0;
documentsId.forEach((value)=> {
    index++;
    var documentKey = ":doc_id"+index;
    documentsObj[documentKey.toString()] = value;
});

var params = {
    TableName: 'job',
    FilterExpression: 'doc_id IN ('+Object.keys(documentsObj).toString()+')',
    ExpressionAttributeValues: documentsObj,
};



注意:使用扫描时要小心操作,效率不如查询。


Note:be careful while using Scan operation, less efficient than Query.

这篇关于在Boto3的DynamoDB中使用IN运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆