我在Cosmos中有一个Azure DocumentDB json存储,我试图在集合中的集合上应用互斥的条件where子句。我期望查询的工作方式不会返回预期的结果!
假设我有一个产品类:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<ProductAttribute> ProductAttributes { get; set; }
}
具有ProductAttributes的集合,而ProductAttributes又包含字符串集合:
public class ProductAttribute
{
public string Name { get; set; }
public IEnumerable<string> AttributeValues { get; set; }
}
如果我创建2个示例产品并将它们添加到DocumentDB集合中:
var product = new Product
{
Id = 1,
Name = "Banana",
ProductAttributes = new List<ProductAttribute>
{
new ProductAttribute{Name = "SourceCountry",AttributeValues = new List<string>{ "COL", "HON", "SA" }},
new ProductAttribute{Name = "Colours",AttributeValues = new List<string>{ "Yellow" }},
}
};
var product1 = new Product
{
Id = 2,
Name = "Grape",
ProductAttributes = new List<ProductAttribute>
{
new ProductAttribute{Name = "SourceCountry",AttributeValues = new List<string>{ "FRA", "ITA", "SA" }},
new ProductAttribute{Name = "Colours",AttributeValues = new List<string>{ "Red", "Green" }},
}
};
文档存储为以下JSON:
{
"id": "1",
"name": "Banana",
"productAttributes": [
{
"name": "SourceCountry",
"attributeValues": [
"COL",
"HON",
"SA"
]
},
{
"name": "Colours",
"attributeValues": [
"Yellow"
]
}
]}
和
{
"id": "2",
"name": "Grape",
"productAttributes": [
{
"name": "SourceCountry",
"attributeValues": [
"FRA",
"ITA",
"SA"
]
},
{
"name": "Colours",
"attributeValues": [
"Red",
"Green"
]
}
]}
我想查询产品只返回那些在两种类型的ProductAttribute中都具有符合条件的属性。
以下关于单个属性的查询按预期返回两个产品(Grape和Banana都包含一个SourceCountry&#39; SA&#39;:
select p.name, p.productAttributes from c as p
join pa in p.productAttributes
join pav in pa.attributeValues
where (pa.name='SourceCountry' and pav = 'SA')
但是,我需要能够在两种类型的属性中应用标准,即SourceCountry&#39;和&#39;颜色&#39; - 所以我尝试了以下查询:
select p.name, p.productAttributes from c as p
join pa in p.productAttributes
join pav in pa.attributeValues
where (pa.name='SourceCountry' and pav = 'SA')
and (pa.name='Colours' and pav = 'Red')
我期待着'Grape&#39;要从上述查询返回,因为此产品是唯一一个同时拥有&#39; SourceCountry&#39; &#39; SA&#39;和一个颜色&#39; &#39; Red&#39;。
的属性然而,没有产品退回,我非常感谢有人可以解释为什么会这样!
答案 0 :(得分:1)
在黑暗中完全拍摄,但这可能有效:
select p.name, p.productAttributes from c as p
join pa in p.productAttributes
join pav in pa.attributeValues
join pa2 in p.productAttributes
join pav2 in pa2.attributeValues
where (pa.name='SourceCountry' and pav = 'SA')
and (pa2.name='Colours' and pav2 = 'Red')