Cosmos Db:如何查询数组数组中属性的最大值?

Cosmos Db: How to query for the maximum value of a property in an array of arrays?

我不确定在使用 CosmosDb 时如何查询,因为我习惯了 SQL。我的问题是关于如何在数组数组中获取 属性 的最大值。到目前为止我一直在尝试子查询,但显然我不太了解它们是如何工作的。

在如下所示的结构中,如何使用 Azure 中的数据资源管理器查询所有州中人口较多的城市:

{
    "id": 1,
    "states": [
        {
            "name": "New York",
            "cities": [
                {
                    "name": "New York",
                    "population": 8500000
                },
                {
                    "name": "Hempstead",
                    "population": 750000
                },
                {
                    "name": "Brookhaven",
                    "population": 500000
                }           
            ]
        },
        {
            "name": "California",
            "cities":[
                {
                    "name": "Los Angeles",
                    "population": 4000000
                },
                {
                    "name": "San Diego",
                    "population": 1400000
                },
                {
                    "name": "San Jose",
                    "population": 1000000
                }
            ]
        }
    ]
}

据我所知,目前这是不可能的。

看起来有点像这样:

SELECT TOP 1 state.name as stateName, city.name as cityName, city.population FROM c
join state in c.states
join city in state.cities
--order by city.population desc <-- this does not work in this case

您可以编写一个用户定义的函数来编写您可能期望的查询,类似于:

结果可能如下所示:

SELECT c.name, udf.OnlyMaxPop(c.states) FROM c
function OnlyMaxPop(states){
    function compareStates(stateA,stateB){  
       stateB.cities[0].poplulation - stateA.cities[0].population;
  }
  
  onlywithOneCity = states.map(s => {
    maxpop = Math.max.apply(Math, s.cities.map(o => o.population));
    return {
      name: s.name,
      cities: s.cities.filter(x => x.population === maxpop)
    }
  });
  
    return onlywithOneCity.sort(compareStates)[0];
}

您可能需要根据您的确切查询需求调整函数,但我不确定您想要的结果是什么样的。