我试图了解如何使用 DataModel 在 dynamo 中查询表。但是,我发现了两种似乎可行的方法,但我找不到正在发生的事情的解释或文档,或者它们之间是否有任何区别。
我发现的方法是使用Filter
或KeyExpression + FilterExpression
. 有什么区别和正确的做法?
一些例子:
选项1:
-- 带索引和键
public async Task<List<T>> Find<T>(Guid id)
{
var query = new QueryOperationConfig
{
IndexName = "Table_Id_Index",
Filter = new QueryFilter("TableId", QueryOperator.Equal, id)
};
return await _dynamoDbContext
.FromQueryAsync<T>(query)
.GetRemainingAsync();
}
-- 带有索引、键和额外的过滤
public async Task<List<T>> Find<T>(Guid id)
{
var query = new QueryOperationConfig
{
IndexName = "Table_Id_Index",
Filter = new QueryFilter("TableId", QueryOperator.Equal, id)
};
query.AddCondition("Deleted", ScanOperator.NotEqual, true);
return await _dynamoDbContext
.FromQueryAsync<T>(query)
.GetRemainingAsync();
}
-- 使用 GSI、密钥和分区
public async Task<List<T>> Find<T>(Guid id, string partitionKey)
{
var query = new QueryOperationConfig
{
IndexName = "GSI_Index",
Filter = new QueryFilter("TableId", QueryOperator.Equal, id)
};
query.AddCondition("PartitionKey", QueryOperator.Equal, partitionKey);
return await _dynamoDbContext
.FromQueryAsync<T>(query)
.GetRemainingAsync();
}
选项 2:
-- 带索引和键
public async Task<List<T>> Find<T>(Guid id)
{
var expressionAttributeValues = new Dictionary<string, DynamoDBEntry>();
expressionAttributeValues.Add(":v_TableId", id);
var queryOperationConfig = new QueryOperationConfig
{
IndexName = "Table_Id_Index",
KeyExpression = new Expression
{
ExpressionStatement = "TableId = :v_TableId"
ExpressionAttributeValues = expressionAttributeValues
}
};
var result = await _dynamoDBContext
.FromQueryAsync<T>(query)
.GetRemainingAsync();
}
-- 带有索引、键和额外的过滤
public async Task<List<T>> Find<T>(Guid id)
{
var expressionAttributeValues = new Dictionary<string, DynamoDBEntry>();
expressionAttributeValues.Add(":v_TableId", id);
var filterAttributes = new Dictionary<string, DynamoDBEntry>();
filterAttributes.Add(":v_Deleted", true);
var queryOperationConfig = new QueryOperationConfig
{
IndexName = "Table_Id_Index",
KeyExpression = new Expression
{
ExpressionStatement = "TableId = :v_TableId"
ExpressionAttributeValues = expressionAttributeValues
}
FilterExpression = new Expression
{
ExpressionStatement = "Deleted != :v_Deleted"
ExpressionAttributeValues = filterAttributes
};
};
var result = await _dynamoDBContext
.FromQueryAsync<T>(query)
.GetRemainingAsync();
}
-- 使用 GSI、密钥和分区
public async Task<List<T>> Find<T>(Guid id, string partitionKey)
{
var expressionAttributeValues = new Dictionary<string, DynamoDBEntry>();
expressionAttributeValues.Add(":v_TableId", id);
expressionAttributeValues.Add(":v_PartitionKey", partitionKey);
var queryOperationConfig = new QueryOperationConfig
{
IndexName = "GSI_Index",
KeyExpression = new Expression
{
ExpressionStatement = "TableId = :v_TableId and PartitionKey = :v_PartitionKey"
ExpressionAttributeValues = expressionAttributeValues
}
};
var result = await _dynamoDBContext
.FromQueryAsync<T>(query)
.GetRemainingAsync();
}