API Tìm kiếm sơ đồ tri thức của Google

API Tìm kiếm sơ đồ tri thức cho phép bạn tìm thấy các thực thể trong Sơ đồ tri thức của Google. API sử dụng các loại schema.org tiêu chuẩn và tuân thủ thông số kỹ thuật JSON-LD.

Các trường hợp sử dụng thông thường

Một số ví dụ về cách bạn có thể sử dụng API Tìm kiếm sơ đồ tri thức:

  • Nhận danh sách xếp hạng gồm những thực thể đáng chú ý nhất khớp với một số tiêu chí nhất định.
  • Dự đoán hoàn thành các thực thể trong hộp tìm kiếm.
  • Chú thích/sắp xếp nội dung bằng các thực thể của Sơ đồ tri thức.

Để biết thông tin chi tiết về các phương thức và tham số API, hãy xem Tài liệu tham khảo API.

Yêu cầu mẫu

Ví dụ sau đây cho thấy một loại yêu cầu bạn có thể gửi tới API. (Nhưng hãy kiểm tra phần Điều kiện tiên quyết trước tiên. Bạn cũng cần chèn khoá API của riêng mình.)

https://kgsearch.googleapis.com/v1/entities:search?query=taylor+swift&key=API_KEY&limit=1&indent=True

Tìm kiếm mẫu ở trên trả về kết quả JSON-LD tương tự như sau:

{
  "@context": {
    "@vocab": "http://schema.org/",
    "goog": "http://schema.googleapis.com/",
    "resultScore": "goog:resultScore",
    "detailedDescription": "goog:detailedDescription",
    "EntitySearchResult": "goog:EntitySearchResult",
    "kg": "http://g.co/kg"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "@type": "EntitySearchResult",
      "result": {
        "@id": "kg:/m/0dl567",
        "name": "Taylor Swift",
        "@type": [
          "Thing",
          "Person"
        ],
        "description": "Singer-songwriter",
        "image": {
          "contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",
          "url": "https://en.wikipedia.org/wiki/Taylor_Swift",
          "license": "http://creativecommons.org/licenses/by-sa/2.0"
        },
        "detailedDescription": {
          "articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",
          "url": "http://en.wikipedia.org/wiki/Taylor_Swift",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        },
        "url": "http://taylorswift.com/"
      },
      "resultScore": 4850
    }
  ]
}

Các mã mẫu sau đây cho biết cách thực hiện một lượt tìm kiếm tương tự bằng nhiều ngôn ngữ được hỗ trợ. Lượt tìm kiếm này trả về các mục khớp với Taylor Swift.

Python

"""Example of Python client calling Knowledge Graph Search API."""
import json
import urllib

api_key = open('.api_key').read()
query = 'Taylor Swift'
service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
params = {
    'query': query,
    'limit': 10,
    'indent': True,
    'key': api_key,
}
url = service_url + '?' + urllib.urlencode(params)
response = json.loads(urllib.urlopen(url).read())
for element in response['itemListElement']:
  print(element['result']['name'] + ' (' + str(element['resultScore']) + ')')

Java

package com.google.knowledge.platforms.syndication.entitymatch.codesample;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.jayway.jsonpath.JsonPath;
import java.io.FileInputStream;
import java.util.Properties;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/** Example of Java client calling Knowledge Graph Search API */
public class SearchExample {
  public static Properties properties = new Properties();
  public static void main(String[] args) {
    try {
      properties.load(new FileInputStream("kgsearch.properties"));

      HttpTransport httpTransport = new NetHttpTransport();
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
      JSONParser parser = new JSONParser();
      GenericUrl url = new GenericUrl("https://kgsearch.googleapis.com/v1/entities:search");
      url.put("query", "Taylor Swift");
      url.put("limit", "10");
      url.put("indent", "true");
      url.put("key", properties.get("API_KEY"));
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse httpResponse = request.execute();
      JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
      JSONArray elements = (JSONArray) response.get("itemListElement");
      for (Object element : elements) {
        System.out.println(JsonPath.read(element, "$.result.name").toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

JavaScript

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script>
  var service_url = 'https://kgsearch.googleapis.com/v1/entities:search';
  var params = {
    'query': 'Taylor Swift',
    'limit': 10,
    'indent': true,
    'key' : '<put your api_key here>',
  };
  $.getJSON(service_url + '?callback=?', params, function(response) {
    $.each(response.itemListElement, function(i, element) {
      $('<div>', {text:element['result']['name']}).appendTo(document.body);
    });
  });
</script>
</body>
</html>

1.199

<?php
require '.api_key';
$service_url = 'https://kgsearch.googleapis.com/v1/entities:search';
$params = array(
  'query' => 'Taylor Swift',
  'limit' => 10,
  'indent' => TRUE,
  'key' => $api_key);
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
foreach($response['itemListElement'] as $element) {
  echo $element['result']['name'] . '<br/>';
}

Thực thể trong Sơ đồ tri thức

Sơ đồ tri thức có hàng triệu mục nhập mô tả các thực thể trong thế giới thực như con người, địa điểm và sự vật. Những thực thể này tạo thành các nút của biểu đồ.

Sau đây là một số loại thực thể có trong Sơ đồ tri thức: