K20GH
K20GH

Reputation: 6263

Query with multiple where clauses in Firebase

I'm having a bit of trouble with a Firebase query, mainly due to the size of the dataset I am querying.

What I would like to achieve is:

Find all tshirts where brandStartsWith = 'A' and salesRank is between 1 and 100

I've started to pad this out, but I am running into an issue whereby I can't seem to get the data due to having over 300,000 records within t-shirts.

If call it within React when the page loads, after a while I get the following error in console:

Uncaught RangeError: Invalid string length

Here is the code I am using to get me started, but I'm not sure where to go. Looking at the solutions on this question it seems I need to download the data per my query below, and then sort it on the client side. Something I cant seem to do

  firebase.database().ref('tshirts')
    .orderByChild('brandStartsWith')
    .equalTo('A')
    .once('value', function (snapshot) {
       console.log(snapshot.val())
   })

Upvotes: 0

Views: 5293

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You're going to need to create a combined key as you can only do one where clause at a time.

{
    "tShirts" : {
        "brandStartsWith" : 'A',
        "salesRank" : 5
        "brandStartsWith_salesRank" = 'A_00005' //pad for as many sales ranks as you have
    }, {
        "brandStartsWith" : 'B',
        "salesRank" : 108
        "brandStartsWith_salesRank" = 'B_00108' //pad for as many sales ranks as you have
    }, {
        "brandStartsWith" : 'C',
        "salesRank" : 52
        "brandStartsWith_salesRank" = 'C_00052' //pad for as many sales ranks as you have
    }
}

This will allow you to do this query:

firebase.database().ref('tshirts')
    .orderByChild('brandStartsWith_salesRank')
    .startAt('A_00001')
    .endAt('A_00100')
    .once('value', function (snapshot) {
        console.log(snapshot.val())
    })

Don't forget to update your rules to .index brandStartsWith_salesRank

Upvotes: 2

Related Questions