Similar Bing Entities Example

The Similar Documents Results Processor code example based on the received similar documents request, uses the first metadata value to execute searches via the Bing Entity Search API.

The end-to-end mechanism returns the Bing Entity result related to the most frequent entity (metadata values) present in the user query results set:

Example
Copy
try
{
 
 if(!Results.ExecutedQuery.QueryText.ToLower().Contains("diabetes treatment"))
 return;
 
 string contentString;
var
 entities = new { entities = new { Value = new[] { new { name = 
string.Empty, url = string.Empty, description = string.Empty } } } };
Task.Run(async () => {
 // Do any async anything you need here without worry
string host = "https://api.cognitive.microsoft.com";
 string path = "/bing/v7.0/entities";
string market = "en-US";
// NOTE: Replace this example key with a valid subscription key.
 string key = "yourAPIKeyHere";
 
 
 SimilarDocumentsRequest similarDocRequest;
string newsEntity = "DOCUMENTENTITIES";
try
{
similarDocRequest = SimilarDocumentsUtil.GetSimilarDocumentsRequestFromQuery(Results.ExecutedQuery);
 
 if(similarDocRequest.CallerId!="Entities")
 return;
 
}
catch(Exception e)
{//log exception 
 return;
}
if
 (!similarDocRequest.SimilarityProperties.ContainsKey(newsEntity) || 
similarDocRequest.SimilarityProperties[newsEntity].Count < 1)
 return;
var bestEntity = similarDocRequest.SimilarityProperties[newsEntity].FirstOrDefault();
if(bestEntity==null)
 return;
string query = "Diabetes";
HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
string uri = host + path + "?mkt=" + market + "&q=" + System.Net.WebUtility.UrlEncode(query);
HttpResponseMessage response = await client.GetAsync(uri);
contentString = await response.Content.ReadAsStringAsync();
 

 var schema = new { entities = new { Value = new[] { new { name = 
string.Empty, url = string.Empty, description = string.Empty } } } };
entities = JsonConvert.DeserializeAnonymousType(contentString, schema);
 
 foreach (var value in entities.entities.Value.Take(3))
 {
 var title = value.name;
 var summary = value.description;
 var url = value.url;
var result = new SearchResult();

 result.AddOrChangeProperty("title", query +": " + title, typeof(System.String));
result.AddOrChangeProperty("clickUri", url, typeof(System.String));
 
 result.AddOrChangeProperty("filetype", "html");

 Results.RelevantResults.Add(result);
 }

 }).GetAwaiter().GetResult();
}
catch
{ //log exception 
 return;
}

 

Referenced Assemblies

  • Newtonsoft.Json.dll
  • System.Net.Http.dll

Imported Namespaces

  • System
  • System.Net
  • Newtonsoft.Json
  • System.Threading.Tasks
  • System.Net.Http