Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
}
like image 523
Manspof Avatar asked Mar 07 '23 04:03

Manspof


1 Answers

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.

like image 105
Frank van Puffelen Avatar answered Mar 15 '23 15:03

Frank van Puffelen