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

Cosmos Db Trigger is not being run when inserting new document

我正在使用 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);

不幸的是,当我插入新文档时,这个触发器没有被触发。我还尝试将 "Trigger Type" 设置为 "Post"。我错过了什么吗?

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

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

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

例如,查看此处的代码:https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-use-stored-procedures-triggers-udfs#pre-triggers (copied below as well). Notice the use of PreTriggerInclude in 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);

在关系数据库中自动触发触发器是有意义的,因为在 数据库,你有点知道在触发器逻辑中要处理什么。 在 NoSQL 数据库中,由于没有模式,您最终可能会得到一个大型脚本来处理各种异常。 触发器中的大脚本意味着云中的账单更高。使触发器自动化可以使许多客户在物联网解决方案方面的费用非常高。 您可以在我的 post 中阅读有关 Azure Cosmos DB pre/post 触发器的信息。 https://h-savran.blogspot.com/2020/03/create-triggers.html

根据@Guarav Mantri 和@Hasan Savaran 的回答,唯一的方法是在通过 API 创建项目时指定触发器。我已经在 Java Azure SDK 中做到了,就像这样:

 RequestOptions options = new RequestOptions();
 options.setPreTriggerInclude(Arrays.asList("pre"));
 documentClient.createDocument(
                    collectionLink(),
                    documentToAdd,
                    options,
                    true);

虽然我对这个解决方案不满意,因为例如通过 Portal 创建项目时不会触发触发器。