插入新文档时,Cosmos Db Trigger未运行

时间:2020-04-01 10:52:31

标签: java azure azure-cosmosdb azureportal azure-java-sdk

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

enter image description here

  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);

不幸的是,当我插入新文档时,未触发此触发器。我还尝试将“触发器类型”设置为“发布”。我想念什么吗?

3 个答案:

答案 0 :(得分:5)

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

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

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

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

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);

答案 1 :(得分:2)

在关系数据库中自动触发触发器是有道理的,因为其中存在模式 在数据库中,您有点知道如何处理触发逻辑。 在NoSQL数据库中,由于没有架构,因此您可能会以大型脚本处理各种异常。 触发器中的大脚本意味着Cloud中的费用更高。将触发器设为自动可以使许多客户在物联网解决方案中的费用很高。 您可以在我的文章中了解有关Azure Cosmos DB之前/之后触发器的信息。 https://h-savran.blogspot.com/2020/03/create-triggers.html

答案 2 :(得分:0)

根据@Guarav Mantri和@Hasan Savaran的回答,唯一的方法是在通过API创建商品时指定触发器。我设法在Java Azure SDK中做到了这一点:

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

尽管我对此解决方案不满意,因为例如在通过Portal创建商品时不会触发触发器。