How to count nodes for child item having same date

102 views Asked by At

I have Xml structures coming like this below. I will have to count the installations on the same date and list them. So I will have to find count by InstallDate and return in XQuery to be used in Marklogic query.

<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>
2

There are 2 answers

0
Fiona Chen On

If you wish to group, count and list the Installation by date in MarkLogic server, see below 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> 

In a transaction-driven environment, you should utilise MarkLogic performant search engine:

for $vt in cts:value-tuples(
    (cts:element-reference(xs:QName( 'InstallDate'))
    ),("item-frequency")
    )
return "Installation on " || $vt[1] || " total count: " || cts:frequency($vt) 
0
BenW On

It's pretty straightforward even in 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,', ')