Checking for the existence of an element
26 May 2015 01:37 PM
A common use case in many business applications is to find if an element exists in any document or not. This article provide ways to find such documents and explain points that should be taken care of while designing a solution.
In general, existence of an element in a document can checked by using below XQuery.
Note the empty cts:and-query construct here. An empty cts:and-query is used to fetch all fragments.
Hence running below search query will bring back all the documents having element "myElement".
Wrapping the query in cts:not-query will bring back all the documents *not* having element "myElement"
As a search using cts:not-query is only guaranteed to be accurate if the underlying query that is being negated is accurate from its index resolution, hence to check existence of a specific XPath, we need to index that XPath.
Things to remember
1.) Have unique element name in a single document i.e. try not to use same element name at multiple places within a document if they have different meaning for your use case. Either give them different element names or put them under different namespaces to remove any ambiguity. e.g. if you have element "table" at two places in a single document then you can put them both under different namespaces such as html:table & furniture:table or you can name them differently such as html_table & furniture_table.
2.) If element names are unique within a document then you don't need to create additional indexes. If element names are not unique within a document and you are interested in only a specific XPath then create path(field) indexes on those XPaths and use the same in your not-query.