0

I have a query that I use to fetch data from cloud firestore .but it throws me a key error. Not sure what is wrong.the code below.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import pandas as pd
import sys
import os
import fileinput

# Use the application default credentials
cred = credentials.Certificate('creddatabase.json')
firebase_admin.initialize_app(cred)

db = firestore.client()
docs = db.collection(u'testcollection').stream()
users_ref = db.collection(u'testcollection')
docs = users_ref.stream()
array = []
is_header_printed = False

rows_keys = None
out_file = open("testcollection.csv","w")
for doc in docs:
    print(doc.id)
    row_items = doc.to_dict()
    print(doc)
    if(is_header_printed == False):
        rows_keys = list(row_items.keys())
        rows_keys.sort(reverse=False)
        #loop through every key and print the header row
        for key in rows_keys:
            print(key)
            out_file.write(str(key.replace(",","_"))+",")
        out_file.write("\n")
        is_header_printed = True
    for key in rows_keys:
        print(key)
        out_file.write(str(row_items[key]).replace(',',' ')+',')
        out_file.write("\n")

    print(str(doc.to_dict()['StartDate'].year) + '/' + str(doc.to_dict()['StartDate'].month) + '/' + str(doc.to_dict()['StartDate'].day))
out_file.close()

My document in collection looks like this:

Comments: ""
Objectived: "test" 
Media: "test media"
notes: "test notest"
Zone A: 0
Zone B: 0

Error message:

Traceback (most recent call last):
  File "/Users/DataScience/Firebasequery/Firebase_query_for_psolzsol_jnhibtionsingalling.py", line 49, in <module>
    out_file.write(str(row_items[key]).replace(',',' ')+',')
KeyError: 'Media'
Donnald Cucharo
  • 3,866
  • 1
  • 10
  • 17
  • 3
    I would recommend using try catch statements to catch for key errors and log the data that is causing errors so that you can deduce a solution, the data may not be formatted or keyed the way you think. Perhaps try to visualize the data and revisit, additionally it may not always be perfect from the server side so you should account for those with exception handling – Theodore Howell Sep 13 '21 at 20:45
  • You are initializing `rows_keys` only in this if: `is_header_printed == False`, so my guess is that you are using outdated `row_keys` for a row which contains different data. – yedpodtrzitko Sep 14 '21 at 08:48
  • @yedpodtrzitko : Thank you . Each document has some headers that are different. is there a way to merge those headers and print result in a csv file – Sarija Janardh Sep 14 '21 at 16:14

0 Answers0