如何在 CosmosDB 查询中将值数组展平为行?

How do you flatten an array of values into rows in a CosmosDB query?

给定 CosmosDB 数据库中的以下集合数据:

[
    {
        "id": "1",
        "title": "Blog post #1",
        "tags": ["tag1", "tag2", "tag3"]
    },
    {
        "id": "2",
        "title": "Blog post #2",
        "tags": ["tag1"]
    }
]

您如何将其扁平化为如下所示的结果集:

[
    {
        "id": "1",
        "title": "Blog post #1",
        "tagName": "tag1"
    },
    {
        "id": "1",
        "title": "Blog post #1",
        "tagName": "tag2"
    },
    {
        "id": "1",
        "title": "Blog post #1",
        "tagName": "tag3"
    },
    {
        "id": "2",
        "title": "Blog post #2",
        "tagName": "tag1"
    }
]

这个例子的最终目标是找到标签计数,所以这个查询将被包装在类似 SELECT COUNT(1) as count, s.tagName FROM (subquery) s GROUP BY s.tagName.

您的想法是正确的,但使用了错误的联接类型。您需要使用 JOIN IN 来展平数组。

SELECT c.id, c.title, t AS tagName
FROM c
JOIN t IN c.tags