Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

go - How to get random child from Firebase

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.

question from:https://stackoverflow.com/questions/65931438/how-to-get-random-child-from-firebase

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...