noons
noons

Reputation: 13

Using MarkLogic to counting

I am a beginner in the field of MarkLogic and need help in solving this question with clarification please. This is an example of xml classes. I need a function to count the number of classes a student attends, use map

<Classes>
   <Class>
      <Class-name>math</Class-name>
      <Student-name>Jon</Student-name>
      <Student-name>Sam</Student-name>
   </Class>
   <Class>
     <Class-name>Sciences</Class-name>
     <Student-name>Jon</Student-name>
     <Student-name>Jack</Student-name>
     <Student-name>Nay</Student-name>
   </Class>
   <Class>
     <Class-name>Languages</Class-name>
     <Student-name>Jon</Student-name>
     <Student-name>Sam</Student-name>
     <Student-name>Nay</Student-name>
   </Class>
</Classes>

Upvotes: 1

Views: 73

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66723

A way to count without maps would be to collect a distinct list of Student-name, and then use those names to get a count of the Student-name elements with those names:

for $student in fn:distinct-values($Classes/Class/Student-name)
return 
  $student||":"||count($Classes/Class[Student-name=$student])

A way to achieve the same thing with maps would be to walk over each of the Student-name elements, putting an entry in the map that increments the current count by 1:

let $stats := map:new()
let $_ := 
  for $student in $Classes/Class/Student-name
  return map:put($stats, $student, 1 + (map:get($stats, $student), 0)[1])
return
  map:keys($stats) ! ( .||":"||map:get($stats, .) )

Upvotes: 2

Related Questions