Check if field exists in CosmosDB JSON with SQL - nodeJS
To check the existence of a field in a JSON document stored in CosmosDB, use the IS_DEFINED function:
The IS_DEFINED function returns a boolean, true if the field exists, false if not.
Increase query performance with IS_DEFINED
Processing and querying JSON documents in CosmosDB can be resource-intensive. For more efficient queries, use IS_DEFINED to check the existence of a field. Unlike other methods, IS_DEFINED doesn't fetch the actual field data, which saves computational resources:
This is better than:
This contrasting example illustrates the comparative efficiency of the IS_DEFINED function.
Using IS_DEFINED in conditional SQL statements
Consider IS_DEFINED as a swiss army knife for conditional logic within CosmosDB. It can be used to create dynamic SQL statements:
This flexible approach to writing SQL statements allows you to adapt the output based on the existence of a field.
Potential pitfalls: Be aware of NULL values
IS_DEFINED does have its nuances. It does not differentiate between a field set to null, and a field that does not exist - both return false. So, if you want to differentiate between these situations, use a null check in tandem with IS_DEFINED:
Nested fields and IS_DEFINED: How deep can we go?
CosmosDB allows creating complex JSON documents with deeply nested fields. To check the existence of nested fields, use IS_DEFINED in your SQL query - it can go as deep as your fields do!
This proves particularly useful for multi-tier nested documents.
Was this article helpful?