搜索概览

  1. 概览
  2. 安全注意事项
  3. 高级过滤

概览

Freebase Search API 可根据自由文本查询提供对 Freebase 数据的访问权限。查询结果按顺序排列,并具有数值相关性得分。

开发者可以应用过滤条件,将搜索结果限制为特定类型的数据。如需详细了解如何构建详细的搜索查询,请参阅搜索实用指南

以下是一些开发者可能希望使用 Search API 的示例:

以下代码示例(使用多种受支持的语言)展示了如何搜索与文本“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']
} 
此示例使用 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>

另请参阅客户端库页面,了解您喜爱的语言是否受支持。

搜索 API 文档

另请参阅以下文档:

安全注意事项

Search API 会对存储在 Freebase 图中的用户生成的内容进行索引和搜索。这意味着,您无法直接使用网页上的内容,必须先对其进行安全转义。

如需了解详情,请参阅使用入门:安全性

高级过滤

Search API 支持大量过滤条件,以便更好地将搜索范围限定为正确的实体。

例如,使用“类型”过滤条件限制,我们可以显示 Freebase 中最著名的人员列表。

filter=(any type:/people/person)

过滤条件限制可接受各种输入:

  • 架构实体或用户的可读 ID,例如:
    • /people/person(适用于类型限制)
    • 针对网域限制的 /film
  • Freebase MID,例如:
    • 针对同一 /people/person 类型限制条件的 /m/01g317
    • 上述 /film 网域限制的 /m/010s
  • 实体名称,例如:
    • "person",用于不太精确的 /people/person 类型限制
    • "film" 表示不太精确的 /film 网域限制

过滤条件限制可分为以下几类。如需了解详情,请参阅搜索实用指南

您可以在 SearchRequest 中自由组合和重复使用过滤条件限制。重复的过滤条件限制参数会合并为 OR 查询。不同的过滤条件限制参数或组会组合成 AND 查询。

例如:

如需搜索“名为 Gore 的人或城市”,请尝试以下操作:

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

这种合并行为可以通过 filter 参数进行替换和更好地控制,该参数提供了一个更丰富的接口来合并限制条件。它是一个 s 表达式,可能任意嵌套,其中的运算符是以下之一:

  • any,在逻辑上为“或”
  • all,逻辑上为 AND
  • not
  • should,只能在顶层使用,表示相应限制条件是可选的。在评分期间,不符合可选限制条件的匹配项的得分会因不符合的每个可选限制条件而减半。

例如:

如需根据 /people/person 类型或 /film 网域进行匹配,请尝试以下操作:

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