我正在尝试使用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,Key和Partion
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、Key 和 Partition
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();
}