In this tutorial, i will show you the steps to write a query to get data from datastore of Google Apps Engine. In this case, i will get data from Person Entity. On your application you have save the Person entity like:
And you will print on web the Person:
Salieri Antonio, 16 inches tall
Here is the step to do that:
1. On your servlet, input these code
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
........................
// Get the Datastore Service
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
// The Query interface assembles a query
Query q = new Query("Person");
q.addFilter("lastName", Query.FilterOperator.EQUAL, "Salieri");
q.addFilter("height", FilterOperator.GREATER_THAN_OR_EQUAL, 16);
// PreparedQuery contains the methods for fetching query results
// from the datastore
PreparedQuery pq = datastore.prepare(q);
for(Entity result: pq.asIterable()){
String firstName = (String) result.getProperty("firstName");
String lastName = (String) result.getProperty("lastName");
Long height = (Long) result.getProperty("height");
resp.getWriter().println(lastName + " " + firstName + ", " + height.toString() + " inches tall");
}
In here, if you build and deploy on Google Apps Engine, you will get a Critical message like that:
Uncaught exception from servlet
com.google.appengine.api.datastore.DatastoreNeedIndexException: no matching index found.
The suggested index for this query is:
<datastore-index kind="Person" ancestor="false" source="manual">
<property name="lastName" direction="asc"/>
<property name="height" direction="asc"/>
</datastore-index>
at com.google.appengine.api.datastore.DatastoreApiHelper.translateError(DatastoreApiHelper.java:42)
at com.google.appengine.api.datastore.DatastoreApiHelper$1.convertException(DatastoreApiHelper.java:98)
................
To fix this issue you need to do the step two
2. Create datastore-indexes.xml file to make google known about the Query will execute on application
- Add the datastore-indexes.xml file at war/WEB-INF folder
- Add the these code
<?xml version="1.0" encoding="utf-8"?>
<datastore-indexes autoGenerate="true">
<datastore-index kind="Person" ancestor="false" source="manual">
<property name="lastName" direction="asc"/>
<property name="height" direction="asc"/>
</datastore-index>
</datastore-indexes>
3. Build and Deploy
DONE :)

