eggsy84
eggsy84

Reputation: 1139

Cloud datastore order by with ancestor

Language: NodeJS

Is it possible to combine both an order and ancestorKey when querying google cloud data?

Something similar to this:

const ancestorKey = datastore.key({namespace: 'MyNameSpace', 
                                   path: ['MyParentEntity', 'parent_entity_id']});

const query = datastore.createQuery('MyNameSpace', 'my_child_entity')
                        .order('someProperty', {descending: true})
                        .hasAncestor(ancestorKey);

NOTE: The above doesn't work

Upvotes: 0

Views: 480

Answers (1)

Jofre
Jofre

Reputation: 3898

TL;DR: Yes, this is possible.

Through the API, at least, this kind of query is possible.

Example:

  1. First we create the ancestor entity (keep the key ID from the response). [API call]
  2. Then we create a couple of child entities. API calls: [1] [2]
  3. For Datastore queries you'll need an index for each property or combination of properties that you want to query. Datastore provides built-in single-property indexes by default, but your query is composite (ancestor+order_property), so you'll have to build your own indexes. To do so, first write your index.yaml file (I'm creating two indexes, one for ordering ascending and another for descending):

    indexes:
    - kind: child
      ancestor: yes
      properties:
        - name: order
          direction: desc
    
    - kind: child
      ancestor: yes
      properties:
        - name: order
          direction: asc
    
  4. Deploy your indexes with gcloud datastore create-indexes index.yaml

  5. Wait for the indexes to finish building, and then you can perform the query. API calls: [ascending] [descending]

You can test this example in the cloud shell.

Knowing that the API works properly, you just have to implement this in the idiomatic library. Make sure you have your entities properly defined, and your indexes created. If you have doubts, just try your query through the API to verify if it should work within node or not.

Upvotes: 1

Related Questions