Google 지식 그래프 검색 API

이 빠른 시작에서는 Google 지식 그래프 Search API를 소개합니다. 이 빠른 시작에서는 API를 사용하여 Google 지식 그래프에서 항목을 검색하거나 빠른 검색합니다.

새 프로젝트를 계획 중이면 새로운 기능 및 서비스 개선 사항을 활용할 수 있도록 Cloud 지식 그래프 Advanced 버전을 사용하여 애플리케이션을 빌드하세요. Basic 버전은 계속 사용할 수 있지만 새로운 기능, 높은 QPS, 추가 보안 및 규정 준수 표준은 지원하지 않습니다.

Cloud 지식 그래프 항목 검색

다음 샘플은 지식 그래프에서 항목을 검색하는 방법을 보여줍니다.

고급

REST

Advanced 버전의 지식 그래프를 검색하려면 projects.locations.cloudKnowledgeGraphEntities.search 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION: 지식 그래프 위치입니다.
    • 옵션: global - 전역 엔드포인트
  • SEARCH_QUERY: 검색을 위한 리터럴 쿼리 문자열입니다.
  • LANGUAGES: (선택사항) 쿼리를 실행할 언어 코드 목록입니다(ISO 693에 정의됨). 지정하지 않으면 기본값은 en입니다.
  • TYPES: (선택사항) `https://schema.org`에 정의된 대로 반환된 항목을 이러한 유형으로 제한합니다. 여러 유형이 지정된 경우 반환된 항목에는 이러한 유형 중 하나 이상이 포함됩니다. 기본값은 비어 있으며, 유형 제한이 없는 항목을 반환합니다. 지원되는 유형은 Schema.org 전체 계층 구조를 참고하세요.
  • LIMIT: (선택사항) 반환할 항목 수를 제한합니다. 기본값은 20입니다.

HTTP 메서드 및 URL:

GET https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Search?query=SEARCH_QUERY&limit=LIMIT

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Search?query=SEARCH_QUERY&limit=LIMIT"

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Search?query=SEARCH_QUERY&limit=LIMIT" | Select-Object -Expand Content

응답에는 JSON-LD 형식으로 표현되고 제한된 외부 확장 프로그램과 함께 schema.org 스키마와 호환되는 항목 목록이 포함됩니다.

응답 구조에 대한 자세한 내용은 항목 응답 구조를 참조하세요.

다음 JSON-LD 예시는 응답 본문의 구조를 보여줍니다.

