Search code examples
marklogicmarklogic-8

Facet filtering in Marklogic


I have a requirement, wherein I want to display facets starting with a particular sequence of characters. Can this be done ?

e.g.:

If my search:search returns following facets

<search:values-response name="facet" type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:search="http://marklogic.com/appservices/search">
<search:distinct-value frequency="846">DMPK</search:distinct-value>
<search:distinct-value frequency="323">TNF</search:distinct-value>
<search:distinct-value frequency="301">IL6</search:distinct-value>
<search:distinct-value frequency="297">PAGE4</search:distinct-value>
<search:distinct-value frequency="296">INS</search:distinct-value>
<search:distinct-value frequency="291">PSD</search:distinct-value>
<search:distinct-value frequency="280">EGFR</search:distinct-value>
<search:distinct-value frequency="271">PAGE3</search:distinct-value>
<search:distinct-value frequency="270">PAGE5</search:distinct-value>
<search:distinct-value frequency="268">CD4</search:distinct-value>
<metrics xmlns="http://marklogic.com/appservices/search">
<values-resolution-time>PT0.012602S</values-resolution-time>
<total-time>PT0.014218S</total-time>
</metrics>
</search:values-response>

I want further filter the facets by saying only get me all the facets starting with say PAGE. I cannot apply the filter after I got all the facets as the facets can be in 1000's. So, I want to apply the filter while getting the facets itself. Can this be done ?


Solution

  • Yes, you can create a custom constraint with a custom facet function. Out of the box, facets are based on direct value comparisons only, not wildcards. Your custom constraint would be pretty boilerplate (see the documentation examples), and your facet function would perform the wildcarding:

    declare function my:start-facet(
      $constraint as element(search:constraint), 
      $query as cts:query?, 
      $facet-options as xs:string*, 
      $quality-weight as xs:double?, 
      $forests as xs:unsignedLong*) 
    as item()*
    {
      cts:element-value-match(
        xs:QName("my:element"), "PAGE*", 
        $facet-options, $query, $quality-weight, $queries)
    };