Reputation: 16338
What would a basic example of querying Freebase with MQL from the Java Freebase API (google-api-services-freebase) look like and what is the recommended way for processing the resulting data?
I’m especially wondering how to “correctly” use the com.google.api.services.freebase.Freebase
class.
I have these dependencies in my project:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-freebase</artifactId>
<version>v1-rev42-1.17.0-rc</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.17.0-rc</version>
</dependency>
Now with the following code I can get unparsed JSON results to stdout:
Freebase freebase = new Freebase(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
null);
Mqlread mqlread = freebase.mqlread(
"[{ \"limit\": 5, \"name\": null, \"type\": \"/medicine/disease\" }]");
mqlread.executeAndDownloadTo(System.out);
But what is the recommended way of parsing the returned JSON? Why would I want to use the Freebase API at all, if I should have to manually parse a JSON result stream anyway?
NB: eventually I would like to query for larger amounts of data; the above query is just a simple example.
Upvotes: 4
Views: 1654
Reputation: 4603
You're correct, as it currently stands the standard Google Java client library doesn't offer a lot of benefit over just making the Freebase API calls yourself. This is because the Freebase MQL API can return arbitrarily complex JSON data which makes it difficult for the client library to do anything fancy with it. I like the json-simple library for parsing the results.
The following snippet uses the Google HTTP client library and json-simple to issue a Freebase query and parse the result.
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
String query = "[{\"limit\": 5,\"name\":null,\"type\":\"/medicine/disease\"}]";
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
url.put("key", "YOUR-API-KEY-GOES-HERE");
url.put("query", query);
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(result.get("name").toString());
}
Upvotes: 4