Use Dataverse search Suggestions API of Microsoft Dynamics 365

By | September 21, 2023

Dataverse Search has been a prominent feature in the Microsoft Dynamics 365 CRM environment, offering access to advanced search capabilities. The earlier “Relevance Search” has been upgraded to “Dataverse Search” with some interesting additional enhancements.

Previously, we demonstrated how to utilize the Relevance Search API in Power Automate and Canvas Apps. Today, let’s explore the enhancements.

Configuring Dataverse Search

Before you use this feature, an Administrator must enable “Dataverse search” in the target environment.

Note: Enabling “Dataverse Search” is required to make “Suggestions Search” work.

To enable “Dataverse Search” simply follow the steps given below:

  1. Navigate to Power Platform Admin Center, and select the appropriate environment
  2. Click on the “Settings” in the “Product” area and click open the “Features” section
  3. Under the “Search” section, there is an option to turn on the “Dataverse Search”
  4. Click on the Save button to save the changes

Dataverse search Suggestions API
Suggestion Search

Now, let’s understand the usage of Dataverse Search Suggestions.

Suggestion is another feature of the Dataverse Search API. With the HTTP POST endpoint [Organization URI]/api/search/v1.0/suggest, a list of records where their primary field matches the input term will be returned.

Search requests scan through all dataverse search-enabled entity fields.

The comprehensive list of input parameters is outlined in Microsoft’s documentation. Perhaps the most critical parameter is the “usefuzzy” option, which holds a Boolean value to determine whether to enable fuzzy search.

By default, the result records that are retrieved are 5 and the Top Max count is 100.

Here, is a List of Some Similar Records inside our Account Entity-

Dataverse search Suggestions API

To use the fuzzy search inside our suggested API:

POST [Organization URI]/api/search/v1.0/suggest
{

“search”: “aiden”,

“usefuzzy”: true ,

}

Dataverse search Suggestions API

In this scenario, we are issuing the POST API request with a JSON-formatted request body.

The Below content is our received response:

{

"value": [

{

"text": "{crmhit}Aiden{/crmhit}",

"document": {

"@search.objectid": "07a22dec-6750-ee11-be6e-000d3af2ec33",

"@search.entityname": "account",

"@search.objecttypecode": 1,

"name": "Aiden",

"versionnumber": 7401941,

"statecode": [

"Active"

],

"statuscode": [

"Active"

],

"entityimage_url": null,

"createdon": "9/11/2023 11:26 AM",

"modifiedon": "9/11/2023 11:26 AM",

"accountnumber": null,

"address1_city": null,

"emailaddress1": null,

"primarycontactid": null,

"primarycontactidname": null,

"telephone1": null

}

},

{

"text": "{crmhit}Ayden{/crmhit}",

"document": {

"@search.objectid": "a2bc4df3-6750-ee11-be6e-000d3af2ec33",

"@search.entityname": "account",

"@search.objecttypecode": 1,

"name": "Ayden",

"versionnumber": 7401943,

"statecode": [

"Active"

],

"statuscode": [

"Active"

],

"entityimage_url": null,

"createdon": "9/11/2023 11:26 AM",

"modifiedon": "9/11/2023 11:26 AM",

"accountnumber": null,

"address1_city": null,

"emailaddress1": null,

"primarycontactid": null,

"primarycontactidname": null,

"telephone1": null

}

},

{

"text": "{crmhit}Aaden{/crmhit} K",

"document": {

"@search.objectid": "7366032a-6850-ee11-be6e-000d3af2ec33",

"@search.entityname": "account",

"@search.objecttypecode": 1,

"name": "Aaden K",

"versionnumber": 7401953,

"statecode": [

"Active"

],

"statuscode": [

"Active"

],

"entityimage_url": null,

"createdon": "9/11/2023 11:28 AM",

"modifiedon": "9/11/2023 11:28 AM",

"accountnumber": null,

"address1_city": null,

"emailaddress1": null,

"primarycontactid": null,

"primarycontactidname": null,

"telephone1": null

}

}

],

"querycontext": null

}

Our response will be in JSON Format, we can Deserialize the JSON as per our requirement, We’ll show you that later in the Code.

We got three Responses Names–

” Ayden “,

” Aaden K “,

” Aiden “.

Dataverse search Suggestions API

In this case, we are getting records from all CRM Database entities, However, if we wish to perform entity-specific searches, that is also achievable.

Note: It is necessary to specify the entity within the request body. Moreover, it’s possible to define multiple entities by separating them with commas.

{

"entities": ["contact",” account”],

"search": "aiden",

"usefuzzy": true

}

One can also include or exclude an entity from the Dataverse search.

To Configure Dataverse in a way that allows you to Include or Exclude entities based on your requirements, you should refer to our Blog post.

Note:
Fuzzy matches the search term with the PrimaryAttribute of the entity only and even if not specified in the documentation, it seems that the fuzzy search shows only those records with just 1 letter misspelled.

If you want to apply this API search inside the Console App and WPF (Windows Presentation Foundation), you can utilize the following code snippet within them to capture the response

In the below code, we’re using the search term “Aiden” inside the “Account” Entity,

using Microsoft.Xrm.Tooling.Connector;
using Newtonsoft.Json;

using System;

using System.Net.Http;

using System.Threading.Tasks;

 

namespace FuzzyAPIinConsole

{

class Program

{

static void Main(string[] args)

{

//Create a connection string inside which you’ve to pass your Credentials in the given format

string connectionString = @"AuthType=OAuth;Url=https://YOUR_URL.crm8.dynamics.com;Username=YOUR_USERNAME.onmicrosoft.com;Password=YOUR_PASSWORD;AppId=51f81489-12ee-4a9e-aaae-a2591f45987d; RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;LoginPrompt=Auto";

 

//Creating CrmServiceClient object to build the connection by passing the connectionString as a parameter

CrmServiceClient crmService = new CrmServiceClient(connectionString);

 

if (crmService != null)

{

//Create an object of the current class and call the ExecuteAsync method

Program obj = new Program();

Console.WriteLine("connected");

obj.ExecuteAsync(crmService);

Console.ReadLine();

 

}

else

Console.WriteLine("connnection error");

}

 

public async Task ExecuteAsync(CrmServiceClient crmService)

{

//Access token get from CrmServiceClient

string accesstoken = crmService.CurrentAccessToken;

 

// HttpClient Object

HttpClient client = new HttpClient();

 

// Endpoint URL inside HttpRequestMessage to send the request

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"https://YOUR_URL.crm8.dynamics.com/api/search/v1.0/suggest");

 

//Passing access token in the request so that it can connect to the environment

request.Headers.Add("Authorization", $"{accesstoken}");

 

//Specify the request body, as per the body it'll give us the output

var searchRequest = new

{

entities = "account",

search = "aiden",

usefuzzy = true,

};

 

// Serializing the Search Response in JSON format

string jsonContent = JsonConvert.SerializeObject(searchRequest);

 

HttpContent content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");

 

request.Content = content;

 

var response = await client.SendAsync(request);

 

response.EnsureSuccessStatusCode();

 

// Converting the response in string format

string result = await response.Content.ReadAsStringAsync();

 

// Deserialize the JSON response into a dynamic object which is captured in the result variable

dynamic jsonResponse = JsonConvert.DeserializeObject(result);

 

// You'll get all the Data of the record, Here I'm getting the names of the records by the "name" property from each object in the array

foreach (var item in jsonResponse.value)

{

string name = item.document.name;

Console.WriteLine("Name: " + name);

}

Console.ReadLine();

}

}

}

Here is the Result we received in our Console App Based on Fuzzy Logic,

Dataverse search Suggestions API

Code Summary

  • A connection string is Created with OAuth authentication, organization URL, username, password, and app ID (App ID will be same as it is)
  • A `CrmServiceClient` object, `crmService`, is created passing as connectionString as a parameter.
  • The access token is obtained from `crmService.CurrentAccessToken`, So that we can access the environment.
  • An `HttpClient` object named `client` is created for making HTTP requests.
  • The URL for the fuzzy search API endpoint is created using the organization’s URL, Replace the URL with your URL before executing it.
  • An `HttpRequestMessage` object, `request`, is created for a POST request to the ‘suggest’ endpoint.
  • The access token is added to the request headers for authentication.
  • The search request is defined with parameters such as `entities` (Specific Entities to search), `search` (search value), and `usefuzzy` (enabling fuzzy search).
  • The search request is serialized to JSON format and added as the content of the HTTP request.
  • The request is sent asynchronously using `client.SendAsync(request)`.
  • The response is read, ensuring its success and the result is read as a string.
  • Deserialize the JSON response and only take the list of names from all the JSON

Conclusion

Utilizing suggestion searches within Dataverse offers an efficient means of locating information within your dataset. You can tailor your searches to specific requirements by leveraging the “usefuzzy” parameters and filters, thereby enhancing data retrieval and facilitating informed decision-making processes.