Quickstart: Detecting named entities (NER)

Reference documentation | Additional samples | Package (NuGet) | Library source code

Use this quickstart to create a Named Entity Recognition (NER) application with the client library for .NET. In the following example, you will create a C# application that can identify recognized entities in text.

Tip

You can use Language Studio to try Language service features without needing to write code.

Prerequisites

  • Azure subscription - Create one for free
  • The Visual Studio IDE
  • Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, select Go to resource.
    • You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
    • You can use the free pricing tier (Free F0) to try the service, and upgrade later to a paid tier for production.
  • To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.

Setting up

Create a new .NET Core application

Using the Visual Studio IDE, create a new .NET Core console app. This will create a "Hello World" project with a single C# source file: program.cs.

Install the client library by right-clicking on the solution in the Solution Explorer and selecting Manage NuGet Packages. In the package manager that opens select Browse and search for Azure.AI.TextAnalytics. Select version 5.2.0, and then Install. You can also use the Package Manager Console.

Code example

Copy the following code into your program.cs file. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource. Then run the code.

Important

Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint by navigating to your resource's Keys and Endpoint page, under Resource Management.

Important

Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like Azure Key Vault. See the Azure AI services security article for more information.

using Azure;
using System;
using Azure.AI.TextAnalytics;

namespace Example
{
    class Program
    {
        private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
        private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");
        
        // Example method for extracting named entities from text 
        static void EntityRecognitionExample(TextAnalyticsClient client)
        {
            var response = client.RecognizeEntities("I had a wonderful trip to Seattle last week.");
            Console.WriteLine("Named Entities:");
            foreach (var entity in response.Value)
            {
                Console.WriteLine($"\tText: {entity.Text},\tCategory: {entity.Category},\tSub-Category: {entity.SubCategory}");
                Console.WriteLine($"\t\tScore: {entity.ConfidenceScore:F2},\tLength: {entity.Length},\tOffset: {entity.Offset}\n");
            }
        }

        static void Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            EntityRecognitionExample(client);

            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }

    }
}

Output

Named Entities:
        Text: trip,     Category: Event,        Sub-Category:
                Score: 0.74,    Length: 4,      Offset: 18

        Text: Seattle,  Category: Location,     Sub-Category: GPE
                Score: 1.00,    Length: 7,      Offset: 26

        Text: last week,        Category: DateTime,     Sub-Category: DateRange
                Score: 0.80,    Length: 9,      Offset: 34

Reference documentation | Additional samples | Package (Maven) | Library source code

Use this quickstart to create a Named Entity Recognition (NER) application with the client library for Java. In the following example, you will create a Java application that can identify recognized entities in text.

Tip

You can use Language Studio to try Language service features without needing to write code.

Prerequisites

  • Azure subscription - Create one for free
  • Java Development Kit (JDK) with version 8 or above
  • Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, select Go to resource.
    • You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
    • You can use the free pricing tier (Free F0) to try the service, and upgrade later to a paid tier for production.
  • To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.

Setting up

Add the client library

Create a Maven project in your preferred IDE or development environment. Then add the following dependency to your project's pom.xml file. You can find the implementation syntax for other build tools online.

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

Code example

Create a Java file named Example.java. Open the file and copy the below code. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource. Then run the code.

Important

Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint by navigating to your resource's Keys and Endpoint page, under Resource Management.

Important

Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like Azure Key Vault. See the Azure AI services security article for more information.

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;

public class Example {

    private static String KEY = "replace-with-your-key-here";
    private static String ENDPOINT = "replace-with-your-endpoint-here";

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(KEY, ENDPOINT);
        recognizeEntitiesExample(client);
    }
    // Method to authenticate the client object with your key and endpoint
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }
    // Example method for recognizing entities in text
    static void recognizeEntitiesExample(TextAnalyticsClient client)
    {
        // The text that need be analyzed.
        String text = "I had a wonderful trip to Seattle last week.";
    
        for (CategorizedEntity entity : client.recognizeEntities(text)) {
            System.out.printf(
                "Recognized entity: %s, entity category: %s, entity sub-category: %s, score: %s, offset: %s, length: %s.%n",
                entity.getText(),
                entity.getCategory(),
                entity.getSubcategory(),
                entity.getConfidenceScore(),
                entity.getOffset(),
                entity.getLength());
        }
    }
}

