Library klien Enterprise Knowledge Graph

Halaman ini menunjukkan cara memulai Library Klien Cloud untuk Enterprise Knowledge Graph API. Library klien mempermudah aksesGoogle Cloud API dari bahasa yang didukung. Meskipun Anda dapat menggunakanGoogle Cloud API secara langsung dengan membuat permintaan mentah ke server, library klien memberikan penyederhanaan yang secara signifikan mengurangi jumlah kode yang perlu ditulis.

Baca lebih lanjut Library Klien Cloud dan Library Klien Google API versi lama di Penjelasan library klien.

Menginstal library klien

Python

pip install --upgrade google-cloud-enterpriseknowledgegraph

Untuk mengetahui informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Python.

Menyiapkan autentikasi

Untuk mengautentikasi panggilan ke Google Cloud API, library klien mendukung Kredensial Default Aplikasi (ADC). Library ini mencari kredensial dalam kumpulan lokasi yang ditentukan dan menggunakan kredensial tersebut untuk mengautentikasi permintaan ke API. Dengan ADC, Anda dapat menyediakan kredensial untuk aplikasi di berbagai lingkungan, seperti produksi atau pengembangan lokal, tanpa perlu mengubah kode aplikasi.

Untuk lingkungan produksi, cara menyiapkan ADC bergantung pada layanan dan konteksnya. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan Kredensial Default Aplikasi.

Untuk lingkungan pengembangan lokal, Anda dapat menyiapkan ADC dengan kredensial yang terkait dengan Akun Google Anda:

  1. Install the Google Cloud CLI. After installation, initialize the Google Cloud CLI by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Layar login akan muncul. Setelah Anda login, kredensial Anda akan disimpan dalam file kredensial lokal yang digunakan oleh ADC.

Menggunakan library klien

Contoh berikut menunjukkan cara menggunakan library klien.

Python


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'
# search_query = 'YOUR_SEARCH_QUERY'
# languages = ['en']                    # Optional: List of ISO 639-1 Codes
# types = ['']                          # Optional: List of schema.org types to return
# limit = 20                            # Optional: Number of entities to return


def search_public_kg_sample(
    project_id: str,
    location: str,
    search_query: str,
    languages: Sequence[str] = None,
    types: Sequence[str] = None,
    limit: int = 20,
):
    # 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.SearchPublicKgRequest(
        parent=parent,
        query=search_query,
        languages=languages,
        types=types,
        limit=limit,
    )

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

    print(f"Search Query: {search_query}\n")

    # 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")

Referensi lainnya

Python

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk Python: