1

如何使用 Python 的 Google API 客户端库 ( http://wiki.freebase.com/wiki/Google_API_Client_Libraries#Python )重现以下 MQL 查询

https://api.freebase.com/api/service/mqlread?queries={"q1":[{"name~=":"*doubt*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}], "q2":[{"name~=":"*law*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}]}

以下单个查询有效:

from apiclient import discovery
from apiclient import model
import json
from pprint import pprint

DEVELOPER_KEY = ''

model.JsonModel.alt_param = ""
freebase = discovery.build('freebase', 'v1', developerKey=DEVELOPER_KEY)
query = [{"name~=":"*doubt*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}]
response = json.loads(freebase.mqlread(query=json.dumps(query)).execute())
pprint (response)

我看不到如何将参数“查询”更改为“查询”

4

3 回答 3

1

queries参数已在新 API 中消失。您可以改用类似以下的方式使用文档较少的 RPC 接口:

import urllib
import urllib2
import json

url = 'https://www.googleapis.com/rpc'
requests = [{
  'method': 'freebase.text.get', 
  'apiVersion': 'v1', 
  'params': {
   'id': ['en','bob_dylan']
  }
},{
  'method': 'freebase.text.get', 
  'apiVersion': 'v1', 
  'params': {
    'id': ['en','blade_runner']
  }
}]
headers = { 'Content-Type': 'application/json' }
req = urllib2.Request(url, json.dumps(requests), headers)
response = urllib2.urlopen(req)
print response.read()

[代码片段由 Google 开发人员 Shawn Simister 提供]

于 2012-05-29T14:03:38.403 回答
1

在Google API Python 客户端的下一个版本(1.0 beta 9)中,您将能够将多个查询批处理在一起,如下所示:

from apiclient import discovery, model
from apiclient.http import BatchHttpRequest
import json

DEVELOPER_KEY = open('DEVELOPER_KEY').read()
query1 = [{"name~=":"*doubt*","name":None,"type":"/media_common/quotation","author":[{"name":"William Shakespeare"}]}]
query2 = [{"name~=":"*law*","name":None,"type":"/media_common/quotation","author":[{"name":"William Shakespeare"}]}]

model.JsonModel.alt_param = ""
freebase = discovery.build('freebase', 'v1', developerKey=DEVELOPER_KEY)

def display_results(request_id, response):
    for topic in response['result']:
        print topic['name']

batch = BatchHttpRequest(callback=display_results)
batch.add(freebase.mqlread(query=json.dumps(query1)))
batch.add(freebase.mqlread(query=json.dumps(query2)))
batch.execute(http)

使用这种技术,您可以组合多个查询,甚至 MQL 查询与搜索查询,它只会创建一个 HTTP 请求。

于 2012-05-31T21:16:21.277 回答
0

假设发现文档包含queries参数,我相信它会是:

queries = {"q1":[{"name~=":"*doubt*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}], "q2":[{"name~=":"*law*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}]}
response = json.loads(freebase.mqlread(queries=json.dumps(queries)).execute())
pprint (response)

客户端使用发现文档来确定每个 API 方法接受的参数。因此,只需更改 python 参数的名称就可以了。

于 2012-05-29T09:40:32.830 回答