database 如何从 DynamoDB 获取项目计数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27316643/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:51:21  来源:igfitidea点击:

How to get item count from DynamoDB?

databaseamazon-dynamodb

提问by sam lee

I want to know item count with DynamoDB querying.

我想通过 DynamoDB 查询了解项目计数。

I can querying for DynamoDB, but I only want to know 'total count of item'.

我可以查询 DynamoDB,但我只想知道“项目总数”。

For example, 'SELECT COUNT(*) FROM ... WHERE ...' in MySQL

例如,'SELECT COUNT(*) FROM ... WHERE ...' 在 MySQL 中

$result = $aws->query(array(
 'TableName' => 'game_table',
 'IndexName' => 'week-point-index',
 'KeyConditions' => array(
    'week' => array(
        'ComparisonOperator' => 'EQ',
        'AttributeValueList' => array(
            array(Type::STRING => $week)
        )
    ),
    'point' => array(
        'ComparisonOperator' => 'GE',
        'AttributeValueList' => array(
            array(Type::NUMBER => $my_point)
        )
    )
 ),
));
echo Count($result['Items']);

this code gets the all users data higher than my point.

此代码使所有用户数据高于我的观点。

If count of $result is 100,000, $result is too much big. And it would exceed the limits of the query size.

如果 $result 的计数为 100,000,则 $result 太大了。它会超出查询大小的限制。

I need help.

我需要帮助。

采纳答案by mkobit

You can use the Selectparameter and use COUNTin the request. It "returns the number of matching items, rather than the matching items themselves". Important, as brought up by Saumitra R. Bhave in a comment, "If the size of the Query result set is larger than 1 MB, then ScannedCount and Count will represent only a partial count of the total items. You will need to perform multiple Query operations in order to retrieve all of the results".

您可以使用该Select参数并COUNT在请求中使用。它“返回匹配项的数量,而不是匹配项本身”。重要的是,正如Saumitra R. Bhave 在评论中提出的“如果 Query 结果集的大小大于 1 MB,则 ScannedCount 和 Count 将仅表示总项目的部分计数。您将需要执行多个查询操作以检索所有结果”

I'm Not familiar with PHP but here is how you could use it with Java. And then instead of using Count(which I am guessing is a function in PHP) on the 'Items'you can use the Countvalue from the response- $result['Count']:

我不熟悉 PHP,但这里是如何将它与 Java 一起使用。然后Count'Items'您可以使用Count响应中值,而不是使用(我猜是 PHP 中的函数)- $result['Count']

final String week = "whatever";
final Integer myPoint = 1337;
Condition weekCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.EQ)
        .withAttributeValueList(new AttributeValue().withS(week));
Condition myPointCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.GE)
        .withAttributeValueList(new AttributeValue().withN(myPoint.toString()))

Map<String, Condition> keyConditions = new HashMap<>();
keyConditions.put("week", weekCondition);
keyConditions.put("point", myPointCondition);

QueryRequest request = new QueryRequest("game_table");
request.setIndexName("week-point-index");
request.setSelect(Select.COUNT);
request.setKeyConditions(keyConditions);

QueryResult result = dynamoDBClient.query(request);
Integer count = result.getCount();

If you don't need to emulate the WHEREclause, you can use a DescribeTablerequest and use the resulting item count to get an estimate.

如果您不需要模拟该WHERE子句,则可以使用DescribeTable请求并使用结果项目计数来获得估计值。

The number of items in the specified table. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.

指定表中的项目数。DynamoDB 大约每六小时更新一次该值。最近的更改可能不会反映在此值中。

回答by Daniel Bubenheim

With the aws dynamodb cliyou can get it via scanas follows:

使用aws dynamodb cli,您可以通过扫描获取它,如下所示:

aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"

The response will look similar to this:

响应将类似于以下内容:

{
    "Count": 123,
    "ScannedCount": 123,
    "ConsumedCapacity": null
}

notice that this information is in real time in contrast to the describe-tableapi

