Knossos
Knossos

Reputation: 16048

How to implement a where clause in Datastore on AppEngine

The purpose of this API is to list all Servers owned by a certain User E-mail Address.

If I remove the filter, then the method returns all Servers (as expected). The problem, is that I need to filter by a specific E-mail Address, which only ever returns a result such as:

{
 "kind": "serverApi#resources",
 "etag": "\"q4aBTdWQBYSnhbijLrKGtcu63OU/cXL3GSvQ29gE3tK-4VKxQrWjAt0\""
}

I am expecting a result similar to:

{
 "items": [
  {
   "id": "1",
   "hostname": "aaa",
   "ip": "192.168.1.2",
   "mac": "00:00:00:00:00:00",
   "user": "[email protected]",
   "domain": "HOME",
   "kind": "serverApi#resourcesItem"
  },
  {
   "id": "2",
   "hostname": "bbb",
   "ip": "192.168.1.1",
   "mac": "00:00:00:00:00:00",
   "user": "[email protected]",
   "domain": "HOME",
   "kind": "serverApi#resourcesItem"
  },
  {
   "id": "3",
   "hostname": "ccc",
   "ip": "192.168.1.3",
   "mac": "00:00:00:00:00:00",
   "user": "[email protected]",
   "domain": "HOME",
   "kind": "serverApi#resourcesItem"
  },
  {
   "id": "4",
   "hostname": "ddd",
   "ip": "192.168.1.4",
   "mac": "00:00:00:00:00:00",
   "user": "[email protected]",
   "domain": "HOME",
   "kind": "serverApi#resourcesItem"
  }
 ],
 "kind": "serverApi#resources",
 "etag": "\"q4aBTdWQBYSnhbijLrKGtcu63OU/cXL3GSvQ29gE3tK-4VKxQrWjAt0\""
}

The code I am using on my Endpoint.

public CollectionResponse<Server> listServerByUser(User user) throws OAuthRequestException {
    List<Server> records = new ArrayList<Server>();

    Query<Server> query = ofy().load().type(Server.class).filter("mUser", user.getEmail());
    QueryResultIterator<Server> iterator = query.iterator();
    while (iterator.hasNext()) {
        records.add(iterator.next());
    }

    return CollectionResponse.<Server>builder().setItems(records).build();
}

Columns as shown in the Datastore Viewer on the AppEngine Dashboard:

ID/Name mDomain mHostname mIp mMac mUser

Upvotes: 0

Views: 205

Answers (2)

Deviling Master
Deviling Master

Reputation: 3113

You need to index the properties where you are filtering or ordering on.

Since you're using Objectify, you need to edit the User class with the proper @Index annotation

Here is the full guide to the indexing process

https://code.google.com/p/objectify-appengine/wiki/Queries

After you add the annotation, the indexing process is not retroactive. You need to put again all entities the property of each entity (a simple get+put with Objectify is enough)

Upvotes: 1

Andrei Volgin
Andrei Volgin

Reputation: 41089

If mUser property is not indexed, you are not going to find any results when you use it in a filter.

Upvotes: 1

Related Questions