How to restrict Search API for particular collection search in Marklogic?

Viewed 34
import module namespace search = "http://marklogic.com/appservices/search"
  at "/MarkLogic/appservices/search/search.xqy";

let $options  :=
<options xmlns="http://marklogic.com/appservices/search">
  <constraint>
    <collection>'/mycollection'</collection>
  </constraint>
</options>
let $options-1  :=
<options xmlns="http://marklogic.com/appservices/search">
  <constraint name="collection">
    <collection prefix="/mycollection"/>
  </constraint>
</options>
return
  search:search('Text',$options)

I tried both the options, but none of this is restricting the search to the particular collection /mycollection.

1 Answers

You have defined a constraint called collection and have configured the prefix for that constraint to be /mycollection, however you have not applied that constraint to your search.

The constraints are not automatically applied to your searches, they just define what search terms and options can be applied.

If you look at the Collection Constraint Example they note:

If you include a prefix attribute in the definition of a collection constraint, then the collection name is derived from the prefix concatenated with the constraint value.

So, in order for you to apply the constraint that limits to the collection /mycollection I would do this:

xquery version "1.0-ml";

import module namespace search = "http://marklogic.com/appservices/search"
    at "/MarkLogic/appservices/search/search.xqy";
    
let $options  :=
<options xmlns="http://marklogic.com/appservices/search">
  <constraint name="collection">
    <collection />
  </constraint>
</options>

return
  search:search("collection:/mycollection " ||'Text', $options)

If all of your collections start with a leading slash, you could set that as the prefix and then just apply the "name" of the collection without the leading slash:

xquery version "1.0-ml";

import module namespace search = "http://marklogic.com/appservices/search"
    at "/MarkLogic/appservices/search/search.xqy";
    
let $options  :=
<options xmlns="http://marklogic.com/appservices/search">
  <constraint name="collection">
    <collection prefix="/"/>
  </constraint>
</options>
return
  search:search("collection:mycollection "||'Text', $options)
Related