请注意,与描述表api相比,此信息是实时的

回答by coder007

Can be seen from UI as well. Go to overview tab on table, you will see item count. Hope it helps someone.

也可以从 UI 中看到。转到表格上的概览选项卡,您将看到项目数。希望它可以帮助某人。

回答by ymerej

If you happen to reach here, and you are working with C#, here is the code:

如果您碰巧到达这里,并且正在使用 C#,则代码如下:

var cancellationToken = new CancellationToken();

var request = new ScanRequest("TableName") {Select = Select.COUNT};

var result = context.Client.ScanAsync(request, cancellationToken).Result;

totalCount = result.Count;

回答by Ravi Ranjan

Replace the table name and use the below query to get the data on your local environment:

替换表名并使用以下查询获取本地环境中的数据:

aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT" --endpoint-url http://localhost:8000

Replace the table name and remove the endpoint url to get the data on production environment

替换表名并删除端点url以获取生产环境的数据

aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"

回答by jajhonrod

Similar to Java in PHP only set Select PARAMETER with value 'COUNT'

类似于 PHP 中的 Java 仅设置 Select PARAMETER 值为 'COUNT'

$result = $aws->query(array(
 'TableName' => 'game_table',
 'IndexName' => 'week-point-index',
 'KeyConditions' => array(
    'week' => array(
        'ComparisonOperator' => 'EQ',
        'AttributeValueList' => array(
            array(Type::STRING => $week)
        )
    ),
    'point' => array(
        'ComparisonOperator' => 'GE',
        'AttributeValueList' => array(
            array(Type::NUMBER => $my_point)
        )
    )
 ),
 'Select' => 'COUNT'
));

and acces it just like this :

并像这样访问它:

echo $result['Count'];

回声 $result['Count'];

but as Saumitramentioned above be careful with resultsets largers than 1 MB, in that case use LastEvaluatedKey til it returns null to get the last updated count value.

但正如上面提到的Saumitra 对大于 1 MB 的结果集要小心,在这种情况下,使用 LastEvaluatedKey 直到它返回 null 以获得最后更新的计数值。

回答by RendezAWS

len(response['Items'])

will give you the count of the filtered rows

会给你过滤的行数

where,

在哪里,

fe = Key('entity').eq('tesla')
response = table.scan(FilterExpression=fe)

回答by Feng Han

You could use dynamodb mapper query.

您可以使用 dynamodb 映射器查询。

PaginatedQueryList<YourModel> list = DymamoDBMapper.query(YourModel.class, queryExpression);
int count = list.size();

it calls loadAllResults()that would lazily load next available result until allResultsLoaded.

它调用loadAllResults()会延迟加载下一个可用结果,直到 allResultsLoaded。

Ref: https://docs.amazonaws.cn/en_us/amazondynamodb/latest/developerguide/DynamoDBMapper.Methods.html#DynamoDBMapper.Methods.query

参考:https: //docs.amazonaws.cn/en_us/amazondynamodb/latest/developerguide/DynamoDBMapper.Methods.html#DynamoDBMapper.Methods.query

回答by user1977823

I used scan to get total count of the required tableName.Following is a Java code snippet for same

我使用 scan 来获取所需 tableName 的总数。以下是相同的 Java 代码片段

Long totalItemCount = 0;
do{
    ScanRequest req = new ScanRequest();
    req.setTableName(tableName);

    if(result != null){
        req.setExclusiveStartKey(result.getLastEvaluatedKey());
    }

    result = client.scan(req);

    totalItemCount += result.getItems().size();

} while(result.getLastEvaluatedKey() != null);

System.out.println("Result size: " + totalItemCount);

回答by Joshua David Lickteig

In Scala:

在斯卡拉:

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder
import com.amazonaws.services.dynamodbv2.document.DynamoDB
val client = AmazonDynamoDBClientBuilder.standard().build()

val dynamoDB = new DynamoDB(client)
val tableDescription = dynamoDB.getTable("table name").describe().getItemCount()