Google 지식 그래프 검색 API

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

새 프로젝트를 계획 중이라면 새로운 기능과 서비스 개선사항을 활용할 수 있도록 Cloud 지식 그래프 Advanced edition으로 애플리케이션을 빌드하세요. 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