I have a slight feeling I'm missing the obvious but can't seem to figure this one out.
I'm migrating an API from a traditional MySQL data model to Cloud Datastore and having trouble recursively building the hierarchy tree when filtering a child entity using the Go Library.
My model looks like this:
type Country struct {
Key *datastore.Key `datastore:"__key__"`
Id int
Name string
Region []Region
}
type Region struct {
Key *datastore.Key `datastore:"__key__"`
Id int
Name string
State []State
}
type State struct {
Key *datastore.Key `datastore:"__key__"`
Id int
Name string
}
I'm NOT using nested entities in datastore like the representation above. In datastore I have 3 different entities storing each with its respective Ancestor key as such:
Entity Country: Parent = nil
Entity Region: Parent = Country
Entity State: Parent = Region
I'd like to query for a given list of states and build the correct representation of the entire hierarchy within the structs. I could possible achieve this retrieving all the States entities that satisfy my criteria first:
var state []*State
query := datastore.NewQuery("State").Filter("Name=", params[i])
if _, err = client.GetAll(ctx, query, &state); err != nil {
return nil, err
}
and then iterate over state to look for the region each state belongs to:
var region Region
if err := client.Get(ctx, state[i].Key.Parent, ®ion); err != nil {
return nil, err
}
The problem with this solution is that more than one state returned can belong to the same region and if I get the parent region for each state, I'll ultimately end up with a slice of regions that will likely have repeated regions in it with a single state each.
I know I could solve this through my code sorting and checking if a region has already been added and then just append the state onto it. However, this solution seem to be a very cumbersome way to solve this problem and I'm wondering if I have another alternatives.
Just as a side note, this model is just a simplified representation of the real one. The real model has 9 levels in the hierarchy and users can search as far as the lowest level and the respective tree needs to be represented in the final JSON.