How can I get all children doc of a parent in nested hierarchy?

A : HealthCenter:  {_id: 1}
B : HouseHold: {_id: 2}, parent: {_id:1}
C: Person: {_id: 3}, parent: { _id: 2 {parent: {_id: 1}}

Given the above structure. I need to delete all records recursively of a test health center (So delete Health center, Household, people) but I cannot figure out a way to get all the records at once of a certain parent, In this case I need to get B and C record for parent A.

The way our data is structured the child knows about the parent hierarchy but not vice versa.

So I can only think of two ways of doing this:

  1. Retrieving all the docs and searching for the parent _id one by one to filter them.

2: The second option would be to selectively filter each level’s doc using the previous parent Id.

Is there an easier way to do this? I found little to no resources on the hierarchical queries. A Mango Query or steps for query would be highly appreciated

2 Likes

These are the selectors you can use for each level you want to delete. I suggest going with lower levels first so that no contacts are orphaned.

C:

{
   "selector": {
      "parent.parent._id": "1"
   }
}

B:

{
   "selector": {
      "parent._id": "1"
   }
}

A: delete manually or

{
   "selector": {
      "_id": "1"
   }
}

You can add more conditions to the selector if you need to delete only certain contact types:

{
   "selector": {
     "contact_type": "health_center",
      "_id": "1"
   }
}

Also, make sure to delete the reports that might appear at certain levels:

{
   "selector": {
      "type": "data_record",
      "contact.parent.parent._id": "1"
   }
}

If you want to select everything at once, you can use the "$or" operator, but it can be slow and difficult to verify the records before deleting:

{
   "selector": {
      "type": "contact",
      "$or": [
         {
            "parent._id": "1"
         },
         {
            "parent.parent._id": "1"
         }
      ]
   }
}

It would be nice to have an automated script that does everything for us.

Also, when searching for the resources related to these selectors, if mango query does not give you good results, you can try including terms such as couchdb query or cloudant query.

You could look at querying the following couchdb views:

  • data_records_by_ancestor under medic-scripts
  • places_by_type_parent_id_name under medic-scripts
1 Like

Hello @Prajwol, the support scripts, specifically data_deletion with usage detailed in the …HOWTO file and here are a good resource.

3 Likes