검색 개요

  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 라이브러리를 사용합니다.

자바

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();
    }
  }
}

자바스크립트

<!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는 올바른 항목을 더 정확하게 검색하도록 수많은 필터 제약 조건을 지원합니다.

예를 들어 '유형' 필터 제약 조건을 사용하면 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)

이러한 결합 동작은 재정의와 제약 조건 결합을 위한 더 풍부한 인터페이스를 제공하는 필터 매개변수로 더 잘 제어할 수 있습니다. S-표현식은 임의로 중첩될 수 있는 s-expression이며, 연산자는 다음 중 하나입니다.

  • any, 논리적으로 OR
  • all, 논리적으로 AND
  • not
  • should: 최상위 수준에서만 사용할 수 있으며 제약 조건이 선택사항임을 나타냅니다. 점수 산출 중 선택적 제약 조건과 일치하지 않는 일치 항목은 일치하지 않는 각 제약 조건의 점수가 절반으로 나누어집니다.

예를 들면 다음과 같습니다.

/people/person 유형 또는 /film 도메인을 일치시키려면 다음을 시도해 보세요.

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