How do I query in GQL using the entity key

倖福魔咒の 提交于 2019-12-03 01:50:37

问题


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'

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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)


来源:https://stackoverflow.com/questions/1998084/how-do-i-query-in-gql-using-the-entity-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!