Skip to content

How to Use the Read Service

hangy edited this page Sep 13, 2010 · 4 revisions

Simple Query

Reads a list of countries by parsing an MQL query from a string.

Java Code


ReadService readService = new ReadService();
QueryParser queryParser = new QueryParser();
String queryText = "[{\"p0:id\":null,\"p1:name\":null,\"type\":\"/location/country\"}]";
Query query = queryParser.parse("q1", queryText );
try {
	ResultSet results = readService.read(query);
	while (results.hasNext()) {
		Result result = results.next();
		String countryId = result.getString("p0");
		String countryName = result.getString("p1");
		System.out.println(countryId + "\t" + countryName);
	}
} catch (IOException e) {
	e.printStackTrace();
} catch (FreebaseServiceException e) {
	e.printStackTrace();
}

You’ll notice that MQL query cursors are handled transparently by the ResultSet so that you can easily iterate through the full set of results.

Parameterized Query

Reads a list of capital cities of South Africa by parsing a parameterized MQL query from a file.

MQL Query


[{
  "capital:name" : null,
  "!/location/country/capital" : {
    "country:id" : null
  }
}]

Java Code


ReadService readService = new ReadService();
QueryParser queryParser = new QueryParser();
Query query = queryParser.parse(new File("capitals_by_country.mql"));
query.setParameterValue("country", "/en/south_africa");
try {
	ResultSet results = readService.read(query);
	while (results.hasNext()) {
		Result result = results.next();
		System.out.println(result.getString("capital"));
	}
} catch (IOException e) {
	e.printStackTrace();
} catch (FreebaseServiceException e) {
	e.printStackTrace();
}

Here we use the same syntax as before to get string values from the results except that we’re able to refer to values by their parameter name rather than using the full property ID.

Reading from the Sandbox

If you’d like to be able to make read queries to the Freebase sandbox all you have to do is point your ReadService at the sandbox URL like this:

ReadService readService = new ReadService(new URL("http://sandbox.freebase.com/api"));
Clone this wiki locally