Chapter 2. Fun with Maps

Maps (known as associative arrays in some languages) are a useful data structure, allowing fast, key-based access to a value. MarkLogic provides a common set of map operators, but the recipes in this chapter make them even easier to work with.

Check Whether Two Maps Are Equal

Problem

Sometimes you need to see if two maps are equal, but don’t want to loop through all the keys and compare them. If you do an equals (=), you’ll get an error called XDMP-COMPARE saying “Items not comparable.”

Solution

Applies to MarkLogic versions 7 and higher

If you serialize the map into XML, then you can use fn:deep-equal(). Here is an example of how this can be done:

let $mapA :=
  map:new((
    map:entry("a", "aardvark"),
    map:entry("b", "badger")
  ))
let $mapB :=
  map:new((
    map:entry("a", "aardvark"),
    map:entry("b", "badger")
  ))
let $mapC :=
  map:new((
    map:entry("c","candidate")
  ))
return
 (
   (: ($mapA eq $mapB), will cause the XDMP-COMPARE error :)
   fn:deep-equal(<x>{$mapA}</x>, <x>{$mapB}</x>),
   fn:deep-equal(<x>{$mapA}</x>, <x>{$mapC}</x>)
 )

Discussion

MarkLogic represents maps as XML, so:

map:new((
  map:entry("a", "aardvark"),
  map:entry("b", "badger")
))

becomes:

<map:map xmlns:map="http://marklogic.com/xdmp/map"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <map:entry key="b">
    <map:value xsi:type="xs:string">badger</map:value>
  </map:entry>
  <map:entry key="a">
    <map:value xsi:type="xs:string">aardvark</map:value>
  </map:entry> ...

Get MarkLogic Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.