1

I want to query Firebase that contains an input. for example in the database structure below, I would like to query all nodes that contains "4140" so I use this code

enter image description here

  var catref = Cataloguedatabase.ref("/Listing Search/");


    return catref.once('value').then(function(snapshot){
    snapshot.forEach(childSnapshot => { 

    let snapdb = childSnapshot.val();
    let key = childSnapshot.key;
    //use ES6 includes function
    if(key.includes(schname)){  

    console.log(childSnapshot.val());
    var searchresults = childSnapshot.val();
    var container = document.getElementById('listing_gallery');
                      // container.innerHTML = '';

    var productCard = `
        <div class="col-sm-3">
        <div class="card" onclick="gotoproduct(this);" id="${key}">
                              `
         container.innerHTML += productCard;
                    }
                })
              })

This works but the problem is that it first query all the child and sort through the array.This is ok for node with few children but when it gets to thousands of children, it becomes impractical. is there a away i can only query key the contains the value in firebase and if not how else can i implement this?

jone2
  • 191
  • 1
  • 4
  • 18

2 Answers2

8

As Doug says, there is no way to query for values that contain a certain string. But you can query for keys that start with a certain substring:

return catref.orderByKey().startAt("4140-").endAt("4140-\uf8ff").once('value').then(function(snapshot){

This will just match the child nodes whose key starts with 4140-.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • is there any other way apart from firebase to accomplish this ? – jone2 Feb 21 '18 at 01:44
  • Kato described a basic approach a while ago here: https://stackoverflow.com/questions/28589092/firebase-query-find-item-with-child-that-contains-string, I recently described the "Firebase can do prefix matches, but not check 'contains' " here: https://stackoverflow.com/a/48426478/209103. I'd nowadays consider using Algolia for a hosted search though. – Frank van Puffelen Feb 21 '18 at 01:50
2

What you're asking is not possible with Firebase Realtime Database. There are no substring queries.

If you're only interested in the first four characters for your query, what you can do is store that string as a child inside that node, then orderByChild() on that child to find only those items that begin with a certain four character sequence.

You can read more about ordering in the documentation.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441