How do I query in GQL using the entity key

2019-03-07 17:17发布

How do I write a query against the entity key using GQL in the Google App Engine Data Viewer ?

In the viewer, the first column (Id/Name) displays as name=_1, in the detail view it shows the key as

Decoded entity key: Programme: name=_1
Entity key: agtzcG9................... 

This query does not work:

SELECT * FROM Programme where name = '_1'

5条回答
淡お忘
2楼-- · 2019-03-07 17:46

You can use the entity's key to retrieve it:

SELECT * FROM Programme where __key__ = KEY('agtzcG9...................')

And, you should be able to query using the name similarly:

SELECT * FROM Programme where __key__ = KEY(Programme, '_1')

Note that this is not something that you would want to do in your AppEngine application; as Nick notes in his comment, it is a huge waste of time. Really, this example is only good to show you how to query by Key in the Admin console.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-07 17:46

You don't need to query to get an entity by key at all - you can simply fetch the entity by its key. In Python, you can do this with MyModel.get_by_key_name('_1'). This is 3 to 5 times faster than Adam's suggestion of using a query.

查看更多
Anthone
4楼-- · 2019-03-07 17:49

For numeric IDs, a form similar to the query-by-name works:

SELECT * from Programme where __key__ = KEY('Programme', 1234567)

I found this form especially useful in the Admin Console.

查看更多
虎瘦雄心在
5楼-- · 2019-03-07 17:51

When querying by key, you need to match the key exactly, including the parent and not just the ID or name. Of course, if the parent is null, as in the example above, the ID or Name and the type of entity is enough.

If you have the already encoded entity key, you can just use that like:

SELECT * FROM Programme where __key__ = KEY('agtzcG9...................')

For the simple example above,

SELECT * FROM Programme where __key__ = KEY('Programme', '_1')

will do, but if your key has a parent, like

Paren: id=123

Then the query would be

SELECT * FROM Programme where __key__ = KEY('Paren', 123, 'Programme', '_1')

If the parent itself has a parent, you need to add that too. For more details see the official GQL documentation.

There does not appear to be a way to select everything with the same ID or name regardless of parent.

查看更多
6楼-- · 2019-03-07 17:57

Just a quick note on this: When I use any quotes around any of the args in KEY, the call fails (in the admin console I get the error popup).

For example, for type "mytype" with ID/Name 12345, this does NOT work:

SELECT * FROM mytype WHERE __key__ = KEY('mytype', '12345')

But this does:

SELECT * FROM mytype WHERE __key__ = KEY(mytype, 12345)
查看更多
登录 后发表回答