Managed metadata and KQL Search

Using metadata on your information is a great way of categorizing it. It also enables you to drill up and down in information by the means of the term hierarchy.

By leveraging search, you can gather information from all the site collections, even web applications in your farm (as long as they use the same Search Service Application at least).

Let’s take a look at a basic example of how to create a method that using KQL will gather all items tagged with a specific term.

First, here is the complete method:

public DataTable GetItemsByTag(Term term, string[] selectProperties, string filterManagedProperyName)
{
     KeywordQuery kq = new KeywordQuery(SPContext.Current.Site);
     kq.TrimDuplicates = false;
     kq.SelectProperties.AddRange(selectProperties);
     kq.QueryText = String.Format("{0}:\"GP0|#{1}\"", term.TermGuid, filterManagedProperyName)

     SearchExecutor se = new SearchExecutor();
     var result = se.ExecuteQuery(kq);
     return result.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault().Table;
}

So, a very basic method that just returns the relevant results based on the term passed in. Of course, to be able to render the results we later on would have to iterate the DataTable rows and perhaps generate some more easy to handle objects that we could pass to our view manager.

Some clarifications about the code:
“filterManagedProperyName” should the the name of the managed property created for the metadata column (the one with ows_taxId in it).

The “GP0|#” part of the QueryText makes sure we only get items tagged with the passed in term. If you do not add “GP0|#” in from of the term GUID, you will also get results for the parent terms (since in the managed property also parts of the term hierarchy is stored)

That was it for today!

Advertisements