Output

Recognized entity: trip, entity category: Event, entity sub-category: null, score: 0.74, offset: 18, length: 4.
Recognized entity: Seattle, entity category: Location, entity sub-category: GPE, score: 1.0, offset: 26, length: 7.
Recognized entity: last week, entity category: DateTime, entity sub-category: DateRange, score: 0.8, offset: 34, length: 9.

Reference documentation | Additional samples | Package (npm) | Library source code

Use this quickstart to create a Named Entity Recognition (NER) application with the client library for Node.js. In the following example, you will create a JavaScript application that can identify recognized entities in text.

Tip

You can use Language Studio to try Language service features without needing to write code.

Prerequisites

  • Azure subscription - Create one for free
  • Node.js v14 LTS or later
  • Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, select Go to resource.
    • You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
    • You can use the free pricing tier (Free F0) to try the service, and upgrade later to a paid tier for production.
  • To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.

Setting up

Create a new Node.js application

In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp 

cd myapp

Run the npm init command to create a node application with a package.json file.

npm init

Install the client library

Install the npm package:

npm install @azure/ai-language-text

Code example

Open the file and copy the below code. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource. Then run the code.

Important

Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint by navigating to your resource's Keys and Endpoint page, under Resource Management.

Important

Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like Azure Key Vault. See the Azure AI services security article for more information.

"use strict";

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");;
const key = '<paste-your-key-here>';
const endpoint = '<paste-your-endpoint-here>';

//an example document for entity recognition
const documents = [ "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800"];

//example of how to use the client library to recognize entities in a document.
async function main() {
    console.log("== NER sample ==");
  
    const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));
  
    const results = await client.analyze("EntityRecognition", documents);
  
    for (const result of results) {
      console.log(`- Document ${result.id}`);
      if (!result.error) {
        console.log("\tRecognized Entities:");
        for (const entity of result.entities) {
          console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
        }
      } else console.error("\tError:", result.error);
    }
  }

//call the main function
main().catch((err) => {
    console.error("The sample encountered an error:", err);
});

Output

Document ID: 0
        Name: Microsoft         Category: Organization  Subcategory: N/A
        Score: 0.29
        Name: Bill Gates        Category: Person        Subcategory: N/A
        Score: 0.78
        Name: Paul Allen        Category: Person        Subcategory: N/A
        Score: 0.82
        Name: April 4, 1975     Category: DateTime      Subcategory: Date
        Score: 0.8
        Name: 8800      Category: Quantity      Subcategory: Number
        Score: 0.8
Document ID: 1
        Name: 21        Category: Quantity      Subcategory: Number
        Score: 0.8
        Name: Seattle   Category: Location      Subcategory: GPE
        Score: 0.25

Reference documentation | Additional samples | Package (PyPi) | Library source code

Use this quickstart to create a Named Entity Recognition (NER) application with the client library for Python. In the following example, you will create a Python application that can identify recognized entities in text.

Tip

You can use Language Studio to try Language service features without needing to write code.

Prerequisites

  • Azure subscription - Create one for free
  • Python 3.8 or later
  • Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, select Go to resource.
    • You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
    • You can use the free pricing tier (Free F0) to try the service, and upgrade later to a paid tier for production.
  • To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.

Setting up

Install the client library

After installing Python, you can install the client library with:

pip install azure-ai-textanalytics==5.2.0

Code example

Create a new Python file and copy the below code. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource. Then run the code.

Important

Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint by navigating to your resource's Keys and Endpoint page, under Resource Management.

Important

Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like Azure Key Vault. See the Azure AI services security article for more information.

