首页 文章

如何使用Java设置DynamoDB返回的匹配项的限制?

提问于
浏览
6

在我的Android应用中,我想查询DynamoDB中的数据 . 将有一千个匹配的项目,但我只想获得它们中的前十个 . 我不知道如何设置这个限制 . 我在文档中找到了这些行:

DynamoDB查询和扫描API允许限制值限制结果的大小 .

在请求中,将Limit参数设置为您希望DynamoDB在返回结果之前处理的项目数 .

In a response, DynamoDB returns all the matching results within the scope of the Limit value. For example, if you issue a Query or a Scan request with a Limit value of 6 and without a filter expression, DynamoDB returns the first six items in the table that match the specified key conditions in the request (or just the first six items in the case of a Scan with no filter). If you also supply a FilterExpression value, DynamoDB will return the items in the first six that also match the filter requirements (the number of results returned will be less than or equal to 6).

但我找不到设定响应限制的方法 . 我找到了QueryResult的方法SetCount:

QueryResult result2 = dynamodb.query(request);
    result2.setCount(5);

它说: then Count is the number of items returned after the filter was applied

但我认为这不是我想要的 . 因为DynamoDb在调用setCount之前仍会返回所有匹配项 . 谁能帮我?

2 回答

  • 0

    您需要将限制作为发送给API的请求的一部分,而不是响应 .

    我假设您提交给dynamodb对象的请求对象是QuerySpec . 您要做的是调用withMaxResultSize以在针对API运行查询之前传递您想要应用的限制 .

    但是,正如您在问题中提到的,您需要确保了解Limits上DynamoDB文档中描述的限制行为:

    在响应中,DynamoDB返回Limit值范围内的所有匹配结果 . 例如,如果发出限制值为6且没有过滤器表达式的查询或扫描请求,DynamoDB将返回表中与请求中指定的键条件匹配的前六项(或仅返回前六项)扫描没有过滤器的情况) . 如果还提供FilterExpression值,DynamoDB将返回前六个中与过滤器要求匹配的项目(返回的结果数将小于或等于6) .

    这意味着如果你没有使用FilterExpression,你可能会很好 . 但是,如果要过滤结果,则可能会收到少于限制的结果,因为技术上限制不是要返回的结果数,而是DynamoDB可能返回的项数 .

    听起来你想要一种方法让DynamoDB在应用FilterExpression的同时将它返回的结果数量限制为一个确切的数字 . 不幸的是,目前DynamoDB无法实现这一目标 .

  • 4

    这是使用aws-java-sdk ver 1.10.61限制查询结果的方法

    import com.amazonaws.AmazonClientException;
    import com.amazonaws.auth.AWSCredentialsProvider;
    import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
    import com.amazonaws.regions.Region;
    import com.amazonaws.regions.Regions;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.ItemCollection;
    import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
    import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; 
    
    
    
    AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBAsyncClient client = new AmazonDynamoDBAsyncClient(provider);
    Region region = Region.getRegion(Regions.fromName(DYNAMODB_REGION));
    client.setRegion(region);
    dynamoDB = new DynamoDB(client);
    
    QuerySpec querySpec = new QuerySpec();
    
    /* MAX 1 item */
    querySpec.setMaxResultSize(1);
    
    querySpec.withHashKey("myPartitionKeyName", partitionKeyValue);
    
    ItemCollection<QueryOutcome> query = dynamoDB.getTable(DYNAMODB_TABLE).query(querySpec);
    

相关问题