0

I have a database which is shown in below

enter image description here

I want to show only the full_names in order. I want that output:

Alan Turing
Alan Turing
Alan Turing
Alan Turing
Alan Turing

I tried with this code below but it shows the user names.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

# Fetch the service account key JSON file contents
cred = credentials.Certificate('BLABLA.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://BLABLA.firebaseio.com/'
})

ref = db.reference('users')
snapshot = ref.order_by_child('full_name').get()
for key in snapshot:
    print(key)

The output is:

alanisawesom
alanisawesome
alanisawesomee
alanisawesomeee
alanisawesomeeee

Where is my fault? Can you fix it?

EDIT: My Rules in Firebase is:

{
  "rules": {
    "users": {
      ".indexOn": ["date_of_birth", "full_name"]
    },
    ".read": "true",
    ".write": "true"
  }
}

1 Answers1

0

Your query tells the database to return the nodes under users ordered by their full_name property. But Firebase still returns the full nodes, not just the property you told it to order on.

To only display the full_name of each node, you need to get that property from each child node in the result. Something like this:

ref = db.reference('users')
snapshot = ref.order_by_child('full_name').get()
for user in snapshot.each():
    print(user.child("full_name").val())

I'm not a Pythonista, so I looked here for help on syntax: How to loop through each firebase database child with python?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807