{
  "@context": {
    "@vocab": "http://schema.org/"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "result": {
        "@id": "c-07xuup16g",
        "name": "Stanford University",
        "description": "Private university in Stanford, California",
        "detailedDescription": {
          "articleBody": "Stanford University, officially Leland Stanford Junior University, is a private research university in Stanford, California. The campus occupies 8,180 acres, among the largest in the United States, and enrolls over 17,000 students. ",
          "url": "https://en.wikipedia.org/wiki/Stanford_University",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        },
        "url": "http://www.stanford.edu/",
        "image": {
          "contentUrl": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTfPPf-ker0y_892m1wu8-U89furQgQ67foDFncY3r9sREpeWxV",
          "url": "https://es.wikipedia.org/wiki/Archivo:Logo_of_Stanford_University.png"
        },
        "identifier": [
          {
            "@type": "PropertyValue",
            "propertyID": "googleKgMID",
            "value": "/m/06pwq"
          },
          {
            "@type": "PropertyValue",
            "propertyID": "googlePlaceID",
            "value": "ChIJneqLZyq7j4ARf2j8RBrwzSk"
          },
          {
            "@type": "PropertyValue",
            "propertyID": "wikidataQID",
            "value": "Q41506"
          }
        ],
        "@type": [
          "Place",
          "Organization",
          "MovieTheater",
          "Corporation",
          "EducationalOrganization",
          "Thing",
          "CollegeOrUniversity"
        ]
      }
    }
  ]
}

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'
# 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_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.SearchRequest(
        parent=parent,
        query=search_query,
        languages=languages,
        types=types,
        limit=limit,
    )

    # Make the request
    response = client.search(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")

기본

REST

Basic 버전의 지식 그래프를 검색하려면 projects.locations.publicKnowledgeGraphEntities.search 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION: 지식 그래프 위치입니다.
    • 옵션: global - 전역 엔드포인트
  • SEARCH_QUERY: 검색을 위한 리터럴 쿼리 문자열입니다.
  • LANGUAGES: (선택사항) 쿼리를 실행할 언어 코드 목록입니다(ISO 693에 정의됨). 지정하지 않으면 기본값은 en입니다.
  • TYPES: (선택사항) `https://schema.org`에 정의된 대로 반환된 항목을 이러한 유형으로 제한합니다. 여러 유형이 지정된 경우 반환된 항목에는 이러한 유형 중 하나 이상이 포함됩니다. 기본값은 비어 있으며, 유형 제한이 없는 항목을 반환합니다. 지원되는 유형은 Schema.org 전체 계층 구조를 참고하세요.
  • LIMIT: (선택사항) 반환할 항목 수를 제한합니다. 기본값은 20입니다.

HTTP 메서드 및 URL:

GET https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Search?query=SEARCH_QUERY&limit=LIMIT

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Search?query=SEARCH_QUERY&limit=LIMIT"

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Search?query=SEARCH_QUERY&limit=LIMIT" | Select-Object -Expand Content

응답에는 JSON-LD 형식으로 표현되고 제한된 외부 확장 프로그램과 함께 schema.org 스키마와 호환되는 항목 목록이 포함됩니다.

응답 구조에 대한 자세한 내용은 항목 응답 구조를 참조하세요.

다음 JSON-LD 예시는 응답 본문의 구조를 보여줍니다.

{
  "@context": {
    "@vocab": "http://schema.org/"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "result": {
        "@id": "c-07xuup16g",
        "name": "Stanford University",
        "description": "Private university in Stanford, California",
        "detailedDescription": {
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
          "url": "https://en.wikipedia.org/wiki/Stanford_University",
          "articleBody": "Stanford University, officially Leland Stanford Junior University, is a private research university in Stanford, California. The campus occupies 8,180 acres, among the largest in the United States, and enrolls over 17,000 students. "
        },
        "url": "http://www.stanford.edu/",
        "identifier": [
          {
            "@type": "PropertyValue",
            "propertyID": "googleKgMID",
            "value": "/m/06pwq"
          }
        ],
        "image": {
          "contentUrl": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTfPPf-ker0y_892m1wu8-U89furQgQ67foDFncY3r9sREpeWxV",
          "url": "https://es.wikipedia.org/wiki/Archivo:Logo_of_Stanford_University.png"
        },
        "@type": [
          "EducationalOrganization",
          "CollegeOrUniversity",
          "Thing",
          "Place",
          "Corporation",
          "MovieTheater",
          "Organization"
        ]
      }
    }
  ]
}

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

Cloud 지식 그래프 MID에서 항목 조회

Google 지식 그래프 Search API는 더 쉬운 제품 및 Application Integration을 위해 새로운 머신 ID(MID) 형식을 도입합니다. lookup API는 새 Cloud 지식 그래프 MID(c-로 시작)와 Google 지식 그래프 MID(/m로 시작) 모두에서 작동합니다.

고급

REST

고급 버전의 MID로 항목을 조회하려면 projects.locations.cloudKnowledgeGraphEntities.lookup 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION: 지식 그래프 위치입니다.
    • 옵션: global - 전역 엔드포인트
  • LOOKUP_IDS: 조회에 사용할 엔티티 ID 목록입니다.
    • 예: /m/0dl567
  • LANGUAGES: (선택사항) 쿼리를 실행할 언어 코드 목록입니다(ISO 693에 정의됨). 지정하지 않으면 기본값은 en입니다.

HTTP 메서드 및 URL:

GET https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS"

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS" | Select-Object -Expand Content

응답에는 JSON-LD 형식으로 표현되고 제한된 외부 확장 프로그램과 함께 schema.org 스키마와 호환되는 항목 목록이 포함됩니다.

응답 구조에 대한 자세한 내용은 항목 응답 구조를 참조하세요.

다음 JSON-LD 예시는 응답 본문의 구조를 보여줍니다.

