1

I made a UDF in my Azure CosmosDB so that I can query records where the Timestamp field equals a certain year.

For example, my query looks like this:

SELECT * FROM c WHERE c.StaticKey = 'd6c5a92203d84ce28b94cfc64a6ad4ce' 
AND udf.YEAR(c.Timestamp) = '2020' OFFSET 0 LIMIT 1

But for some reason my query always returns 0 results. I have a lot of records in my table that have a datetime from this year.

This record for exmaple DOES return 1 row and prints 2020:

SELECT udf.YEAR(c.Timestamp) FROM c WHERE c.StaticKey = 'd6c5a92203d84ce28b94cfc64a6ad4ce' OFFSET 0 LIMIT 1

My UDF in Azure looks like this:

function YEAR(datetimeString){
    var datetime = new Date(Date.parse(datetimeString));
    return datetime.getFullYear();
}

The column Timestamp contains datetime values looking like this: 2020-10-20T07:13:22.802346.

As you can see in this fiddle the javascript function works good: https://jsfiddle.net/0eozyhnv/

Anyone any idea why my UDF isn't working in my WHERE clause?

0

1 Answer 1

1

Your UDF returns an integer. So you should write the query like this:

SELECT * FROM c WHERE c.StaticKey = 'd6c5a92203d84ce28b94cfc64a6ad4ce' 
AND udf.YEAR(c.Timestamp) = 2020 OFFSET 0 LIMIT 1

But note that this is relatively slow since UDFs can't make use of indexes. If you can format your dates in the format accepted by Cosmos DB (YYYY-MM-DDThh:mm:ss.fffffffZ) you could also use the built-in function DATETIMEPART('yyyy', c.Timestamp)=2020.

However, I suspect the fastest solution would be STARTSWITH(c.Timestamp, '2020') since this makes use of a range index on Timestamp.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, also for the suggestions! I had no idea that there was a DATETIMEPART function. I will use that one from now on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.