Redigera

Dela via


Quickstart: Use the Bing Entity Search Python client library

Use this quickstart to begin searching for entities with the Bing Entity Search client library for Python. While Bing Entity Search has a REST API compatible with most programming languages, the client library provides an easy way to integrate the service into your applications. The source code for this sample can be found on GitHub.

Prerequisites

It is recommended that you use a Python virtual environment. You can install and initialize a virtual environment with the venv module. You can install virtualenv with:

python -m venv mytestenv

Install the Bing Entity Search client library with:

cd mytestenv
python -m pip install azure-cognitiveservices-search-entitysearch

Create and initialize the application

  1. Create a new Python file in your favorite IDE or editor, and add the following import statements.

    from azure.cognitiveservices.search.entitysearch import EntitySearchClient
    from azure.cognitiveservices.search.entitysearch.models import Place, ErrorResponseException
    from msrest.authentication import CognitiveServicesCredentials
    
  2. Create a variable for your subscription key and endpoint. Instantiate the client by creating a new CognitiveServicesCredentials object with your key.

    subscription_key = "YOUR-SUBSCRIPTION-KEY"
    endpoint = "YOUR-ENDPOINT"
    client = EntitySearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    

Send a search request and receive a response

  1. Send a search request to Bing Entity Search with client.entities.search() and a search query.

    entity_data = client.entities.search(query="Gibralter")
    
  2. If entities were returned, convert entity_data.entities.value to a list, and print the first result.

    if entity_data.entities.value:
    
        main_entities = [entity for entity in entity_data.entities.value
                         if entity.entity_presentation_info.entity_scenario == "DominantEntity"]
    
        if main_entities:
            print(main_entities[0].description)
    

Next steps