问题描述
我有下面这样的Xml结构。我将必须计算同一日期的安装并列出它们。因此,我将必须通过InstallDate查找计数并返回XQuery以便在Marklogic查询中使用。
<PcDetail>
<Installations>
<Installation>
<Type>pc</Type>
<purchased>Y</purchased>
<InstallDate>2020-10-01T00:00:00:000Z</InstallDate>
</Installation>
<Installation>
<Type>pc</Type>
<purchased>Y</purchased>
<InstallDate>2020-10-01T00:00:00:000Z</InstallDate>
</Installation>
<Installation>
<Type>pc</Type>
<purchased>Y</purchased>
<InstallDate>2020-10-02T00:00:00:000Z</InstallDate>
</Installation>
<Installation>
<Type>pc</Type>
<purchased>Y</purchased>
<InstallDate>2020-10-02T00:00:00:000Z</InstallDate>
</Installation>
<Installation>
<Type>pc</Type>
<purchased>Y</purchased>
<InstallDate>2020-10-02T00:00:00:000Z</InstallDate>
</Installation>
</Installations>
解决方法
如果您希望在MarkLogic服务器中按日期分组,计数和列出Installation
,请参见以下MarkLogic XQuery dialect
:
for $d in distinct-values(doc()//InstallDate)
let $i := doc()//Installation[InstallDate = $d]
order by $d
return <Installations Date="{$d}" Count="{count($i)}">
{
for $install in $i
return $install
}</Installations>
在事务驱动的环境中,您应该使用MarkLogic性能搜索引擎:
for $vt in cts:value-tuples(
(cts:element-reference(xs:QName( 'InstallDate'))
),("item-frequency")
)
return "Installation on " || $vt[1] || " total count: " || cts:frequency($vt)
,
即使在XQuery 1.0中,它也非常简单
let $installations := $xml/PcDetail/Installations/Installation
for $date in fn:distinct-values($installations/InstallDate)
let $installationsOnDate := $installations[InstallDate = $date]
let $c := count($installationsOnDate)
return $date || ':' || $c || ':' || string-join($installationsOnDate/type,',')