How to search/query by Enterprise Keywords?
-
10-12-2019 - |
Question
I'm doing a recommendation engine and I need to access the Enterprise Keywords of a document and search for other documents having at least 1 matching keyword.
So for example I have Document A
which has the following Enterprise Keywords:
- Keyword X
- Keyword Y
- Keyword Z
Then I need to search the whole Site collection for documents having at least one of those keywords. If it's possible to search for all of those 3 tags with an OR and returning all the documents that have at least one match ordered by number of matches, that would be great. If not, then I can do it one tag per query.
I cannot find how to query only for Enterprise Keywords.
So, which is the proper and fastest way of doing this? (The site is not using FAST).
Thank you.
Solution 2
This is what I ended up doing:
var file = Web.GetFile(fileId);
var tags = new TaxonomyFieldValueCollection(file.Item.Properties["TaxKeyword"].ToString());
var query = new SPSiteDataQuery();
// build the query
var sbQuery = new StringBuilder();
sbQuery.Append("<Where><In><FieldRef Name='TaxKeyword' /><Values>");
foreach (var tag in tags)
{
sbQuery.AppendFormat("<Value Type='Text'>{0}</Value>", tag.Label);
}
sbQuery.Append("</Values></In></Where>");
string sViewFields = "<FieldRef Name='UniqueId' /><FieldRef Name='FileRef' /><FieldRef Name='AverageRating' />";
// Search in doclibs only
query.Lists = "<Lists ServerTemplate='101' MaxListLimit='0' />";
query.Query = sbQuery.ToString();
query.ViewFields = sViewFields;
// Search in all webs of the site collection
query.Webs = "<Webs Scope='SiteCollection' />";
// Perform the query
var table = Web.GetSiteData(query);
OTHER TIPS
Without development you can try add a static query to the content search result webpart: tags:"Keyword X" or tags:"Keyword Y" or tags:"Keyword Z" - tags should be the managed property for the Enterprise Keyword column.
With development you have to use the KeywordQueryClass, see: http://msdn.microsoft.com/en-us/library/ms544561%28office.12%29.aspx
ServerContext context = ServerContext.GetContext(HttpContext.Current);
using (KeywordQuery keywordQuery = new KeywordQuery(context))
{
keywordQuery.ResultTypes = ResultType.RelevantResults;
keywordQuery.EnableStemming = true;
keywordQuery.TrimDuplicates = true;
keywordQuery.StartRow = 0;
keywordQuery.QueryText = string.Format(CultureInfo.InvariantCulture, "tags:\"{0} OR tags:{1} OR tags:{2}\"", "Keyword A", "Keyword B","Keyword C");
keywordQuery.SelectProperties.Add("tags"); //add the properties you want
ResultTableCollection resultsCollection = keywordQuery.Execute();
ResultTable resultsTable = resultsCollection[ResultType.RelevantResults]; }