【发布时间】:2019-02-05 06:39:31
【问题描述】:
我正在使用DocumentClient 进行查询。 并在 DynamoDb 中使用无服务器框架。
我正在尝试在不提供任何主键的情况下使用 BEGINS_WITH 进行查询。
这是我的数据的样子:
[
{
id: 1,
some_string: "77281829121"
},
{
id: 2,
some_string: "7712162hgvh"
},
{
id: 3,
some_string: "7212121"
}
]
这是我的serverless.yml [即我猜的表配置]:
Resources:
IPRecord:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: ${file(./serverless.js):Tables.IPRecord.name}
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: 'id'
AttributeType: 'S'
- AttributeName: 'some_string'
AttributeType: 'S'
KeySchema:
- AttributeName: 'id'
KeyType: 'HASH'
GlobalSecondaryIndexes:
- IndexName: ${file(./serverless.js):Tables.IPRecord.index.ID}
KeySchema:
# ...some more index goes here
- AttributeName: 'some_string'
KeyType: 'RANGE'
Projection:
ProjectionType: 'ALL'
问:
使用 DocumentClinet 我想查询some_string 的前几个元素。
这将返回所有匹配的文档。
就像在这种情况下,我想查询 {some_string:"77"} 它会返回
[{
id: 1,
some_string: "77281829121"
},
{
id: 2,
some_string: "7712162hgvh"
}]
目前我的查询看起来像这样 [这给出错误][在本地 DynamoDB JS shell 中运行]:
var params = {
TableName: '<TABLE_NAME>',
IndexName: '<INDEX_NAME>',
KeyConditionExpression: 'begins_with(some_string,:value)',
ExpressionAttributeValues: {
':value': '77'
}
};
docClient.query(params, function(err, data) {
if (err) ppJson(err);
else ppJson(data);
});
上面的查询似乎需要一个主键,在我的例子中是id。如果我通过它,那么它将指向一个文档。
这是我目前所取得的成就:
var params = {
TableName: '<TABLE_NAME>',
FilterExpression: 'begins_with(some_string,:value)',
ExpressionAttributeValues: {
':value': '77'
},
Select:'COUNT' //as i only required COUNT
};
docClient.scan(params, function(err, data) {
if (err) ppJson(err);
else ppJson(data);
});
上面的查询可以满足我的要求。但是 欢迎任何更好的方法或解决方案。
【问题讨论】:
-
您要解决的用例是什么,dynamodb 不支持无主键的开头。
-
@bestwishes 所以,我正在尝试获取所有文档,其中
some_string以say "77" 开头, -
那是计划 :) 行不通(至少用这种方法),但是 some_string 是什么,它们有什么关系,
-
对不起,我没能以正确的方式抓住你。但是是的
some_string是一个字符串字段,可以包含一个随机字符串。喜欢56uijkhfrtu。如果你看serverless.yml你也可以得到,我已经为此添加了GSI。
标签: amazon-dynamodb serverless-framework dynamodb-queries documentclient