Wednesday, December 25, 2013

Filter search results by managed metadata in KQL in Sharepoint 2013

Suppose that we have custom Sharepoint list with custom content type bound to it (let’s call this CT Book). In our CT there is managed metadata field Country, used for targeting books for particular country in search results. Country term set may be hierarchical and look like this:

   1: APAC:
   2:     China
   3:     ...
   4: EMEA:
   5:     Germany
   6:     France
   7:     Russia
   8:     Spain
   9:     UK
  10:     ...
  11: North America:
  12:     Canada
  13:     USA
  14: ...

We want to show books targeted for China only on Chinese site, for Germany on German, etc. How to do it with Sharepoint?

In order to do it we will use KQL. We may define appropriate search query rules directly in Content by search web parts, but it will be needed to be done for each web part separately. Instead we will use another approach: we will create custom search result source and will configure query rules there. With this approach we will need to do it only once and search web parts will use it by default. In one of the previous posts I showed how to create custom search result source: Problem with missing catalog connections when use customized search result source in Sharepoint 2013.

In order to filter results by appropriate country we need to use the following KQL:

   1:  
   2: {?{searchTerms} -ContentClass=urn:content-class:SPSPeople
   3: (ContentType<>Book OR (ContentType=Book AND (Countries:"EMEA:Germany" OR
   4: Countries="EMEA")))}

With this query search results will only show those books which are targeted to Germany or to all EMEA countries.

2 comments:

  1. Could you explain this some more as its doesnt tell me what it all does primarily -ContentClass=urn:content-class:SPSPeople ??

    If its a content type name, my one has spaces in the name. Is it not the GUID that you pass?

    ReplyDelete
  2. Andrew, "-ContentClass=urn:content-class:SPSPeople" means that we want to exclude people from search results. It is specified like that by default in query builder. As far as I understand it is not content type, it is content class which is processed somehow differently. For content types use "ContentType=Book" syntax. If your content type name contains spaces, enclose it with double quotes: ContentType="My Book".

    ReplyDelete