skip to Main Content

I want to setup multi-level index in my firebase realtime database. My database structure looks like this, in which the root key name is jobOpenings which contains child of job opening id (for instance particularJobId) which is going to contain sub child of jobApplications which contains the user information such as age, firstName, etc.

Here is a snapshot of my data
enter image description here

I have made my index rules like this

{
  "rules": {
    ".read": "auth != null",  
    ".write": "auth != null",
    "jobOpenings": {
        "particularJobId" : {
          ".indexOn" : ".value"
        }
    },
  }
}

But I couldn’t able to find the users by their firstName. My query looks like this

const activeUserRef = ref(database, 'jobOpenings/particularJobId');
        const searchQuery = query(
            activeUserRef,
            orderByValue('firstName'),
            equalTo(searchInput)
        );
        const snapshot = await get(searchQuery);
        if (snapshot.exists()) {
            snapshot.forEach((child) => {
                console.log(child.val());
            });
        } else {
            console.log('No data found');
        }

Is it my query wrong or my indexing ?

2

Answers


  1. orderByValue() doesn’t take a parameter, you can use orderByChild() to order your result:

       const searchQuery = query(
           activeUserRef,
           orderByChild('firstName'),
           equalTo(searchInput)
         );
    

    And the equalTo() should contain same value as the one you have in the database.

    Check here for API reference:

    orderByValue()

    orderByChild()

    Login or Signup to reply.
  2. The following changes should do the trick:

    Rules:

    {
      "rules": {
        ".read": "auth != null",  
        ".write": "auth != null",
        "jobOpenings": {
            "particularJobId" : {
              ".indexOn" : ["age", "firstName", ...]
            }
        },
      }
    }
    

    Query:

    const activeUserRef = ref(db, 'jobOpenings/particularJobId');
    const searchQuery = query(
      activeUserRef,
      orderByChild('firstName'),
      equalTo(searchInput)
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search