0

I would like to query a particular child from the array of color hex codes.

Here's a snapshot of my database structure:

enter image description here

How do I query a particular hex code and obtain the entire array of its parent object?

AL.
  • 36,815
  • 10
  • 142
  • 281
Ler Ws
  • 317
  • 5
  • 17

2 Answers2

2

You cannot query whether a specific value exists in a list. This is one of the many reasons why the Firebase documentation recommends against using arrays in the database.

But in this case (and most cases that I encounter), you may likely don't really need an array. Say that you just care about what colors your user picked. In that case, you can more efficiently store the colors as a set:

palettes
    -KSmJZ....A5I
        "0x474A39": true
        "0xbA9A7C": true
        "0xDEDEDF": true
        "0x141414": true
        "0x323E35": true
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hmm I see, but would I still be able to obtain all child objects of KSmJZ...A5I for example. The use of this is so that when a user queries a particular hex colour, he will obtain the entire palette of 5 colors stored in this particular parent. – Ler Ws Sep 28 '16 at 20:26
  • Yeah, the best data structure depends on how you want to use it. Which is why I stopped typing where I did. You need to store your data in a way that allows for the use-cases of your app. Often that means that you'll need to store the same data multiple times. For a great introduction, read [NoSQL data modeling](https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/). – Frank van Puffelen Sep 28 '16 at 20:28
1

I did it in a different way,

made a function that does this:

let databaseRef = FIRDatabase.database().reference()
        let HEX1 = hex1.text! as String
        let HEX2 = hex2.text! as String
        let HEX3 = hex3.text! as String
        let HEX4 = hex4.text! as String
        let HEX5 = hex5.text! as String
        let URL = url.text! as String

        // First set
        let colorArray1 = [HEX2, HEX3, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX1).setValue(colorArray1)

        // second set 
        let colorArray2 = [HEX1, HEX3, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX2).setValue(colorArray2)

        // third set
        let colorArray3 = [HEX1, HEX2, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX3).setValue(colorArray3)

        // fourth set
        let colorArray4 = [HEX1, HEX2, HEX3, HEX5, URL]
        databaseRef.child("palette").child(HEX4).setValue(colorArray4)

        // fifth set
        let colorArray5 = [HEX1, HEX2, HEX3, HEX4, URL]
        databaseRef.child("palette").child(HEX5).setValue(colorArray5)

so that when I target any of the 5 hexes, it will bring me back the whole array together with it.

Ler Ws
  • 317
  • 5
  • 17