How to use the negative operator in KM Advanced search with SOLR

  • KM00451662
  • 11-Jun-2013
  • 18-Nov-2015

Summary

Users cannot search for field values NOT matching a value. Here is how to make it work.

Question

When using field searches from the KM advanced search, special characters and other syntax are typically stripped to keep the search from failing.  Users would like to be able to search not only for a field equals value but also for field unequals value or what we would call a "negative" query.  Out of the box, KM using SOLR does not support this but it is easy to achieve.

Answer

We cannot simply add the negative operator to our value like this: -value.  This is incorrect syntax for the search.  The proper syntax would be: -field:value.  But since the user cannot manually add the negative operator to the field name, how can me make this work without a full rewrite of the advanced search screen?

Simple, here's what to do:

We will modify the author field for this example.
From Manage Knowledgebases for the library you wish to work on (ie Knowledge_Library), go to the "type information" tab.
Click on the magnifying glass next to the Advanced Search Script "Knowledge_Library_kmprocesslibcriteria", a script should open.
Scroll down to the section that begins with "Else" around line 50.  This is where the SOLR specific code resides.
Look for the line "if(KMQuery.kmlib.author != null)"
We want to modify this area from this:
if(KMQuery.kmlib_author != null)
    strQuery += " (author: " + KMQuery.kmlib_author + " AND knowledgebase_name: Knowledge_Library)";
to this:
if(KMQuery.kmlib_author != null)
   if (KMQuery.kmlib_author.charAt(0) == "-")
    strQuery += " (-author: " + KMQuery.kmlib_author.substr(1,KMQuery.kmlib_author.length) + " AND knowledgebase_name: Knowledge_Library)";
   else
    strQuery += " (author: " + KMQuery.kmlib_author + " AND knowledgebase_name: Knowledge_Library)";

Save and then exit this script library.

How it works:
We are checking first to see if the author field contains a value.  If so, we check to see if the first character is the negative operator "-".  If it is, we add the negative operator to the field name and remove it from the field value.  Otherwise, we work as we did before.

Now, if we enter "falcon" in the author field of the advanced search form, we will find all documents where falcon is the author.
If we enter "-falcon", we will find all documents where falcon IS NOT the author.
This can be done for any field in the advanced search form.