30

在这样的 Azure Documentdb 文档中

{
"id": "WakefieldFamily",
"parents": [
    { "familyName": "Wakefield", "givenName": "Robin" },
    { "familyName": "Miller", "givenName": "Ben" }
],
"children": [
    {
        "familyName": "Merriam", 
        "givenName": "Jesse", 
        "gender": "female", 
        "grade": 1,
        "pets": [
            { "givenName": "Goofy" },
            { "givenName": "Shadow" }
        ]
    },
    { 
      "familyName": "Miller", 
      "givenName": "Lisa", 
      "gender": "female", 
      "grade": 8 
    }
],
  "address": { "state": "NY", "county": "Manhattan", "city": "NY" },
  "isRegistered": false
};

如何查询以获取宠物名称为“Goofy”的孩子?

看起来下面的语法无效

Select * from root r
WHERE r.children.pets.givenName="Goofy"

相反,我需要做

Select * from root r
WHERE r.children[0].pets[0].givenName="Goofy"

这并不是真正搜索数组。

关于我应该如何处理这些查询的任何建议?

4

2 回答 2

46

您应该利用 DocumentDB 的子句,该子句的操作与 RDBMJOIN中的操作有些不同(因为 DocumentDB 处理无模式文档的非规范化数据模型)。JOIN

简而言之,您可以将 DocumentDBJOIN视为自联接,可用于在嵌套的 JSON 对象之间形成交叉积。

在查询宠物名字为“Goofy”的孩子的上下文中,您可以尝试:

SELECT 
    f.id AS familyName,
    c AS child,
    p.givenName AS petName 
FROM Families f 
JOIN c IN f.children 
JOIN p IN c.pets
WHERE p.givenName = "Goofy"

返回:

[{
    familyName: WakefieldFamily,
    child: {
        familyName: Merriam,
        givenName: Jesse,
        gender: female,
        grade: 1,
        pets: [{
            givenName: Goofy
        }, {
            givenName: Shadow
        }]
    },
    petName: Goofy
}]

参考:http ://azure.microsoft.com/en-us/documentation/articles/documentdb-sql-query/

编辑:

您还可以使用如下ARRAY_CONTAINS所示的函数:

SELECT food.id, food.description, food.tags
FROM food
WHERE food.id = "09052" or ARRAY_CONTAINS(food.tags.name, "blueberries")
于 2014-12-09T23:14:53.190 回答
9

我认为 ARRAY_CONTAINS 函数自 2014 年得到回答以来发生了变化。我必须使用以下内容才能使其工作。

SELECT * FROM c
WHERE ARRAY_CONTAINS(c.Samples, {"TimeBasis":"5MIN_AV", "Value":"5.105"},true)

Samples是我的 JSON 数组,它包含具有许多属性的对象,包括上述两个。

于 2018-09-18T09:44:26.200 回答