How to Get Only Keys from Firebase

How to only get child keys in Firebase

From Best practices for data structure in the docs:

Avoid nesting data

Because the Firebase Realtime Database allows nesting data up to 32
levels deep, you might be tempted to think that this should be the
default structure. However, when you fetch data at a location in your
database, you also retrieve all of its child nodes. In addition, when
you grant someone read or write access at a node in your database, you
also grant them access to all data under that node. Therefore, in
practice, it's best to keep your data structure as flat as possible.

That is how Firebase works: If you get an item, you get its children as well. If you don't want this, you should restructure the database.

firebase getting only keys then getting data

Firebase has a shallow parameter which can retrieve only the keys. I verified it's way faster (by a factor of 100), than retrieving the whole nodes.

Here it is in Google App Script (sorry):

class FirebaseNamespace {

get database() {
if(!this._database) {
var firebaseUrl = "https://mydatabase.firebaseio.com/";
var secret = "mysecret";
this._database = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
}
return this._database;
}

get(path, parameters) {
return this.database.getData(path, parameters);
}

keys(path) {
return Object.keys(this.get(path, {shallow:true}));
}

save(path, value) {
this.database.setData(path, value);
return value;
}

}

How to get children keys from Firebase without downloading their children?

To get the ids of those users, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
Log.d("TAG", uid);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);

The output will be:

5Aoz6ZaB9QS7o9M4lsdbh07VGA02
// the other ids

When you attach a listener on a specific node, you get all the data beneath that node. This is how Firebase Realtime database works and unfortanately this behaviour cannot be changed. But there is an workaround in which you can create another separate node in which you can add all those ids separately. The new node should look something like this:

Firebase-root
|
--- userIds
|
--- 5Aoz6ZaB9QS7o9M4lsdbh07VGA02: true
|
--- //other ids

In this case, if you attach a listener on userIds node, you'll get only the desired data and nothing more. The code to get those ids is simmilar with the code above, but instead of using .child("users") you need to use .child("userIds"). The output will be the same.

If you want another behaviour, you can consider using Cloud Firestore where this behaviour isn't an issue anymore.

How to get all child keys in Firebase?

Use Firebase's shallow query https://firebase.google.com/docs/database/rest/retrieve-data#shallow

For example, if your data is structured like this

parent: {
child_0: {...<large data>...},
child_1: {...<large data>...},
child_2: "abc",
child_3: 123
}

The shallow query's result will be:

parent: {
child_0: true,
child_1: true,
child_2: "abc",
child_3: 123
}

How to get just keys from Firebase Realtime Databse

What you need is known as a "shallow query" where the result will contain the value of the current node, but nothing nested under it. This type of query is only accessible in select SDKs that don't have a caching layer such as the Admin SDKs or you can access these queries via the REST API directly. Depending on your use case, consider building an index.

import firebase_admin
from firebase_admin import db

# ... init the SDK ...

ref = db.reference('my_db_rtdb/daily_data') # may only need to be /daily_data (unclear from your question)

# first arg must be False for shallow queries
# ref.get(includeEtag, shallowQuery)
valueAtRef = ref.get(False, True) # as a dict

print(valueAtRef) # print the dict
print([*valueAtRef]) # get the keys as a list

The docs for ref#get(etag, shallow) can be found in the Python Admin SDK Reference.

How can i get only keys from firebase?

Your structure is a Dictionary of Dictionary so you have to cast your snap to [String:[String:Any]] where the key is your "11dot..." and value contains all hours

So try to use this code:

guard let dict = snap.value as? [String:[String:Any]] else { return }
for (key, value) in dict {
for (key2, value2) in value {
print(key2, value2) // this print your hours
}
}

Anyway I suggest you to don't use a observe(.value) which will read all change happened on all child node. Instead use the .childAdded feature of observer.

With a .childAdded you will receive only one child at a time (like a for on child node) and after that only the child added:

Database.database().reference().child("doc1").observe(.childAdded) { (snap) in
guard let dict = snap.value as? [String:Any]
print(dict) // this print data contains on "11dot10" and so on
}

how to get only key from key value pair in firebase ?

You can use keys property .

From official documentation here

keys

A collection containing just the keys of the dictionary.

Again from the official documentation:

When iterated over, keys appear in this collection in the same order
as they occur in the dictionary’s key-value pairs. Each key in the
keys collection has a unique value.

So in your particular case you can do some thing like this:

Since you get dictionary from the firebase server

refUniId.observe(.value, with: { (snapp) in

print("Value><", snapp.key)
print("Key><", snapp.value!)

if let dict = snapp.value as? [String: Any] {

for k in dict.keys {
print(k)
}
}
}


Related Topics



Leave a reply



Submit