key = "paste-your-key-here"
endpoint = "paste-your-endpoint-here"

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example function for recognizing entities from text
def entity_recognition_example(client):

    try:
        documents = ["I had a wonderful trip to Seattle last week."]
        result = client.recognize_entities(documents = documents)[0]

        print("Named Entities:\n")
        for entity in result.entities:
            print("\tText: \t", entity.text, "\tCategory: \t", entity.category, "\tSubCategory: \t", entity.subcategory,
                    "\n\tConfidence Score: \t", round(entity.confidence_score, 2), "\tLength: \t", entity.length, "\tOffset: \t", entity.offset, "\n")

    except Exception as err:
        print("Encountered exception. {}".format(err))
entity_recognition_example(client)

Output

Named Entities:

    Text:    trip   Category:        Event  SubCategory:     None
    Confidence Score:        0.74   Length:          4      Offset:          18

    Text:    Seattle        Category:        Location       SubCategory:     GPE
    Confidence Score:        1.0    Length:          7      Offset:          26

    Text:    last week      Category:        DateTime       SubCategory:     DateRange
    Confidence Score:        0.8    Length:          9      Offset:          34

Reference documentation

Use this quickstart to send Named Entity Recognition (NER) requests using the REST API. In the following example, you'll use cURL to identify recognized entities in text.

Tip

You can use Language Studio to try Language service features without needing to write code.

Prerequisites

  • The current version of cURL.
  • Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, select Go to resource.
    • You need the key and endpoint from the resource you create to connect your application to the API. Paste your key and endpoint into the code later in the quickstart.
    • You can use the free pricing tier (Free F0) to try the service, and upgrade later to a paid tier for production.

Note

  • The following BASH examples use the \ line continuation character. If your console or terminal uses a different line continuation character, use that character.
  • You can find language specific samples on GitHub.
  • Go to the Azure portal and find the key and endpoint for the Language resource you created in the prerequisites. They are located on the resource's key and endpoint page, under resource management. Then replace the strings in the code with your key and endpoint. To call the API, you need the following information:
parameter Description
-X POST <endpoint> Specifies your endpoint for accessing the API.
-H Content-Type: application/json The content type for sending JSON data.
-H "Ocp-Apim-Subscription-Key:<key> Specifies the key for accessing the API.
-d <documents> The JSON containing the documents you want to send.

The following cURL commands are executed from a BASH shell. Edit these commands with your own resource name, resource key, and JSON values.

Named Entity Extraction (NER)

  1. Copy the command into a text editor.
  2. Make the following changes in the command where needed:
    1. Replace the value <your-language-resource-key> with your key.
    2. Replace the first part of the request URL <your-language-resource-endpoint> with your endpoint URL.
  3. Open a command prompt window.
  4. Paste the command from the text editor into the command prompt window, and then run the command.
curl -i -X POST https://<your-language-resource-endpoint>/language/:analyze-text?api-version=2022-05-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key:<your-language-resource-key>" \
-d \
'
{
    "kind": "EntityRecognition",
    "parameters": {
        "modelVersion": "latest"
    },
    "analysisInput":{
        "documents":[
            {
                "id":"1",
                "language": "en",
                "text": "I had a wonderful trip to Seattle last week."
            }
        ]
    }
}
'

JSON response

Note

{
	"kind": "EntityRecognitionResults",
	"results": {
		"documents": [{
			"id": "1",
			"entities": [{
				"text": "trip",
				"category": "Event",
				"offset": 18,
				"length": 4,
				"confidenceScore": 0.74
			}, {
				"text": "Seattle",
				"category": "Location",
				"subcategory": "GPE",
				"offset": 26,
				"length": 7,
				"confidenceScore": 1.0
			}, {
				"text": "last week",
				"category": "DateTime",
				"subcategory": "DateRange",
				"offset": 34,
				"length": 9,
				"confidenceScore": 0.8
			}],
			"warnings": []
		}],
		"errors": [],
		"modelVersion": "2021-06-01"
	}
}

Clean up resources

If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Next steps