検索の概要

  1. 概要
  2. セキュリティ上の考慮事項
  3. 高度なフィルタリング

概要

Freebase Search API は、フリーテキスト クエリを指定して Freebase データにアクセスする手段を提供します。クエリの結果は順序付けされ、数値の関連性スコアが付けられます。

デベロッパーは、フィルタを適用して、検索結果を特定のタイプのデータに制限できます。詳細な検索クエリの作成方法については、検索クックブックをご覧ください。

デベロッパーが Search API を使用する例を次に示します。

  • エンティティの自動提案(Freebase Suggest Widget など)
  • 指定された名前の最も注目すべきエンティティのランキング リストを取得します。
  • Search 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']) + ')')

Ruby

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']
} 
この例では、Httparty ライブラリと Addressable ライブラリを使用します。

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 グラフに保存されているユーザー作成コンテンツのインデックス登録と検索を行います。つまり、ウェブページのコンテンツを安全にエスケープせずに直接使用することはできません。

詳しくは、スタートガイド: セキュリティをご覧ください。

高度なフィルタリング

Search API は、検索を正しいエンティティに絞り込むために、多数のフィルタ制約をサポートしています。

たとえば、「type」フィルタ制約を使用すると、Freebase で最も注目すべき人物のリストを表示できます。

filter=(any type:/people/person)

フィルタ制約では、さまざまな入力を使用できます。

  • スキーマ エンティティまたはユーザーの人間が読める ID。例:
    • 型制約の場合は /people/person
    • ドメイン制約の /film
  • Freebase MID(例):
    • 同じ /people/person 型制約の /m/01g317
    • 上記の /film ドメイン制約の /m/010s
  • エンティティ名(例:
    • 精度の低い /people/person 型制約の "person"
    • "film"(精度が低い /film ドメイン制約の場合)

フィルタ制約は、いくつかのカテゴリに分類できます。詳細については、検索クックブックをご覧ください。

フィルタ制約は、SearchRequest で自由に組み合わせたり、繰り返したりできます。繰り返されるフィルタ制約パラメータは、OR クエリに結合されます。異なるフィルタ制約パラメータまたはグループは、AND クエリに結合されます。

例:

Gore という名前の人物または都市」を検索するには、次のように入力します。

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

この結合動作は、フィルタ パラメータでオーバーライドしてより適切に制御できます。フィルタ パラメータは、制約を結合するためのよりリッチなインターフェースを提供します。これは、任意にネストできる s 式です。演算子は次のいずれかです。

  • any(論理的には OR)
  • all(論理的には AND)
  • not
  • should。最上位レベルでのみ使用でき、制約が省略可能であることを示します。スコアリングでは、省略可能な制約に一致しない一致のスコアは、一致しない省略可能な制約ごとに半分に分割されます。

例:

/people/person タイプまたは /film ドメインで一致させるには、次のようにします。

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