【问题标题】:createUserDefinedFunction : if already exists?createUserDefinedFunction : 如果已经存在?
【发布时间】:2015-06-09 14:43:14
【问题描述】:

我使用azure-documentdb java SDK 来创建和使用“用户定义函数 (UDF)”

所以从official documentation 我终于找到了关于如何创建 UDF 的方法(使用 Java 客户端):

String regexUdfJson = "{"
          + "id:\"REGEX_MATCH\","
          + "body:\"function (input, pattern) { return input.match(pattern) !== null; }\","
          + "}";
UserDefinedFunction udfREGEX = new UserDefinedFunction(regexUdfJson);
getDC().createUserDefinedFunction(
    myCollection.getSelfLink(),
    udfREGEX,
    new RequestOptions());

这是一个示例查询:

SELECT * FROM root r WHERE udf.REGEX_MATCH(r.name, "mytest_.*")

我只需要创建一次 UDF,因为如果我尝试重新创建现有 UDF 会出现异常:

DocumentClientException: Message: {"Errors":["The input name presented is already taken. Ensure to provide a unique name property for this resource type."]}

我应该如何知道 UDF 是否已经存在? 我尝试使用“readUserDefinedFunctions”功能但没有成功。任何例子/其他想法?

也许从长远来看,我们是否应该在azure feedback 上建议“createOrReplaceUserDefinedFunction(...)”

【问题讨论】:

  • 尊敬的照明师@abatishchev 为什么将我的 java 代码更新为 c#?
  • 对此感到抱歉。您的问题缺少语言标签。我放错了。

标签: java azure-cosmosdb


【解决方案1】:

您可以通过使用queryUserDefinedFunctions 运行查询来检查现有的UDF。

例子:

List<UserDefinedFunction> udfs = client.queryUserDefinedFunctions(
        myCollection.getSelfLink(),
        new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id",
                         new SqlParameterCollection(new SqlParameter("@id", myUdfId))),
        null).getQueryIterable().toList();
if (udfs.size() > 0) {
    // Found UDF.
}

【讨论】:

    【解决方案2】:

    .NET 用户的答案。

    `var collectionAltLink = documentCollections["myCollection"].AltLink; // Target collection's AltLink
    var udfLink = $"{collectionAltLink}/udfs/{sampleUdfId}"; // sampleUdfId is your UDF Id
    var result = await _client.ReadUserDefinedFunctionAsync(udfLink);
    var resource = result.Resource;
    if (resource != null)
    {
       // The UDF with udfId exists
    }`
    

    这里 _client 是 Azure 的 DocumentClientdocumentCollections 是您的 documentDb 集合的字典。

    如果提到的集合中没有这样的 UDF,_client 会抛出 NotFound 异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-28
      • 2015-05-14
      • 2013-11-07
      • 1970-01-01
      • 2014-03-15
      • 2015-06-14
      • 2016-05-30
      • 2012-12-14
      相关资源
      最近更新 更多