0

I have a Firebase database with the following structure:

{
  "School" : {
    "Class A" : {
      "Student K" : [ "Language1", "Language2" ],
      "Student L" : [ "Language1", "Language2", "Language3 ],
    },
    "Class B" : {
      "Student M" : [ "Language1", "Language2" ],
      "Student N" : [ "Language1", "Language3 ],
      "Student O" : [ "Language1", "Language2", "Language3 ],
    },
  },
}

Here all languages are different and none of them are same for any student.

I want to retrieve a random Student and Languages pair from this database. I have reference upto the Class node.

I am retrieving all the children of School/Class and then storing them in a map. To get a random key, value pair from them I just traverse the map once using range to get an arbitrary pair.

My code looks like this:

q := constants.GlobalClient.NewRef("School/" + className)
result := make(map[string][]string)
lang, studName := "", ""

if err := q.Get(constants.GlobalCtx, &result); err != nil {
    return nil, err
}

var allLang []string
for key, value := range result {
    studName = key
    allLang = value
    break
}

But, this is not providing the amount of randomness I would want, so I want to just retrieve a random Student, Languages pair from the database query itself.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Panda
  • 499
  • 11
  • 22
  • you can move them in a slice and then use this rand to generate random index https://golang.org/pkg/math/rand/#example_Intn – Shubham Srivastava Jan 28 '21 at 05:59
  • @ShubhamSrivastava Yes, but that would be a rather inefficient approach since there might be a lot of nodes to the `Class`. Also, I saw some posts that do this in JavaScript but there is almost no documentation or example to do this in Go – Panda Jan 28 '21 at 07:24
  • I do not think there is any other way if you use map – Shubham Srivastava Jan 28 '21 at 07:27
  • Anyhow you can use the DB to do something like https://stackoverflow.com/questions/45145596/get-random-item-from-firebase – Shubham Srivastava Jan 28 '21 at 07:28
  • @ShubhamSrivastava my question is exactly this, how to do this in Golang that they do this in the answer above – Panda Jan 28 '21 at 08:37
  • did you check the answer by Guillermo Jose Aiquel – Shubham Srivastava Jan 28 '21 at 08:41
  • @ShubhamSrivastava unfortunately due to problem requirements I can't add random numbers to the database structure itself. But, there should be at least some way a random child is retrieved from a database node in firebase using Golang. – Panda Jan 28 '21 at 09:01

0 Answers0