I have the following setup in my realtime database in Firebase:
- my_db_rtdb
-- daily_data
-- A
0
1
2
3
-- K
0
1
2
-- R
0
1
2
3
-- S
0
1
The actual data tree is quite large.
Each of daily_data/<item>
can have multiple childs, where the <item>
is A
, K
, etc. as shown above.
From this setup, I need to get a list of keys under daily_data. In the particular example above, I need to write a Python script that will give me the list as ["A", "K", "R", "S"]
.
And I would like to do this without downloading everything as the data is quite large.
How can I achieve this in Python? I could not make it clear to me by reading the documentation.
CodePudding user response:
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.