插入新文档时未运行 Cosmos Db 触发器

fas*_*cja 3 java azure azure-java-sdk azureportal azure-cosmosdb

我正在使用 Azure Cosmos DB。我在 Azure 门户中创建了一个简单的触发器,如下所示:

在此处输入图片说明

  var context = getContext();
  var request = context.getRequest();

  // item to be created in the current operation
  var itemToCreate = request.getBody();
  itemToCreate["address"] = "test";

  // update the item that will be created
  request.setBody(itemToCreate);
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我插入新文档时没有触发这个触发器。我还尝试将“触发器类型”设置为“发布”。我错过了什么吗?

Gau*_*tri 6

好问题!我一直认为触发器会自动运行:)。

我相信只要插入文档,触发器就不会自动运行。您需要做的是指定在创建文档时要运行的触发器。

您需要做的是在发送创建文档请求时通过将触发器名称作为请求选项来注册触发器。

例如,请参阅此处的代码:https : //docs.microsoft.com/en-us/azure/cosmos-db/how-to-use-stored-procedures-triggers-udfs#pre-triggers(也复制如下)。注意PreTriggerIncludein的使用RequestOptions

dynamic newItem = new
{
    category = "Personal",
    name = "Groceries",
    description = "Pick up strawberries",
    isComplete = false
};

Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
RequestOptions requestOptions = new RequestOptions { PreTriggerInclude = new List<string> { "trgPreValidateToDoItemTimestamp" } };
await client.CreateDocumentAsync(containerUri, newItem, requestOptions);
Run Code Online (Sandbox Code Playgroud)

  • “所以如果触发器能自己触发那就完美了”……我也是:)。根据 SQL 经验,我的期望是它会自行运行......啊好吧......你每天都会学到新东西。 (2认同)