{
  "@context": {
    "@vocab": "http://schema.org/"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "result": {
        "description": "American singer-songwriter",
        "@type": [
          "Person",
          "Thing"
        ],
        "name": "Taylor Swift",
        "@id": "c-0260160kc",
        "url": "http://www.taylorswift.com/",
        "identifier": [
          {
            "@type": "PropertyValue",
            "propertyID": "googleKgMID",
            "value": "/m/0dl567"
          },
          {
            "@type": "PropertyValue",
            "propertyID": "wikidataQID",
            "value": "Q26876"
          }
        ],
        "detailedDescription": {
          "articleBody": "Taylor Alison Swift is an American singer-songwriter. Her discography spans multiple genres and her narrative songwriting—often inspired by her personal life—has received critical praise and widespread media coverage. ",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
          "url": "https://en.wikipedia.org/wiki/Taylor_Swift"
        },
        "image": {
          "contentUrl": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSnsjOArwgD-bhyRslj_Qa7Z2tIPLRFU3VnEuLr1ybcyned49Pt",
          "url": "https://pt.wikipedia.org/wiki/Ficheiro:191125_Taylor_Swift_at_the_2019_American_Music_Awards_(cropped).png"
        }
      }
    }
  ]
}
Cloud 지식 그래프에서 여러 항목을 조회하려면 여러 ID를 제공합니다. URL은 다음과 같이 표시됩니다.
https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cloudKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS&ids=LOOKUP_IDS

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_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.LookupRequest(
        parent=parent,
        ids=ids,
        languages=languages,
    )

    # Make the request
    response = client.lookup(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")

기본

REST

Basic 버전의 MID로 항목을 조회하려면 projects.locations.publicKnowledgeGraphEntities.lookup 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION: 지식 그래프 위치입니다.
    • 옵션: global - 전역 엔드포인트
  • LOOKUP_IDS: 조회에 사용할 엔티티 ID 목록입니다.
    • 예: /m/0dl567
  • LANGUAGES: (선택사항) 쿼리를 실행할 언어 코드 목록입니다(ISO 693에 정의됨). 지정하지 않으면 기본값은 en입니다.

HTTP 메서드 및 URL:

GET https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS"

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS" | Select-Object -Expand Content

응답에는 JSON-LD 형식으로 표현되고 제한된 외부 확장 프로그램과 함께 schema.org 스키마와 호환되는 항목 목록이 포함됩니다.

응답 구조에 대한 자세한 내용은 항목 응답 구조를 참조하세요.

다음 JSON-LD 예시는 응답 본문의 구조를 보여줍니다.

{
  "@context": {
    "@vocab": "http://schema.org/"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "result": {
        "description": "American singer-songwriter",
        "@type": [
          "Person",
          "Thing"
        ],
        "name": "Taylor Swift",
        "@id": "c-0260160kc",
        "url": "http://www.taylorswift.com/",
        "identifier": [
          {
            "@type": "PropertyValue",
            "propertyID": "googleKgMID",
            "value": "/m/0dl567"
          }
        ],
        "detailedDescription": {
          "articleBody": "Taylor Alison Swift is an American singer-songwriter. Her discography spans multiple genres and her narrative songwriting—often inspired by her personal life—has received critical praise and widespread media coverage. ",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
          "url": "https://en.wikipedia.org/wiki/Taylor_Swift"
        },
        "image": {
          "contentUrl": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSnsjOArwgD-bhyRslj_Qa7Z2tIPLRFU3VnEuLr1ybcyned49Pt",
          "url": "https://pt.wikipedia.org/wiki/Ficheiro:191125_Taylor_Swift_at_the_2019_American_Music_Awards_(cropped).png"
        }
      }
    }
  ]
}
Cloud 지식 그래프에서 여러 항목을 조회하려면 여러 ID를 제공합니다. URL은 다음과 같이 표시됩니다.
https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publicKnowledgeGraphEntities:Lookup?ids=LOOKUP_IDS&ids=LOOKUP_IDS

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

항목 구조

필드 이름 유형 설명
@id string 항목의 표준 URI입니다.
name string 항목 이름입니다.
@type array 항목과 일치하는 지원되는 schema.org 유형 목록입니다.
description string 항목에 대한 간략한 설명입니다.
image URL 항목을 식별하는 데 도움이 되는 이미지입니다.
detailedDescription string 항목에 대한 자세한 설명입니다.
url URL 항목의 공식 웹사이트 URL입니다(사용 가능한 경우).
identifier array 연결된 다른 ID의 목록입니다(예: WikidataQID).

JSON-LD 키워드

다음과 같은 JSON-LD 키워드는 JSON-LD 사양을 참고하세요.

Schema.org 호환성

각 Schema.org 유형(예: Person) 및 속성(예: name)에는 다음 예와 같이 해당하는 전체 URI가 있습니다.

클래스 이름 URI
유형 Person https://schema.org/Person
유형 Thing https://schema.org/Thing
속성 name https://schema.org/name
속성 description https://schema.org/description

스키마 확장 프로그램

이 API에 사용되는 유형 및 속성은 https://schema.googleapis.com에서 외부 확장 프로그램으로 호스팅됩니다.

각 유형 및 속성에 대한 문서는 해당 URI에서 확인할 수 있습니다.

클래스 이름 URI
유형 EntitySearchResult https://schema.googleapis.com/EntitySearchResult
속성 detailedDescription https://schema.googleapis.com/detailedDescription

지식 그래프 항목

지식 그래프에는 사람, 장소, 사물과 같은 실제 항목을 설명하는 수백만 개의 항목이 있습니다. 이러한 항목은 그래프의 노드를 형성합니다.

다음은 Cloud 지식 그래프에서 발견되는 일반적인 항목 유형입니다.