强制转换无效:() as xs:string+ while performing search:search($qtext)

Invalid coercion: () as xs:string+ while performing search:search($qtext)

我正在向 MarkLogic 服务器发送一个 http get 请求,类似于 - http://localhost:7040/index.xqy。请求是使用 xdmp:get-request-field("q") 捕获的,它将查询接受到一个变量中,比如 $qtext 并将其传递给 search:search($qtext).
此 returns 404 未找到错误说明
<error:xquery-version>1.0-ml</error:xquery-version> <error:message>Invalid coercion</error:message> <error:format-string>XDMP-AS: (err:XPTY0004) $qtext as xs:string+ -- Invalid coercion: () as xs:string+</error:format-string>

我做错了什么?

我找到了解决方案。基本上$qtext 是空序列(),这在search:search 中是不允许的。我所做的是 -
let $query := if(fn:empty($q-text)) then "" else $q-text.
您还可以将请求更改为 localhost:7040/index.xqy?q= 这 link 帮助了 http://jaketrent.com/post/unexpected-results-marklogic-xquery-type-coercion/

按照建议,这样比较好xdmp:get-request-field("q", "")

在 XQuery 中简洁地提供默认值的一个非常有用的习惯用法依赖于 xs:string 到 xs:boolean 的转换规则以及

的行为
$sequence[.]

使用“.”因为序列表达式中的谓词将序列中的每个项目评估为布尔值,如果为真则包含该项目,如果为假则排除该项目。 xs:string 到布尔值的转换规则是 'true' 非零长度字符串和 'false' 零长度或空序列。以下是 xs:string.

序列的详细等效项

对于 $sequence 中的 $item return if( not( empty( $item) ) and string-length($item) > 0 ) 然后 $item else ()

因此,下面的模式经常用来表示“如果 $x 不为空或长度不为零,则使用 $x,否则使用 $y。

( $x , $y )[.][1]

请注意“[1]”,它选择了先前表达式产生的第一项。 为 $x 提供默认值的示例,如

 ($x , "Default value")[.][1]

函数的结果或参数相同:

cts:search( doc() , ( get-the-search-string() , "default")[.][1] )

其中 'get-the-search-string()' 可能 return 空序列或零长度字符串或 1 个或多个字符串的序列。

在您的示例中,您需要一个空字符串作为默认值,因此可以使用一个轻微的变体来允许使用“”而不是 ()

let $query := ($q-text,"")[1]