NodeJS CosmosDB:在数据资源管理器中使用DISTINCT子查询预期结果计数唯一值,但在使用Rest API时不计数

siv3szwd  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(82)

假设我有一个包含以下项目的CosmosDB容器。

[
  {
    id: '1',
    position: 'Table flipper'
    city: 'Vancouver'
    type: 'Job'
  },
  {
    id: '2',
    position: 'Table painter'
    city: 'Seattle'
    type: 'Job'
  },  
  {
    id: '3',
    position: 'Table flipper'
    city: 'Calgary'
    type: 'NotJob'
  },
  {
    id: '4',
    position: 'Table maker'
    city: 'Toronto'
    type: 'Job'
  },
  {
    id: '5',
    position: 'Table maker'
    city: 'Vancouver'
    type: 'Job'
  },
  {
    id: '6',
    position: 'Table flipper'
    city: 'Vancouver'
    type: 'Job'
  },
]

我想要的是给定类型的独特城市的数量。
我正在运行并尝试的查询如下

SELECT VALUE COUNT(subCollection.city) FROM (
  SELECT DISTINCT (c.city) FROM c
  WHERE c.type = 'Job'
) as subCollection

我希望结果等于特定城市出现的唯一次数。所以在这个例子中,来自Cosmos的资源应该是[3]。
在Azure Portal的Data Explorer中运行此查询,结果为[3]。当我使用REST API运行相同的查询时,结果是[0]。从API返回的实际资源是[0,3]。
如何使用API:

let result = await cosmosDb.container(containerName)
    .items.query({
      query: query,
    })
    .fetchAll()

  return result.resources[0] // returns 0

我尝试了COUNT / DISTINCT的几种组合,但在API和数据资源管理器之间得到了相同的差异。我还尝试在API中包含一个continuation token。
我做错了什么,为什么结果与REST API和数据资源管理器不同?

dy2hfwbg

dy2hfwbg1#

  • 我使用了runQuery函数,它封装了对COSMOS DB执行查询的逻辑。
  • 然后创建一个新的CosmosClient示例。然后,使用database()container()方法获得对指定数据库中所需容器的引用。
  • 使用query()方法查询容器,并使用fetchAll()函数检索每个结果。
  • 通过使用runQuery()函数,then()块结果是result。任何错误都将在catch()块中捕获。
    下面是使用Rest API在Data Explorer中获取预期结果的代码:
const { CosmosClient } = require("@azure/cosmos");
async  function  runQuery() {

// Replace with your Cosmos DB endpoint url
const  endpoint = "https://**********";

// Replace with your Cosmos DB primary key
const  key= "************";

const  containerName = "Items";

const  client = new  CosmosClient({ endpoint, key });

const  container = client.database("NewDb").container(containerName); //Replace with your DB name

const  query = `
SELECT VALUE COUNT(subCollection.city) FROM (
SELECT DISTINCT c.city FROM c WHERE c.type = 'Job'
) AS subCollection`;

const { resources } = await  container.items.query(query).fetchAll();
return  resources;
}

runQuery()

.then((result) => {
console.log(result);
})
.catch((error) => {
console.error("Error running the query:", error);
});

项目:

输出:

相关问题