6

I am trying to use GQL to get some data back from the datastore.

When I do a SELECT * FROM Kind request, it works and I get data back.

However when I try:

SELECT * FROM kind where num < 1234

I get a disallowed literal error.

I even tried to do it with quotations:

SELECT * FROM kind where num < '1234'

but I get the same error.

Has anyone run into this before?

Here is the code:

Query<Entity> query = Query.gqlQueryBuilder(Query.ResultType.ENTITY,             
          "SELECT * FROM " + kind + " WHERE num < '100'"
          ).build();
  QueryResults<Entity> results = datastore.run(query);
  while (results.hasNext()) {
    Entity result = results.next();
   myList.add(result.getString("num"));
Bob__
  • 12,361
  • 3
  • 28
  • 42
A Ba
  • 275
  • 2
  • 10

1 Answers1

5

You need to bind the query parameter rather than directly adding it into the query.

Query<Entity> query = Query.gqlQueryBuilder(Query.ResultType.ENTITY,             
                          "SELECT * FROM " + kind + " WHERE num < @num")
                      .setBinding("num", 100)
                      .build();
QueryResults<Entity> results = datastore.run(query);
while (results.hasNext()) {
    Entity result = results.next();
    myList.add(result.getString("num"));
...
Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
  • I'm glad to hear it! Thanks for using Cloud Datastore (☞゚ヮ゚)☞ – Dan McGrath Jun 15 '16 at 15:06
  • I am just curious, where did you learn how to do this? I want to be able to do this from memory or at least know where to look for answers, other than stackoverflow and google haha. – A Ba Jun 15 '16 at 15:09
  • I'm the PM for Datastore, so memory :) Initially though, I just read code from GitHub samples. For example: https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/datastore/src/main/java/com/google/datastore/snippets/Concepts.java#L1008 – Dan McGrath Jun 15 '16 at 15:14
  • Thanks, I am always looking for more resources to learn from. Thank you for the link, it will be very helpful for my project. Are there any other resources similar to this related to GAE that I could use? – A Ba Jun 15 '16 at 17:53
  • I had another question about the datastore. Is it possible for me get aggregated data back? I am trying to find the average number between two range values (dates). – A Ba Jun 15 '16 at 19:59
  • Consider the same reference file you can see that you can also use literal instead of binding (though you need to explicitly enable it). see: https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/datastore/src/main/java/com/google/datastore/snippets/Concepts.java#L1036 – ozarov Jun 16 '16 at 19:07
  • Currently the Google Cloud Datastore does not support aggregation (other than distinct) or functions over different fields. For complete GQL syntax see this: https://cloud.google.com/datastore/docs/apis/gql/gql_reference#gql_versions – ozarov Jun 17 '16 at 19:12
  • @ozarov Thank you Ozarov! – A Ba Jun 21 '16 at 13:02