Search code examples
javasearchvelocityxwiki

Can I improve the XWiki search results to include keyword matches?


When XWiki search results come back, there is no indication on the context of the match. Only a title and a few when and who items returned. Is there a way of improving the results to include a content summary highlighting the matches found?


Solution

  • Yes, certainly for standard keyword based searches, this velocity code should do the trick. It was developed on XWiki Enterprise 5.0 Milestone 1.

    Edit the page: http://[servername:port]/xwiki/bin/edit/XWiki/Results

    I added my changes below the "rating" section, but you can play with the layout to suit your needs.

    Add the following code which will display up-to 10 keyword matches and the 20 preceding and succeeding words around the keyword. Each match string will be separated by the pipe symbol '|' and the keywords are then highlighted in yellow.

    Obviously it would be nice to make this match a skin colour, but for my purposes I am not interested in that level of development.

               <div class="itemOthers">
             #set($outputSyntax = $xwiki.getAvailableRendererSyntax('plain', '1.0'))
             #if ($outputSyntax)
               #set ($preview = $xwiki.getDocument($itemfullname).getRenderedContent($outputSyntax))
               #set ($regex = $regextool.quote($request.text))
               #set ($regex_summarize = "(?i)(?:((\w+)\W+){0,20})\b\w*$regex\w*\b(((\W+)\w+){0,20})")
               #set ($regex_highlight = "(?i)($regex)")
    
               #set ($pattern_summarize = $regextool.compile($regex_summarize))
               #set ($matcher_summarize = $pattern_summarize.matcher($preview))
    
               #foreach ( $match_loop in [0,1,2,3,4,5,6,7,8,9] )
                 #if ($matcher_summarize.find())
                   #if ($match_loop > 0)
                    <strong> | </strong>
                   #end
                   $escapetool.html($matcher_summarize.group(0)).replaceAll($regex_highlight,'<span style="background-color:yellow;">$1</span>')
                 #end
               #end
             #end
           </div>
    

    Finally, you can see the revisions and changes you made through the url: http://[servername:port]/xwiki/bin/view/XWiki/Results?viewer=history&showminor=true