Javascript 使用哈希值数组的 AWS DynamoDB Scan 和 FilterExpression
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30218710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AWS DynamoDB Scan and FilterExpression using array of hash values
提问by jotamon
I am having a hard time finding a useful example for a scan with FilterExpression on a DynamoDB table. I am using the javascript SDK in the browser.
我很难找到一个有用的示例,用于在 DynamoDB 表上使用 FilterExpression 进行扫描。我在浏览器中使用 javascript SDK。
I would like to scan my table and return only those records that have HASH field "UID" values within an array I pass to the Scan
我想扫描我的表并只返回那些在传递给 Scan 的数组中具有 HASH 字段“UID”值的记录
Lets say I have an array of unique ids that are the hash field of my table I would like to query these records from my DynamoDB table.
假设我有一组唯一 ID,它们是我的表的哈希字段,我想从我的 DynamoDB 表中查询这些记录。
Something like below
像下面这样
var idsToSearch=['123','456','789'] //array of the HASH values I would like to retrieve
var tableToSearch = new AWS.DynamoDB();
var scanParams = {
"TableName":"myAwsTable",
"AttributesToGet":['ID','COMMENTS','DATE'],
"FilterExpression":"'ID' in "+idsToSearch+""
}
tableToSearch.scan(scanParams), function(err,data){
if (err) console.log(err, err.stack); //error handler
else console.log(data); //success response
})
采纳答案by mkobit
You should make use of the INoperator. It is also easier to use Placeholdersfor attribute names and attribute values. I would, however, advise against using a Scanin this case. It sounds like you already have the hash key attribute values that you want to find, so it would make more sense to use BatchGetItem.
您应该使用IN运算符。对属性名称和属性值使用占位符也更容易。但是,我建议不要Scan在这种情况下使用 a。听起来您已经拥有要查找的哈希键属性值,因此使用BatchGetItem.
Anyways, here is how you would do it in Java:
无论如何,以下是您在 Java 中的做法:
ScanSpec scanSpec = new ScanSpec()
.withFilterExpression("#idname in (:val1, :val2, :val3)")
.withNameMap(ImmutableMap.of("#idname", "ID"))
.withValueMap(ImmutableMap.of(":val1", "123", ":val2", "456", ":val23", "789"));
ItemCollection<ScanOutcome> = table.scan(scanSpec);
I would imagine using the Javascript SDK it would be something like this:
我想使用 Javascript SDK 会是这样的:
var scanParams = {
"TableName":"myAwsTable",
"AttributesToGet": ['ID','COMMENTS','DATE'],
"FilterExpression": '#idname in (:val1, :val2, :val3)',
"ExpressionAttributeNames": {
'#idname': 'ID'
},
"ExpressionAttributeValues": {
':val1': '123',
':val2': '456',
':val3': '789'
}
}
回答by tsuz
I had this issue and figured it out by using containsparameter
我遇到了这个问题并通过使用contains参数解决了这个问题
// Object stored in the DB looks like this:
// [
// 'name' => 'myName',
// 'age' => '24',
// 'gender' => 'Male',
// 'visited' => [
// 'countries': ['Canada', 'USA', 'Japan', 'Australia'],
// 'last_trip': '2015/12/13',
// 'reviews_written': 20
// ]
//
// ];
$countries = ['Canada', 'USA', 'Japan', 'Australia'];
$paramToMatch = '24';
$client->query([
'TableName' => 'MyDyanmoDB',
'KeyConditions' => [
'age' => [
'AttributeValueList' => [
$marshaler->marshalValue($paramToMatch)
],
'ComparisonOperator' => 'EQ'
]
],
'ExpressionAttributeNames' => [
'#visited' => 'visited',
'#countries' => 'countries'
],
'ExpressionAttributeValues' => [
':countries' => $marshaler->marshalValue($countries)
],
'FilterExpression' => 'contains(:countries, #visited.#countries)',
]);
回答by xke
Here's how I was able to use "scan" to get the items with a particular ID ("ContentID") in below example:
下面是我如何使用“扫描”来获取具有特定 ID(“ContentID”)的项目,如下例所示:
var params = {
TableName: environment.ddbContentTableName,
ProjectionExpression: "Title, ContentId, Link",
FilterExpression: "ContentId in (:contentId1, :contentId2, :contentId3, :contentId4),
ExpressionAttributeValues: {":contentId1":102,":contentId2":104,":contentId3":103,":contentId4":101}
};
var docClient = new AWS.DynamoDB.DocumentClient();
docClient.scan(params, onQuery);
I can then programmatically construct the FilterExpression and ExpressionAttributeValues based on known values e.g.
然后我可以根据已知值以编程方式构建 FilterExpression 和 ExpressionAttributeValues,例如
// Create the FilterExpression and ExpressionAttributeValues
var filterExpression = "ContentId in (";
var expressionAttributeValues = {};
for (var i = 0; i < currentFavorites.length; i++) {
var contentIdName = ":contentId"+(i+1);
if (i==0) {
filterExpression = filterExpression + contentIdName;
} else {
filterExpression = filterExpression + ", " + contentIdName;
}
expressionAttributeValues[contentIdName] = currentFavorites[i];
}
filterExpression = filterExpression + ")";
var params = {
TableName: environment.ddbContentTableName,
ProjectionExpression: "Title, ContentId, Link",
FilterExpression: filterExpression,
ExpressionAttributeValues: expressionAttributeValues
};
var docClient = new AWS.DynamoDB.DocumentClient();
docClient.scan(params, onQuery);
回答by javatogo
I was also looking for a dynamic solution, than having to manually put each of the parameter names into the conditional expression. Below is a solution:
我也在寻找一种动态解决方案,而不是手动将每个参数名称放入条件表达式中。下面是一个解决方案:
List<String> valList= new ArrayList<String>(); // Populate the Values in a List
StringJoiner valMap = new StringJoiner(","); // This will be the dynamic Value Map
int i=1;
table = dynamoDB.getTable(myTable);
StringBuilder filterExpression = new StringBuilder();
Map<String, Object> eav = new HashMap<String, Object>();
if(!valList.isEmpty())
{
for(String attrVal: valList)
{
eav.put(":val"+i, attrVal);
valMap.add(":val"+i);
i++;
}
filterExpression.append("attrColName in ("+valMap.toString()+")"); //here attrColName is the DB attribute
}
ItemCollection<ScanOutcome> items;
items = table.scan(
filterExpression.toString(), //FilterExpression
null, //ProjectionExpression - choose all columns
null, //ExpressionAttributeNames - not used in this example
eav);//ExpressionAttributeValues
回答by Gaurao Burghate
var params = {
TableName: "tableOne",
ProjectionExpression: "Title, ContentId, Link",
FilterExpression: "ContentId in (:contentIds)",
ExpressionAttributeValues: {":contentIds":[11,22,33,44,55]}
};
var docClient = new AWS.DynamoDB.DocumentClient();
docClient.scan(params);

