Could someone point out to me how the following query could be rewritten to perform better than it does now

declare namespace cl = "http://www.epo.org/namespaces/epodos/clause/v1.0/";
for $clause1 in collection("/db/clause")/cl:clause
where exists(
        for $clause2 in collection("/db/clause")/cl:clause
        where $clause2/@public eq  $clause1/@public
        and $clause2/@procedure-and-phase eq  $clause1/@procedure-and-phase
        and $clause2/cl:name eq  $clause1/cl:name
        and not($clause2/@clause-id eq  $clause1/@clause-id)
        return $clause2/@clause-id)
return $clause1

I have defined a range index on all above attributes and element. The query takes about 30 seconds. I have about 2000 clauses. A clause is identified by the sequence
($clause2/@public, $clause2/@procedure-and-phase, $clause2/cl:name). Every clause is guaranteed to have a unique id (@clause-id).

I have also used the following variation

for $clause1 in collection("/db/clause")/cl:clause
for $clause2 in collection("/db/clause")/cl:clause
..

and I also moved the processing to the return clause

declare namespace cl = "http://www.epo.org/namespaces/epodos/clause/v1.0/";
for $clause1 in collection("/db/clause")/cl:clause
return
for $clause2 in collection("/db/clause")/cl:clause
        where $clause2/@public eq  $clause1/@public
        and $clause2/@procedure-and-phase eq  $clause1/@procedure-and-phase
        and $clause2/cl:name eq  $clause1/cl:name
        and not($clause2/@clause-id eq  $clause1/@clause-id)
return $clause2


with the same result.

Kind regards,
Rudolf de Grijs