0

Is there a way to return Entities of kind that have no descendants in Google Cloud Datastore?

Brandon
  • 375
  • 2
  • 16

1 Answers1

0

If your question is if you can retrieve an entity that has no descendants, then yes. You can retrieve any entity through their key (or through a query).

However, if you intend to run a query that retrieves all the child-less entities, this will not be possible. The ancestry information is stored in the descendant entities, so you should recover all the ancestor keys for all the entities (through a projection query), store all the keys for their ancestors, and then run a query for all the entities checking those that are not ancestors to any entity.

Using curl and jq in a shell, it could be something like the following:

export ancestors=$(gcurl -s -H'content-type:application/json' "https://datastore.googleapis.com/v1/projects/$(gcloud config get-value project):runQuery?fields=batch%2FentityResults%2Fentity%2Fkey%2Fpath" -d"{
 \"partitionId\": {
  \"projectId\": \"$(gcloud config get-value project)\",
  \"namespaceId\": \"namespace_id\"
 },
 \"query\": {
  \"kind\": [
   {
    \"name\": \"descendant_entity_name\"
   }
  ],
  \"projection\": [
   {
    \"property\": {
     \"name\": \"__key__\"
    }
   }
  ]
 }
}" | jq '[.batch.entityResults[].entity.key.path | select(length > 1 ) | .[-2].id]')

gcurl -H'content-type:application/json' "https://datastore.googleapis.com/v1/projects/$(gcloud config get-value project):runQuery?fields=batch%2FentityResults%2Fentity%2Fkey%2Fpath" -d"{
 \"partitionId\": {
  \"projectId\": \"$(gcloud config get-value project)\",
  \"namespaceId\": \"namespace_id\"
 },
 \"query\": {
  \"kind\": [
   {
    \"name\": \"ancestor_entity_name\"
   }
  ],
  \"projection\": [
   {
    \"property\": {
     \"name\": \"__key__\"
    }
   }
  ]
 }
}" | jq '.batch.entityResults[].entity.key.path[-1].id | select(inside(env.ancestors)|not)'
Jofre
  • 3,718
  • 1
  • 23
  • 31