createUserDefinedFunction : if already exists?

468 views Asked by At

I'm using azure-documentdb java SDK in order to create and use "User Defined Functions (UDFs)"

So from the official documentation I finally find the way (with a Java client) on how to create an UDF:

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

And here is a sample query :

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

I had to create the UDF one time only because I got an exception if I try to recreate an existing UDF:

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

How should I do to know if the UDF already exists ? I try to use "readUserDefinedFunctions" function without success. Any example / other ideas ?

Maybe for the long term, should we suggest a "createOrReplaceUserDefinedFunction(...)" on azure feedback

2

There are 2 answers

0
Andrew Liu On BEST ANSWER

You can check for existing UDFs by running query using queryUserDefinedFunctions.

Example:

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.
}
0
JefferinJoseph On

An answer for .NET users.

`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
}`

Here _client is Azure's DocumentClient and documentCollections is a dictionary of your documentDb collections.

If there's no such UDF in the mentioned collection, the _client throws a NotFound exception.