搜尋總覽

  1. 總覽
  2. 安全性考量
  3. 進階篩選

總覽

Freebase Search API 可讓您透過任意文字查詢存取 Freebase 資料。查詢結果會依據關聯性分數排序。

開發人員可以套用篩選器,將搜尋結果限制為特定類型的資料。如要進一步瞭解如何建構詳細的搜尋查詢,請參閱「搜尋食譜」。

開發人員可能會想透過搜尋 API 執行下列操作:

  • 自動建議實體 (例如 Freebase 建議小工具)
  • 取得具有指定名稱的最顯著實體排序清單。
  • 使用「搜尋 Metaschema」尋找實體。

下列程式碼範例以幾種支援的語言,說明如何搜尋符合「Cee Lo Green」文字的音樂藝人,以及他們創作的「The Lady Killer」。

Python

import json
import urllib

api_key = open(".api_key").read()
query = 'blue bottle'
service_url = 'https://www.googleapis.com/freebase/v1/search'
params = {
 'query': query,
 'key': api_key
}
url = service_url + '?' + urllib.urlencode(params)
response = json.loads(urllib.urlopen(url).read())
for result in response['result']:
  print(result['name'] + ' (' + str(result['score']) + ')')

小茹

require 'rubygems'
require 'cgi'
require 'httparty'
require 'json'
require 'addressable/uri'

API_KEY = open(".freebase_api_key").read()
url = Addressable::URI.parse('https://www.googleapis.com/freebase/v1/search')
url.query_values = {
	'query' => 'Blue Bottle',
	'key'=> API_KEY
}
response = HTTParty.get(url, :format => :json)
response['result'].each { |topic|
  puts topic['name']
} 
這個範例使用 HttpartyAddressable 程式庫。

Java

package com.freebase.samples;

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;

public class SearchExample {
  public static Properties properties = new Properties();
  public static void main(String[] args) {
    try {
      properties.load(new FileInputStream("freebase.properties"));
      HttpTransport httpTransport = new NetHttpTransport();
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
      JSONParser parser = new JSONParser();
      GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
      url.put("query", "Cee Lo Green");
      url.put("filter", "(all type:/music/artist created:\"The Lady Killer\")");
      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 results = (JSONArray)response.get("result");
      for (Object result : results) {
        System.out.println(JsonPath.read(result,"$.name").toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

JavaScript

<!DOCTYPE html>
<html>
<head>
    <script src="https://www.gstatic.com/external_hosted/jquery2.min.js"></script>
</head>
<body><aside class="warning"><strong>Warning: </strong>The Freebase API will be retired on June 30,
  2015.</aside>
<script>
  var service_url = 'https://www.googleapis.com/freebase/v1/search';
  var params = {
    'query': 'Cee Lo Green',
    'filter': '(all type:/music/artist created:"The Lady Killer")',
    'limit': 10,
    'indent': true
  };
  $.getJSON(service_url + '?callback=?', params).done(function(response) {
    $.each(response.result, function(i, result) {
      $('<div>', {text:result['name']}).appendTo(document.body);
    });
  });
</script>
</body>
</html>
這個範例使用 jQuery 程式庫。

PHP

<!DOCTYPE html>
<html>
<body>
<?php
  include('.freebase-api-key');
  $service_url = 'https://www.googleapis.com/freebase/v1/search';
  $params = array(
    'query' => 'Blue Bottle',
    'key' => $freebase_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['result'] as $result) {
    echo $result['name'] . '<br/>';
  }
?>
</body>
</html>

此外,請參閱「用戶端程式庫」頁面,瞭解您偏好的語言是否受到支援。

Search API 說明文件

另請參閱下列說明文件:

安全性考量

Search API 會為儲存在 Freebase 圖形中的使用者原創內容建立索引並進行搜尋。也就是說,您必須先安全逸出網頁上的內容,才能直接使用。

詳情請參閱「開始使用:安全性」。

進階篩選

搜尋 API 支援大量篩選條件,可更準確地搜尋正確的實體。

舉例來說,使用「類型」篩選條件限制,我們可以顯示 Freebase 中最知名人士的清單。

filter=(any type:/people/person)

篩選條件可接受多種輸入內容:

  • 結構定義實體或使用者的易讀 ID,例如:
    • /people/person 類型限制
    • /film 網域限制
  • 例如 Freebase MID:
    • /m/01g317,適用於相同 /people/person 類型限制
    • /m/010s,以符合上述 /film 網域限制
  • 實體名稱,例如:
    • "person",以取得較不精確的 /people/person 類型限制
    • "film",以取得較不精確的 /film 網域限制

篩選條件限制可分為幾個類別。詳情請參閱「搜尋食譜」。

篩選條件可在 SearchRequest 中自由組合及重複使用。重複的篩選條件限制參數會合併為 OR 查詢。不同的篩選條件限制參數或群組會合併為 AND 查詢。

例如:

如要搜尋「名為『Gore』的人或城市」,請嘗試:

query=gore
&filter=(any type:/people/person type:/location/citytown)

您可以使用篩選器參數覆寫這項合併行為,並進一步控管,篩選器參數提供更豐富的介面,可合併限制。這是 s 運算式,可能任意巢狀,運算子為下列其中之一:

  • any,邏輯上為 OR
  • all,邏輯上為 AND
  • not
  • should,只能在頂層使用,表示限制條件為選用。評分時,如果相符項目不符合選用限制,每不符合一項選用限制,分數就會除以 2。

例如:

如要比對 /people/person 類型或 /film 網域,請嘗試:

query=gore
&filter=(any type:/people/person domain:/film)