I need to update a bunch of documents in a Firestore database.
I'm successfully retrieving them by using a query, but now I should update the same field in each of them and I'm having troubles with it.
This is what I tried:
def main():
db_credentials = "some_local_file.json"
cred = credentials.Certificate(f"{db_credentials}")
firebase_admin.initialize_app(cred)
db = firestore.client()
user_id = "user_ID_000"
doc_ref_generator = db.collection(u'CollectionName').where(u'UID', u'==', user_id).where(u'Status', u'==', "Active").stream()
for doc_ref in doc_ref_generator:
doc_ref.update({u"Status": u"non_active"})
if __name__ == "__main__":
main()
and I'm getting the error:
File "/Users/user_name/projects/xxx/firestore_check.py", line 17, in main
doc_ref.update({u"Status": u"non_active"})
AttributeError: 'DocumentSnapshot' object has no attribute 'update'
You also have to specify the collection reference and get the document id when iterating the stream(). See sample code below:
# Collection Reference
col_ref = db.collection(u'CollectionName')
doc_ref_generator = col_ref.where(u'UID', u'==', user_id).where(u'Status', u'==', "Active").stream()
for doc_ref in doc_ref_generator:
# Document Reference
doc = col_ref.document(doc_ref.id)
doc.update({u"Status": u"non-active"})
or you could use the reference property to get the document reference from the DocumentSnapshot:
for doc_ref in doc_ref_generator:
# doc = col_ref.document(doc_ref.id)
doc_ref.reference.update({u"Status": u"non-active"})
You can checkout this documentations for more information.
Update a document
Reference
Related
I have searched related to my question but none found.
Below is my tried working code:
import json
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import FormRecognizerClient, FormTrainingClient
from azure.core.credentials import AzureKeyCredential
credentials = json.load(open("creds.json"))
API_KEY = credentials["API_KEY"]
ENDPOINT = credentials["ENDPOINT"]
url = "https://some_pdf_url_which_contains_tables.pdf" #or image url which contains
#table
form_recognizer_client = FormRecognizerClient(ENDPOINT, AzureKeyCredential(API_KEY))
poller = form_recognizer_client.begin_recognize_content_from_url(url)
form_data = poller.result()
for page in form_data:
for table in page.tables:
for cell in table.cells:
for item in cell.text:
print(item)
## But I need table in dictionary format with header names in keys and
## values in values.
I hope I get some help. Thank you.
According to the python Azure form recognizer documentation,
you can use the 'to_dict' method.
result_table = form_data.tables[0].to_dict()
And then you can loop in the dictionary.
I hope it helps you !
I'm trying to download data from Hubspot with the Python helper library from several tables
from hubspot import HubSpot
api_client = HubSpot()
api_client.access_token = 'TOKEN'
contacts = api_client.crm.contacts.get_all()
tickets = api_client.crm.tickets.get_all()
deals = api_client.crm.deals.get_all()
and so on...
Instead of calling every table in a separate way, I was thiniking about looping over a list like this:
def getting_tables (table, api_client):
return api_client.crm.table.get_all()
api_client = HubSpot()
api_client.access_token = 'TOKEN'
tables = ['contacts', 'tickets', 'deals', 'owners' ]
for table in tables:
table = getting_tables(table,api_client)
but when I call api_client.crm.table.get_all() it doesnt take "table" as a place holder for what it comes when I call the function.
How could I do that? Is that possible?
I know I could just call them all separately, but this is for learning purposes mostly.
I've a collection named XYZ in my firestore. And there are 500 documents with different fields in it.
I have to delete multiple documents using a where clause from the collection.
cred = credentials.Certificate('XXXX')
app = firebase_admin.initialize_app(cred)
db = firestore.Client()
batch = db.batch()
doc_ref = db.collection('collection_name').where(u'month', '==', 07).get()
for doc in doc_ref:
batch.delete(doc)
batch.commit()
I tried this but ending up with an error
AttributeError: AttributeError: 'DocumentSnapshot' object has no attribute '_document_path'
Looking for help!
You are passing a DocumentSnapshot object to batch.delete(), which is not allowed. You must pass a DocumentReference object instead, which can be found in a property of a DocumentSnapshot.
batch.delete(doc.reference)
I am listening to changes on the database for collection_group
I cannot access ref (which has path) of a DocumentSnapshot I keep getting the error:
AttributeError: 'DocumentSnapshot' object has no attribute 'ref'
Here is my code:
doc_ref = firestore_db.collection_group(u'collection_name')
doc_ref.on_snapshot(self.__get_snapshot(args))
This is my __get_snapshot method:
def __get_snapshot(self, args):
def on_snapshot(doc_snapshot, changes, read_time):
for doc in doc_snapshot: #crashes
print(u'Received document snapshot: {}'.format(doc.ref))
for change in changes:
if(change.type.name == "MODIFIED"):
print(change.document.ref) #crashes
print(change.document.get("field"))#this works fine
return on_snapshot
The API documentation for DocumentSnapshot says that the reference of the document can be found in its reference property. So you will want to use this: doc.reference.
I'm trying to update a view in bigquery via python. I've been able to create the view using the following approach;
def createView(client):
viewDataset = 'dataset'
viewName = 'name'
view_ref = client.dataset(viewDataset).table(viewName)
view = bigquery.Table(view_ref)
view_sql = """
select * from '{}.{}' where thing = 2
"""".format(viewDataSet, viewName)
view.view_query = view_sql
client.create_table(view)
(Code for explanation purposes)
This worked fine and created the view. I then wanted to run a function that updates the view definition. I reused the same code and it failed with an error saying the view exists already - this makes sense. I then followed this example here;
https://cloud.google.com/bigquery/docs/managing-views
Using the code to update a views SQL query. Basically I swapped the line
client.create_table(view)
for
client.update_table(view)
I get an error saying I have not added the fields attribute... Being a view, I though I wouldn't have to do this.
Can anyone tell me the correct way to use python to update an existing bigquery view?
Cheers
Look! You are using:
"select * from '{}.{}' where thing = 2"
Notice this:
from '{}.{}'
But a table should be referenced as:
from '{}.{}.{}'
This piece of code works to me:
from google.cloud import bigquery
if __name__ == "__main__":
client = bigquery.Client()
dataset_view_id= 'dataset_name'
table_view_id = 'view_name'
view = bigquery.Table(client.dataset(dataset_view_id).table(table_view_id))
##############
###what was in that table? request table info
##############
get_view = client.get_table(view) # API Request
# Display OLD view properties
print('View at {}'.format(get_view.full_table_id))
print('View Query:\n{}'.format(get_view.view_query))
##############
#update the table:
##############
sql_template = (
'SELECT * FROM `{}.{}.{}` where disease="POLIO" ')
source_project_id = "project_from_the_query"
source_dataset_id = "dataset_from_the_query"
source_table_id = "table_from_the_query"
view.view_query = sql_template.format(source_project_id, source_dataset_id, source_table_id)
view = client.update_table(view, ['view_query']) # API request
##############
#Now print the view query to be sure it's been updated:
##############
get_view = client.get_table(view) # API Request
# Display view properties
print('\n\n NEW View at {}'.format(get_view.full_table_id))
print('View Query:\n{}'.format(get_view.view_query))
# [END bigquery_get_view]