查询具有相同 属性 但类型不同的 属性 的 CosmosDB 集合
Querying CosmosDB Collection with property that have the same property but with different types
假设我有一个 Cosmos Db 集合,其中包含由这 2 个解释的文档 类
public class DocumentBase {
public string DocumentType {get; set;}
}
public class DocumentA : DocumentBase {
public string PropertyA {get; set;}
}
public class DocumentB : DocumentBase {
public string[] PropertyA {get; set;}
}
如何查询此集合,对于 DocumentA,子句是 PropertyA = value,对于 DocumentB,子句是 PropertyA contains Value?
需要根据输入值自动生成查询。
编辑:更新了问题内容。
您可以在 Cosmos 中逻辑分隔您的文档,以确保您查询的是正确的文档。我使用了两种方法:
- 使用
type
属性区分类型
- 使用类型作为(the/part 的)分区键
在任何一种情况下,您都可以将类型添加为查询的一部分,可以像 WHERE c.type = 'DocumentA' AND ... <other expressions>
这样的 WHERE 子句,也可以在按类型分区时仅使用 SDK 操作中的分区键。
使用此设置,使用不同的表达式类型查询同名的 属性 没有问题。当然,使用不同的名称可能会更容易混淆。
您可以使用下面的查询。如果 propA
未定义或不是适当的类型,则该部分表达式会导致 false
并且不会抛出任何错误。因此您可以安全地查询这两种类型。
SELECT * FROM c
WHERE ARRAY_CONTAINS(c.propA, "myValue") OR c.propA = "myValue"
假设我有一个 Cosmos Db 集合,其中包含由这 2 个解释的文档 类
public class DocumentBase {
public string DocumentType {get; set;}
}
public class DocumentA : DocumentBase {
public string PropertyA {get; set;}
}
public class DocumentB : DocumentBase {
public string[] PropertyA {get; set;}
}
如何查询此集合,对于 DocumentA,子句是 PropertyA = value,对于 DocumentB,子句是 PropertyA contains Value? 需要根据输入值自动生成查询。
编辑:更新了问题内容。
您可以在 Cosmos 中逻辑分隔您的文档,以确保您查询的是正确的文档。我使用了两种方法:
- 使用
type
属性区分类型 - 使用类型作为(the/part 的)分区键
在任何一种情况下,您都可以将类型添加为查询的一部分,可以像 WHERE c.type = 'DocumentA' AND ... <other expressions>
这样的 WHERE 子句,也可以在按类型分区时仅使用 SDK 操作中的分区键。
使用此设置,使用不同的表达式类型查询同名的 属性 没有问题。当然,使用不同的名称可能会更容易混淆。
您可以使用下面的查询。如果 propA
未定义或不是适当的类型,则该部分表达式会导致 false
并且不会抛出任何错误。因此您可以安全地查询这两种类型。
SELECT * FROM c
WHERE ARRAY_CONTAINS(c.propA, "myValue") OR c.propA = "myValue"