查詢實體 (基本)

使用 Basic 版,透過 MID 在知識圖譜中查詢實體。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列文章:

程式碼範例

Python

詳情請參閱 Enterprise Knowledge Graph Python API 參考文件

如要向 Enterprise Knowledge Graph 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


from __future__ import annotations

from collections.abc import Sequence

from google.cloud import enterpriseknowledgegraph as ekg

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_GRAPH_LOCATION'      # Values: 'global'
# ids = ['YOUR_LOOKUP_MID']             # https://cloud.google.com/enterprise-knowledge-graph/docs/mid
# languages = ['en']                    # Optional: List of ISO 639-1 Codes


def lookup_public_kg_sample(
    project_id: str,
    location: str,
    ids: Sequence[str],
    languages: Sequence[str] = None,
):
    # Create a client
    client = ekg.EnterpriseKnowledgeGraphServiceClient()

    # The full resource name of the location
    # e.g. projects/{project_id}/locations/{location}
    parent = client.common_location_path(project=project_id, location=location)

    # Initialize request argument(s)
    request = ekg.LookupPublicKgRequest(
        parent=parent,
        ids=ids,
        languages=languages,
    )

    # Make the request
    response = client.lookup_public_kg(request=request)

    print(f"Lookup IDs: {ids}\n")

    print(response)

    # Extract and print date from response
    for item in response.item_list_element:
        result = item.get("result")

        print(f"Name: {result.get('name')}")
        print(f"- Description: {result.get('description')}")
        print(f"- Types: {result.get('@type')}\n")

        detailed_description = result.get("detailedDescription")

        if detailed_description:
            print("- Detailed Description:")
            print(f"\t- Article Body: {detailed_description.get('articleBody')}")
            print(f"\t- URL: {detailed_description.get('url')}")
            print(f"\t- License: {detailed_description.get('license')}\n")

        print(f"- Cloud MID: {result.get('@id')}")
        for identifier in result.get("identifier"):
            print(f"\t- {identifier.get('name')}: {identifier.get('value')}")

        print("\n")

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具