검색 개요

  1. 개요
  2. 보안 고려사항
  3. 고급 필터링

개요

Freebase Search API는 자유 텍스트 쿼리가 주어지면 Freebase 데이터에 대한 액세스를 제공합니다. 쿼리 결과는 정렬되어 있으며 숫자 관련성 점수가 있습니다.

개발자는 필터를 적용하여 검색 결과를 특정 유형의 데이터로 제한할 수 있습니다. 자세한 검색 쿼리를 구성하는 방법에 대한 자세한 내용은 검색 Cookbook을 참고하세요.

개발자가 검색 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();
    }
  }
}

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 문서

다음 문서도 참고하세요.

  • API 사용 방법에 관한 자세한 내용은 검색 참조 문서를 참고하세요.
  • 자세한 검색 쿼리를 구성하는 방법에 대한 자세한 내용은 검색 Cookbook을 참고하세요.
  • 엔티티와 속성 간의 관계가 설명되는 방식에 관한 자세한 내용은 검색 메타 스키마 문서를 참고하세요.

보안 고려사항

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 도메인 제약 조건의 경우

필터 제약 조건은 몇 가지 카테고리로 분류할 수 있습니다. 자세한 내용은 검색 Cookbook을 참고하세요.

필터 제약 조건은 SearchRequest에서 자유롭게 결합하고 반복할 수 있습니다. 반복되는 필터 제약 조건 매개변수는 OR 쿼리로 결합됩니다. 서로 다른 필터 제약 조건 매개변수 또는 그룹이 AND 쿼리로 결합됩니다.

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

'고어라는 이름의 사람 또는 도시'를 검색하려면 다음을 시도해 보세요.

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)