declare function t:getIdByName($arg) { let $x := collection($dbName)/module//object[@name = $arg] return if( empty($x/@id) ) then "-1" else $x/@id };
Your query will be optimized if $dbName is globally declared (which I guess it is anyway), and if $arg is specified as string:
declare variable $dbName := '...'; declare function local:getIdByName($arg as xs:string) { let $x := collection($dbName)/module//object[@name = $arg] return if( empty($x/@id) ) then "-1" else $x/@id };
You may as well use db:attributes() to explicitly access the index (if available):
declare variable $dbName := '...'; declare function local:getIdByName($arg) { let $x := db:attribute($dbName, $arg, 'name')/parent::object[ancestor::module] return if( empty($x/@id) ) then "-1" else $x/@id };
Hope this helps, Christian