[MarkLogic Dev General] how to implement an accumulator

Ian Small ian at marklogic.com
Thu Mar 13 19:28:38 PST 2008


the key isn't to try to aggregate, it's to use sequences and qualified
XPaths in XQuery.  so how about:
 
<speakers>
{
  let $speech := doc("speeches.xml")//speech
  let $speakers := distinct-values($speech/speaker)
  for $speaker in $speakers
  order by $speaker
  return
     <speaker>
        <name>{$speaker}</name>
        <count>{ count($speech[speaker = $speaker]/line) }</count>
     </speaker>
}
</speakers>

i haven't actually tested it, but it seems about right to me.  i might
have missed a / in the $speech predicate in the count().
 
ian
 


________________________________

	From: general-bounces at developer.marklogic.com
[mailto:general-bounces at developer.marklogic.com] On Behalf Of Eric
Caplain
	Sent: Thursday, March 13, 2008 7:54 PM
	To: general at developer.marklogic.com
	Subject: [MarkLogic Dev General] how to implement an accumulator
	
	
	I've some XML like:
	
	<speech>
	   <speaker>Joe</speaker>
	   <line>blah blah blah</line>
	   ...
	   <line>this that and the other thing</line>
	</speech>
	
	I can get each speaker and then get each speech of that speaker
and a count of lines in each speech, but I haven't been able to get the
total count of all lines by a speaker.
	
	In the following, the function line-count returns the count of
lines in each speech, but I need to accumulate these counts and return
that, and I haven't been able to figure out a way to do that. Any
suggestions would be appreciated.
	
	define function line-count($s as xs:string) as xs:integer {
	   let $count := 0
	   for $_speech in doc("speeches.xml")//speech
	   where some $_speaker in $_speech/speeker
	   satisfies ($_speaker/text() = $s)
	   return count($_speech/line)    
	}
	
	<speakers>
	{
	  let $speech := doc("speeches.xml")//speech
	  for $speaker in distinct-values($speech/speaker)
	  order by $speaker
	  return
	     <speaker>
	        <name>{$speaker}</name>
	        <count>{ line-count($speaker) }</count>
	     </speaker>
	}
	</speakers>
	

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://xqzone.marklogic.com/pipermail/general/attachments/20080313/9a542394/attachment.html


More information about the General mailing list