How to use Group By in Marklogic?
Asked Answered
C

4

5

I want to use Group By in xquery. Can someone tell me please how to use Group By in Marklogic ?

Cryptogram answered 23/4, 2012 at 7:26 Comment(2)
Haven't used Marklogic. But please have a look at blakeley.com/blogofile/archives/560Claudianus
Does the version of MarkLogic you're using support the XQuery 3.0 draft? (It's only as of 3.0 that group by support was added to FLWOR expressions; before that point, you have to do it yourself). A summary of group by in XQuery 3.0 can be found at docs.basex.org/wiki/XQuery_3.0#Group_ByLumpen
M
4

The short answer is to use map:map. See http://docs.marklogic.com/map:map for documentation, and http://blakeley.com/blogofile/archives/560/ for a longer discussion.

Mariann answered 23/4, 2012 at 14:43 Comment(0)
B
4

Alternatively, you could call out to XSLT using xdmp:xslt-invoke or xdmp:xslt-eval. MarkLogic's XSLT processor supports XSLT 2.0, which includes full support for <xsl:for-each-group>.

Bashuk answered 23/4, 2012 at 16:5 Comment(0)
L
1
xquery version "1.0-ml";
let $xml:= <Students>
    <Student Country="England" Name="Dan" Age="20" Class="C"/>
    <Student Country="England" Name="Maria" Age="20" Class="B" />
    <Student Country="Australia" Name="Mark" Age="22" Class="A" />
  </Students>

let $xsl:= <xsl:stylesheet version="2.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:template match="Students">
  <result>
    <xsl:for-each-group select="Student" group-by="@Country">
    <country>
      <xsl:attribute name="name"><xsl:value-of select="fn:current-grouping-key()"/></xsl:attribute>
      <xsl:for-each select="fn:current-group()/@Name">
        <name><xsl:value-of select="."/></name>     
      </xsl:for-each>
    </country>
    </xsl:for-each-group>
  </result>
</xsl:template>
</xsl:stylesheet>

return xdmp:xslt-eval($xsl,$xml)
Lipread answered 9/3, 2016 at 21:58 Comment(0)
N
0

MarkLogic covers parts of XQuery 3.0 (with its 1.0-ml dialect), but unfortunately FLWOR group by support is lacking.

However, you can still programmatically create group by like syntax which will achieve the same results. Here is an XQuery example:

for $d in distinct-values(doc("order.xml")//item/@dept)
let $items := doc("order.xml")//item[@dept = $d]
order by $d
return <department code="{$d}">{
         for $i in $items
         order by $i/@num
         return $i
       }</department>

HTH

Nictitate answered 31/8, 2012 at 17:21 Comment(2)
MarkLogic 5 doesn't support group by.Spinks
You could speed up this approach using cts:values (instead of distinct-values), and cts:search (instead of XPath predicates), particularly if you can store order items as separate files.Carnify

© 2022 - 2024 — McMap. All rights reserved.