繁体   English   中英

Azure Cosmos DB ChangeFeed Node.js

[英]Azure Cosmos DB ChangeFeed with Node.js

根据文档,应该能够从 Node.js 中的 Azure CosmosDB 读取更改提要。不幸的是,我没有找到任何代码来执行此操作。 这是我的尝试,但我无法让它运行。 我在 hasMoreResults 分支中输入了两次,但在响应中没有任何结果。 我写的 C# 代码没有问题。

import { CosmosClient } from './node_modules/@azure/cosmos/dist/index.js';
import https from 'https';

const db = 'MyNewDb';
const containerName = 'MyNewContainer';
const endpoint = 'https://localhost:8081';
const key = 'myKey';
const partitionKey = { kind: 'Hash', paths: ['/hello'] };

const client = new CosmosClient({
  endpoint,
  agent: new https.Agent({
    rejectUnauthorized: false,
  }),
  key,
});

const dbResponse = await client.databases.createIfNotExists({
  id: db,
});
const database = dbResponse.database;

const containerResponse = await database.containers.createIfNotExists(
  {
    id: containerName,
    partitionKey,
  },
  { offerThroughput: 400 },
);
const container = containerResponse.container;

const feedIterator = container.items.changeFeed('/hello', { startFromBeginning: true });
let count = 0;
while (feedIterator.hasMoreResults) {
  console.log('more results', count++); // I get here twice but no items in feeIteratorResponse.result

  const feedIteratorResponse = await feedIterator.fetchNext();

  console.log(feedIteratorResponse);
}

这是我的 C# 代码,它可以运行并提供所有结果。

class Program
    {
        static async Task Main(string[] args)
        {
            var dbId = "MyNewDb";
            var containerId = "MyNewContainer";
            using var client = new CosmosClient("https://localhost:8081", "myKey");

            var container = client.GetContainer(dbId, containerId);

            var changeFeedIterator = container.GetChangeFeedIterator<dynamic>(ChangeFeedStartFrom.Beginning(), ChangeFeedMode.Incremental);

            while (changeFeedIterator.HasMoreResults)
            {
                var response = await changeFeedIterator.ReadNextAsync();

                foreach (var item in response)
                {
                    Console.WriteLine(item);
                }
            }
        }
    }

你的问题是这一行:

const feedIterator = container.items.changeFeed('/hello', { startFromBeginning: true });

Change Feed 的 API 允许您读取特定分区键值或整个容器的 Change Feed。

您在 C# 中使用的代码正在读取整个容器的更改提要,因此苹果对苹果将是:

const feedIterator = container.items.changeFeed({ startFromBeginning: true });

如果您想读取特定分区键的更改源,您需要使用一个值,而不是分区键定义。

const feedIterator = container.items.changeFeed('someValue', { startFromBeginning: true });

其中someValue表示容器中存储的一些文档的分区键值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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