Manspof
Manspof

Reputation: 357

Firebase warning: Using an unspecified index when search data with Firebase Cloud Function

I built a Firebase Cloud Function that looks for users who has value of 'IsNotificationEnabled' equal to true . Part of my Function

export const sendPushNotification = functions.https
.onRequest(async (req, res) => {
    try {
        const { message } = req.body;
        var usersRef = firebase.ref('/Users');
        var usersPushNotificationTokensRef = firebase.ref('/PushNotificationTokens')

        var listUsersSendNotifications = [],
            usersWithTokenSendNotifications = [],
            promises = [];
        if (message) {
            await usersRef.orderByChild('IsNotificationEnabled').equalTo(true).once('value', (snapshot) => {
                snapshot.forEach((childSnapshot) => {
                    console.log(childSnapshot.key)
                    listUsersSendNotifications.push(childSnapshot.key)

                    return false;
                })
            })
            ..........................

as you can see here I'm looking users where IsNotificationEnabled = true. when I run it I get in logs

[2018-05-22T09:12:57.352Z] @firebase/database: FIREBASE WARNING: Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "IsNotificationEnabled" at /Users to your security rules for better performance.

the rules I insert in firebase console

    {
  "rules": {
     ".indexOn": ["IsNotificationEnabled"],

    "Users":{
      "$uid":{
      ".indexOn": ["IsNotificationEnabled"],
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }


    },
    ".read": true,
    ".write": true
  }
}

Upvotes: 4

Views: 2238

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598886

As the message says, you'll need to add the index to /Users. You're now adding it one level lower, where it won't work.

{
  "rules": {
    "Users":{
      ".indexOn": ["IsNotificationEnabled"]
    },
    ".read": true,
    ".write": true
  }
}

I find it easiest to remember where to define an index by thinking of where I run my query. Since your query runs on /Users, you need to define your index on that level.

I also remove your .read and .write rules on /Users/$uid, since they are ineffective. You're granting full read/write access at the root already, and permission cannot be taken away at a lower level.

Upvotes: 7

Related Questions