简体   繁体   中英

Querying nested subtrees in Cosmos DB

Let's say I have a parent-child-grandchild-etc relationship in a Cosmos document, represented by the following JSON:

"id": "someUniqueString",
"peepsNkids": [
    "Jane": [
        "Joe": [],
        "Jocelyn": [
            "Jerry": [],
            "Jan": [
                "Tom": [],
                "Dick": [],
                "Harry": []
            ],
            "Jim": []
        ],
    "Mary": [
        "Moe": [],
        "Larry": [],
        "Dorothy": [
            "Eadie": [],
            "Phil": [],
            "Lucille": [
                "Desi Jr": []
            ]
        ]
    ]
]

How can I query cleanly (in Storage Explorer and C#) for a subtree that, using the syntax of the "Sub-documents" section of this post titled "Query DocumentDB" , would resolve to:

SELECT * FROM peepsNkids.Jane.Jocelyn.Jan

... with the expectation that the following would be returned?

[
    "Tom": [],
    "Dick": [],
    "Harry": []
]

I don't think I need to worry about the original id here. Worst case is that I get back multiple records that have Jane.Jocelyn.Jan , and since in my "real" setup the "names" are all unique ids, getting back multiple rows would indicate a serious schematic issue.

I can obviously create a potentially cyclical object model with string name and List<PersonAndKids> peepsNkids , then get back the full entry for the id "someUniqueString" and then traverse the objects with lots of peepsNkids.TryGetValue("Jane", out firstParent) kinds of stuff, but I'm looking for a way to do that in Cosmos rather than in my service's memory.

Nested query does not work

Your mistake appears to be believing that you have to query a sort of "nested table" like you mention in your question with this...

SELECT * FROM c.peepsNkids.Jane.Jocelyn.Jan

Now you're right, that's exactly what's demonstrated as a nested query in the link you provided , which includes this query:

SELECT * 
FROM Families.address.state

I don't see a way to execute that in Storage Explorer. It would be interesting to find out how to use this construction or if it's possible.

Composite field equivalent

It is, however, possible to do an equivalent query that selects a sort of "composite field" that equates to a table. Try this:

SELECT peepsNkids.Jane.Jocelyn.Jan FROM c

Or, better yet, to constrain that query to a specific document by id, try this:

SELECT peepsNkids.Jane.Jocelyn.Jan FROM c WHERE c.id = 'someUniqueString'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM