Search code examples
javascriptazure-cognitive-searchappinsights

How to setup Appinsights with azure search javascript sdk


From the Azure Search documentation I know that we have to get some search information to setup appinsights telemetry.

The problem is: How do I get SearchID information from the @azure/search-documents SearchDocumentResult?


Solution

  • Using the @azure/search-documents module, you can set up your client and add custom headers to operations like so:

    const { SearchClient, AzureKeyCredential } = require("@azure/search-documents");
    
    const indexName = "nycjobs";
    const apiKey = "252044BE3886FE4A8E3BAA4F595114BB";
    
    const client = new SearchClient(
      `https://azs-playground.search.windows.net/`,
      indexName,
      new AzureKeyCredential(apiKey)
    );
    
    async function main() {
      var searchId = '';
    
      const searchResults = await client.search('Microsoft', {
        top: 3,
        requestOptions: {
          customHeaders: {
            'Access-Control-Expose-Headers': 'x-ms-azs-searchid',
            'x-ms-azs-return-searchid': 'true'
          },
          shouldDeserialize: (response) => {
            searchId = response.headers.get('x-ms-azs-searchid');
            return true;
          }
        }
      });
    
      console.log(`Search ID: ${searchId}\n`);
    
      for await (const result of searchResults.results) {
        console.log(`${result.document.business_title}\n${result.document.job_description}\n`);
      }
    }
    

    It seems that currently the only way to get them out is the shouldDeserialize callback as shown in the example since it gives you the raw response including the headers before deserializing when the headers are stripped from some objects, such as those paged response objects returned by search.