Navigate to <CF_HOME>/cfusion/bin.
Overview
Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. While the Firestore interface has many of the same features as traditional databases, as a NoSQL database it differs from them in the way it describes relationships between data objects. In ColdFusion, we've integrated Firestore as an additional NoSQL solution.
For more information, see GCP Firestore.
Native mode vs Datastore mode
When you create a Firestore database, you can configure the database instance to run in either Datastore mode, which makes the database backward compatible with Datastore, or the Native mode which has all the new Firestore features.
ColdFusion supports Firestore in native mode through APIs as the datastore mode uses the APIs of datastore.
Data Model
Cloud Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in documents, which are organized into collections. Each document contains a set of key-value pairs. Cloud Firestore is optimized for storing large collections of small documents. All documents must be stored in collections. Documents can contain subcollections and nested objects, both of which can include primitive fields like strings or complex objects like lists.
Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.
To structure your data in Firestore, you create documents, which in turn implicitly create collections (like tables in SQL). These collections contain documents, like rows in SQL. Each document contains fields that contain the actual data. You can refer to a document using its path, or you can query a collection of documents for the intended data.
Indexing
Firestore uses two types of indexes single field and composite field. By default, Cloud Firestore automatically maintains single-field indexes for each field in a document and each subfield in a map. You can exempt a field from your automatic indexing settings by creating a single-field index exemption. An indexing exemption overrides the database-wide automatic index settings. An exemption can enable a single-field index that your automatic indexing settings would otherwise disable or disable a single-field index that automatic indexing would otherwise enable.
For cases where exemptions can be useful, see the indexing best practices.
Get started
Install gcpfirestore package
To install the package gcpfirestore, use the Package Manager page in the ColdFusion Administrator, or follow the steps below:
-
-
Enter the command:
- Windows: cfpm.bat
- Non-Windows: ./cfpm.sh
-
Enter the command, install gcpfirestore.
Wait for the package to get installed.
Get credentials to access GCP Firestore
When you interact with GCP, you specify your GCP security credentials to verify your credentials and check whether you have permission to access the resources that you are requesting.
GCP uses the security credentials to authenticate and authorize your requests.
For more information, see GCP API Keys Overview.
Authentication for GCP services
To access GCP services, create a service account using Google cloud console (you may alternatively use gcloud CLI, REST calls or do it programmatically). Such accounts are managed by Google Cloud's Identity and Access Management (IAM).
For more information, see Authentication for GCP Services.
Add cloud service credentials and configuration
In ColdFusion (2021 release), there is a method getCloudService() that gives you a handle to create objects for accessing various cloud services.
The syntax of the service handle is as follows:
service=getCloudService(cloudCred,cloudConfig), where:
- cloudCred: Defines the credentials for the cloud service. It could either be a struct or a string (also known as credential alias).
- cloudConfig: Defines the cloud service configuration details. It could either be a struct or a string (also known as config alias).
ColdFusion Administrator
Set credentials
In the ColdFusion Administrator, click Data & Services > Cloud Credentials.
An alias is a named representation of a cloud service and its configuration details. You can set the config alias through ColdFusion Administrator.
After entering the details, click Add Credential.
Set configuration options
In the ColdFusion Administrator, click Data & Services > Cloud Configuration.
Enter the following details, like configuration Alias, Vendor, and the name of the service.
Create the object
Once you've created the aliases for GCP credential and configuration options, you can create the object by using the getCloudService API and include the following in your CFM.
fsObject= getCloudService("fsCred", "fsConf")
Credentials JSON file
The credential JSON file contains the project ID and the private keys that help you authenticate with the GCP services. All keys, including the project_id are mandatory keys in the file.
Application.cfc
You can specify the file containing the GCP credentials and configuration options in Application.cfc. For example,
component{ this.name ="FireStore_Test" this.serialization.preservecaseforstructkey=true this.enableNullSupport=true void function onApplicationStart(){ application.gcpCred = { projectId : "my-gcp-project", credentialJsonFilePath : "C:\path\Gcp_Firestore\my-gcp-project-250541665619.json" }; application.gcpConf = { serviceName : "FIRESTORE" }; } }
Create an object. Use the snippet below:
fsObject = getCloudService(application.fsCred, application.fsConf)
On CFM page
On a CFM page, you can specify the GCP credentials and configuration options in one of the four methods, specified below:
Credential and configuration alias
After you've created the aliases for GCP credential and configuration options, you can use these aliases in the getCloudService handle as shown below:
<cfscript> // define the credential and the configuration aliases in the ColdFusion Admin fsObject=getCloudService("fsCred","fsConf") // code below. ........... </cfscript>
Credential alias and struct
<cfscript> // Using credential alias and struct for service config fsConf = { "alias":"gcpConf", "serviceName" : "GCP_STORAGE", "clientOverrideConfig":{ "retryPolicy":{ "numRetries":4 } }, "httpClientConfig":{ "maxConnections":50 } } fsObject= getCloudService("fsCred", fsConf) // code below ..................... </cfscript>
Configuration alias and struct
<cfscript> // Using config alias and struct for service credentials // GCP credentials fsCreds={ "vendorName":"GCP", "alias": "fsCred", "projectId":"1234", " credentialJsonFilePath ": "file path" } fsObject= getCloudService(fsCreds, "fsConf") // code below ..................................... </cfscript>
Credential and configuration structs
<cfscript> // Using Structs for both cloud credential and config fsCreds={ "vendorName":"GCP", "alias": "fsCred", "projectId":"1234", " credentialJsonFilePath ": "file path" } fsConf = { "alias":"fsConf", "serviceName" : "firestore", "clientOverrideConfig":{ "retryPolicy":{ "numRetries":4 } }, "httpClientConfig":{ "maxConnections":50 } } fsObject= getCloudService(fsCreds, fsConf) // code below ................................................................... </cfscript>
CFSetup
Cloud credentials
Add
- add cloudcredential alias=FirestoreCred credentialJSONFilePath=<location to cred.json> projectId=proj-id vendorName=GCP
Set
- set cloudcredential firestoreCred projectId=proj-id
Get
- get cloudcredential firestoreCred credentialJSONFilePath
Show
- show cloudcredential firestoreCred
Export
- export cloudcredential ccd.json
Delete
- delete cloudcredential firestoreCred
Import
- import cloudcredential ccd.json
Cloud configuration
Add
- add cloudconfiguration alias=firestore1 keepAliveTime=1m keepAliveTimeout=30s keepAliveWithoutCalls=YES maxInboundMessageSize=10 databaseId=(default) emulatorHost=127.0.0.1:8500 host=firestore.googleapis.com:443 initialRetryDelay=1s initialRpcTimeout=50s maxAttempts=6 maxRetryDelay=32s maxRpcTimeout=50s retryDelayMultiplier=2 rpcTimeoutMultiplier=1 totalTimeout=50s serviceName=FIRESTORE
Set
- set cloudconfiguration firestore1 keepAliveTime=2m keepAliveTimeout=1m keepAliveWithoutCalls=NO
Get
- get cloudconfiguration firestore1 keepAliveTime keepAliveTimeout keepAliveWithoutCalls
Show
- show cloudconfiguration firestore1
Delete
- delete cloudconfiguration firestore1
Export
- export cloudconfiguration ccf.json
Import
- import cloudconfiguration ccf.json
ColdFusion GCP Firestore APIs
The APIs in Firestore are async, except for the management APIs. ColdFusion uses built-in Future rather than providing synchronous results.
collection
Description
Gets a CollectionReference that refers to a collection at the specified path.
Syntax
firestoreHandle.collection(String path)
Parameters
- Path: The collection at the specified path.
Returns
Reference to a collection.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) // create the document docData = ${ name: "Bangalore", state: "KA", country: "INDIA" } // add document to the collection res = db.collection("cities_D").runQuery().get(); // get the document writeOutput(ArrayLen(res.getDocuments())) </cfscript>
Collection group
Description
Creates and returns a reference to a collection group that includes all documents in the database that are contained in a collection or subcollection with the given id.
Syntax
FirestoreHandle.collectionGroup(String id)
Returns
Reference to a collection group.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) // Creates and returns a new CollectionGroup that includes all documents in the database that are contained in a collection or subcollection with the given id reviews=db.collectionGroup("reviews") query=reviews.whereEqualTo("author","ravi") results = query.runQuery().get() writeDump(results) </cfscript>
List collections
List all collections in the db.
Syntax
firestoreHandle.listCollections()
Returns
References of collections in the document
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) // get list of all collections in a db collections=db.listCollections() // get number of collections writeOutput(collections.size()) </cfscript>
Get all documents
Retrieves multiple documents from Firestore, while optionally applying a field mask to reduce the amount of data transmitted.
Syntax
firestoreHandle.getAll(Array paths,Array masks)
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) gettAllData=db.getAll([db.document("Restaurants_D/restaurant1"), db.document("Restaurants_D/restaurant3")], ["LOCATION", "NAME"]).get() cfloop(array="#gettAllData#", item="itm") { cfloop(collection = "#itm.getData()#",item = "key") { writeOutput(key); writeOutput(" "); writeOutput(itm.getData()[key]); writeOutput(" "); } } </cfscript>
Create and Update
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docRef = db.collection("Ecom_D").document("Order2"); docData = ${ OrderID: 1002233, ItemID: 00001, Price: 499.00, Seller: "ABC" } docRef.set(docData).get() writeOutput(docRef.getDocument().get().getID()) //writeOutput(docRef.getDocument().get()) </cfscript>
Add a new document
Description
Adds a new document to the collection with some unique document id generated by Firestore.
Syntax
add(struct data)
Parameters
- Data: The data to add in a document.
Returns
Future of timestamp, when the document is added.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) docData=${ firstName: "Jack", lastName: "Sparrow", age2: #Int(22)#, arrMarks: [89,90,91,92], percentage: 90.54, isPass: True, feeDue: "Null" } // add the data response=db.collection("Student_D").add(docData).get() writeDump(response) </cfscript>
Add an object
Description
Adds a new document to the collection with the specified object.
Syntax
add(cfobject data)
Parameters
- Data: The object to add to the document.
Returns
Future of timestamp, when the document is added.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) objPerson = new testFiles._Person("Jack", "Sparrow", 8989898989); response=db.collection("Users_D").add(objPerson).get() writeDump(response) </cfscript>
Create a document
Description
Creates a document at the specified location. If the document already exists, the creation fails.
Syntax
create(Struct data)
Parameters
- Data: The data to add in the document to be created.
Returns
Future of timestamp, when the document is created.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) docSchool2=${ name:"NYU", location:"NY", year:2010 } try{ createResponse=db.collection("Coll_Doc_2").document("doc_Doc_2").create(docSchool2).get() writeOutput("Document created successfully") writeDump(createResponse) } catch(any e){ writeDump(e) } </cfscript>
Get multiple documents
Syntax
getAll(Array documentReferences)
Parameters
- DocumentReferences: Array of documents.
Returns
Future of array of document snapshots.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docRef1 = db.collection("Cities_s").document("SF15"); docRef2 = db.collection("Cities_s").document("SF16"); docData = ${ Country: "USA", Population: 901 } docData1 = ${ Country: "USA", Population: 902 } docRef1.set(docData).get(); docRef2.set(docData1).get(); returnValue = db.runTransaction(transaction => { try { getAllFuture=transaction.getAll([docRef1, docRef2], ["Population"]).get(); cfloop(array="#getAllFuture#", item="itm") { cfloop(collection = "#itm.getData()#",item = "key"); { if(itm.getData()["Population"] > 900) transaction.update(db.document(itm.getPath()), {"Population" : itm.getData()["Population"]+1}); } } return transaction; } catch (any e) { return e; } }).get(); </cfscript>
Create a document using object data
Description
Creates a document at the specified location using the specified object. If the document already exists, the creation fails.
Syntax
create(cfobject data)
Parameters
- Data: The object to add to the document to be created.
Returns
Future of timestamp, when the document is created.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) db = getCloudService(this.cred, this.conf); objPerson1 = new testFiles._Person("Jack", "Sparrow", 9090909090); response=db.collection("Users_D").document().create(objPerson1).get() writeDump(response) </cfscript>
Overwrite a document
Description
Overwrites a document at the specified location. If the document does not exist, it will be created. If the document already exists, it will be overwritten.
Syntax
set(Struct data)
Parameters
- Data: The data to add for the document to get updated.
Returns
Future of timestamp, when the document is edited.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) for (i = 1; i <= 5; i++) { docData = ${ name: "Chicago"&i, state: "IL"&i, country: "USA"&i } response=db.collection("cities_D").document(i).set(docData); //Updating the document writeDump(response) } </cfscript>
Overwrite a document using object data
Description
Overwrites a document at the specified location using the specified object. If the document does not exist, it will be created. If the document already exists, it will be overwritten.
Syntax
set(cfobject data)
Parameters
- Data: The object to add for the document to get updated.
Returns
Future of timestamp, when the document is edited.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) objPerson = new testFiles._Person("Joy", "Division", 8989898989); future = runAsync(x => db.collection("Users_D").document("D1").set(objPerson).get()) writeDump(future) </cfscript>
Update fields of a document
Description
Updates the fields of the document at that location.
Syntax
update(Struct fields)
Parameters
- Fields: The struct to replace the existing fields in a document.
Returns
Future of timestamp, when the document is updated.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) docRef = db.collection("Cities_D").document("SF12"); docData = ${ Country: "USA", Population: 860000 } docData1 = ${ Country: "USA", Population: 90000 } docRef.set(docData).get(); createdDate=docRef.getDocument().get().getCreateTime(); response=docRef.update(docData1,createdDate).get() writeDump(response) </cfscript>
Update
Description
Updates the fields of a document with a time stamp.
Syntax
update(Struct fields, dateTime timestamp)
Parameters
- Fields: The struct to replace the existing fields in a document.
- Timestamp: Update the document based on a date.
Returns
Future of timestamp, when the document is updated.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) docRef = db.collection("Cities_D").document("SF12"); docData = ${ Country: "USA", Population: 860000 } docData1 = ${ Country: "USA", Population: 90000 } docRef.set(docData).get(); createdDate=docRef.getDocument().get().getCreateTime(); docRef.update(docData1,createdDate).get(); //Trying to update with the datetime precondition. writeOutput("Population is updated") response=db.document("Cities_D/SF12").getDocument().get().getData()["Population"]); writeDump(response) </cfscript>
The add, set, update, and delete methods return a Future object as a return value, which means that you can make use of ColdFusion's Future abilities. The example below illustrates a different way through which you can process the call via chaining. As chaining uses worker threads, the results from these use separate buffers from the main thread and writing them to a file.
For Example,
<cfscript> aUser = ${ firstName: "Harry", lastName: "Potter", age: 14, address: "Hogwarts" } harry = db.document("users/harry"); fileHandle = fileOpen(ExpandPath("./crudDump.txt"), "write"); harry.set(aUser).then( resultFromFirestore => { fileappend(fileHandle, resultFromFirestore); harry.getDocument() .then(result => { fileappend(fileHandle, serialize(result.getData(),"json")); } ).error(ex => { fileappend(fileHandle, ex.getMessage()); }) } ) .error(ex => { fileappend(fileHandle, ex.getMessage()); }) </cfscript>
Get ID
Description
Get the ID of a document.
Syntax
getID()
Returns
Returns the document Id.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docRef = db.collection("Ecom_D").document("Order2"); docData = ${ OrderID: 1002233, ItemID: 00001, Price: 499.00, Seller: "ABC" } docRef.set(docData).get() writeOutput(docRef.getDocument().get().getID()) </cfscript>
Get path
Description
Get the path of the root.
Syntax
getPath()
Returns
The path of the root.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docSchool2=${ name:"NYU", location:"NY", year:2010 } try{ getResponse=db.collection("Coll_Doc_7").document("docSchool2").getPath() } catch(any e){ writeDump(e) } </cfscript>
Get parent
Description
Get the parent document.
Syntax
getParent()
Returns
Reference of the parent document or collection.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) docSchool2=${ name:"NYU", location:"NY", year:2010 } getParentResponse=db.collection("School_Doc").document("school1").getParent().getID(); writeDump(getParentResponse) </cfscript>
Collection
Description
Create a collection.
Syntax
collection(String path)
Paramaters
- Path: The collection to be created at the specified path.
Returns
Reference to a collection.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", vendorName: "GCP", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) // create the document docData = ${ name: "Bangalore", state: "KA", country: "INDIA" } // add document to the collection res = db.collection("cities_D").runQuery().get(); // get the response writeDump(res) // get the document writeOutput(ArrayLen(res.getDocuments())) </cfscript>
Create
Description
Create a document. It fails the write if the document already exists.
Syntax
create(Struct docName)
Parameters
- docName: The name of the document to be created.
Returns
The document Id.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) docSchool2=${ name:"NYU", location:"NY", year:2010 } try{ createResponse=db.collection("Coll_Doc_2").document("doc_Doc_2").create(docSchool2).get() writeOutput("Collection created successfully") writeDump(createResponse) } catch(any e){ writeDump(e) } </cfscript>
Delete
Description
Delete a document in a collection.
Syntax
delete()
Returns
Future of timestamp, when the document is updated.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) // db.collection("School_Doc").document("school1").delete(); docSchool2=${ name:"NYU", location:"NY", year:2010 } try{ deleteResponse=db.collection("Coll_Doc_5").document("doc_Doc_5").delete() writeOutput("Document deleted successfully") writeDump(deleteResponse) } catch(any e){ writeDump(e } </cfscript>
Update
Description
Update the fields of a document.
Syntax
update(structData)
Parameters
- StructData: The new data that needs to be updated in the document.
Returns
Future of timestamp, when the document is updated.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) // db.collection("School_Doc").document("school1").update(docSchool2).get() docSchool2=${ name:"NYU", location:"NY", year:2010 } try{ updateResponse=db.collection("Coll_Doc_4").document("doc_Doc_3").update(docSchool2) writeOutput("Document updated successfully") writeDump(updateResponse) } catch(any e){ writeDump(e) } </cfscript>
orderBy(string fieldname)
Description
This method returns documents ordered by specified field name.
Parameters
- FieldName: Order the results of the query based on the specified field.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.orderBy("last_name"); results = query.runQuery().get(); </cfscript>
limit(int value)
Description
This method limits the number of documents based on the specified value.
Parameters
- Value: Limit the query results to the specified value.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.orderBy("last_name").limit(20); results = query.runQuery().get(); writeDump(results) </cfscript>
Example: Sort data in descending order
<cfscript> db = getCloudService(Application.cred, Application.conf); students=db.collection("students_p"); query=students.orderBy("first_name","descending"); results = query.runQuery().get(); writeDump(results) </cfscript>
limitToLast(int value)
Description
This method returns last n records based on the specified value.
Parameters
- Value: Set the maximum number of results to be displayed.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.orderBy("first_name").limittolast(3); results = query.runQuery().get(); writeDump(results) </cfscript>
offset(int value)
Description
This method returns the rest of the records after a specified value.
Parameters
- Value: Skips the specified value and displays the next set of results.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p") query=students.offset(5) results = query.runQuery().get() writeDump(results) </cfscript>
startAfter(array[])
Description
This method returns records after the specified value.
Parameters
- array: Display the query results after the specified array values.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) locations=db.collection("locations_p"); query=locations.orderBy("rating").orderBy("name").limit(20) results=query.startAfter([3.8,"Sarkhej Roza"]).limit(20) writeDump(results) </cfscript>
startAt(array[])
Description
This method displays the query results starting at the specified array value.
Parameters
- array: Input array.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) db = getCloudService(Application.cred, Application.conf); locations=db.collection("locations_p"); query=locations.orderBy("rating").startAt([4.1]); results=query.runQuery().get() writeDump(results) </cfscript>
endAt(array)
Description
This method displays the query results ending at the specified array value.
Parameters
- array: Input array.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) locations=db.collection("locations_p"); query=locations.orderBy("rating").endAt([4.6]); results=query.runQuery().get() writeDump(results) </cfscript>
endBefore(array[])
Description
This method displays the query results ending before the specified array value.
Parameters
- array: Display the query results before the specified array value.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; locations=db.collection("locations_p"); query=locations.orderBy("rating").endBefore([4.6]); results=query.runQuery().get() writeDump(results) </cfscript>
startAfter(DocumentSnapshot value)
Description
Returns a new Query that starts after the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameters
- value: Pass the document snapshot as a value.
Returns
A new query object with the filter applied.
For Example,
<cfscript> db = getCloudService(Application.cred, Application.conf); locations=db.collection("locations_p"); myquery=locations.orderBy("rating") results=myquery.runQuery().get(); count=results.size(); startDocument=results.getDocuments()[10]; myquery=locations.orderBy("rating").startAfter(startDocument) results=myquery.runQuery().get(); writeDump(results) </cfscript>
startAt(DocumentSnapshot value)
Description
Returns a new query that starts at the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameters
- value: Pass the document snapshot as a value.
Returns
A new query object with the filter applied.
For Example,
<cfscript> db = getCloudService(Application.cred, Application.conf); count=0; locations=db.collection("locations_p"); myquery=locations.orderBy("rating") results=myquery.runQuery().get(); startDocument=results.getDocuments()[7]; myquery=locations.orderBy("rating").startAt(startDocument) results=myquery.runQuery().get(); writeDump(results) </cfscript>
endAt(DocumentSnapshot value)
Description
Returns a new query that ends at the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameters
- value: Pass the document snapshot as a value.
Returns
A new query object with the filter applied.
For Example,
<cfscript> db = getCloudService(Application.cred, Application.conf); locations=db.collection("locations_p"); myquery=locations.orderBy("rating") results=myquery.runQuery().get(); endDocument=results.getDocuments()[results.size()-2]; myquery=locations.orderBy("rating").endAt(endDocument); results=myquery.runQuery().get(); writeDump(results) </cfscript>
endBefore(DocumentSnapshot value)
Description
Returns a new query that ends before the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameters
- value: Pass the document snapshot as a value.
Returns
A new query object with the filter applied.
For Example,
<cfscript> db = getCloudService(Application.cred, Application.conf); locations=db.collection("locations_p"); myquery=locations.orderBy("rating") results=myquery.runQuery().get(); endDocument=results.getDocuments()[15]; myquery=locations.orderBy("rating").endBefore(endDocument) results=myquery.runQuery().get(); writeDump(results) </cfscript>
A transaction is a set of read and write operations on one or more documents. For more information, see the official GCP docs.
Description
Creates a new Document at the DocumentReference's Location. It fails the write if the document already exists.
Syntax
create(DocumentReference documentReference, Struct data)
Parameters
- DocumentReference: The document to run transaction on.
- Data: The data to populate in the document.
Returns
A new buffered transaction object.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docData = ${ LOCATION: "5th Avenue", NAME: "John's", TYPE: "Thai", TOTAL: 10 } db.document("Restaurants_D/Restaurant4").create(docData).get(); returnValue = db.runTransaction(transaction => { try { restaurant4=db.document("Restaurants_D/Restaurant4"); number = transaction.getDocument(restaurant4).get().getData()["TOTAL"]; review1 = db.document("Restaurants_D/Restaurant4/Reviews/review1"); transaction.create(review1,{"rating": 5}); transaction.update(restaurant4, {"TOTAL" : number+1}) return transaction } catch (any e) { return e; } }).get() </cfscript>
Description
Creates a new Document at the DocumentReference's Location. It fails the write if the document already exists.
Syntax
create(DocumentReference documentReference, CFObject data)
Parameters
- DocumentReference: The document to run transaction on.
- Data: The object to populate in the document.
Returns
A new buffered transaction object.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) objPerson = new testFiles._Person("Jack", "Sparrow", 900); db.document("Users_D/usr1").create(objPerson).get(); db.runTransaction(transaction => { try { usr1=db.document("Users_D/usr1"); number = transaction.getDocument(usr1).get().getData()["phonenumber"]; comment1 = db.document("Users_D/usr1/Comment/comment1"); transaction.create(comment1,{"comment1": "Test Comment."}); transaction.update(usr1, {"phonenumber" : number+1}) return transaction } catch (any e) { return e; } }).get() </cfscript>
Description
Overwrites the document referred to by this DocumentReference. If no document exists yet, it will be created. If a document already exists, it will be overwritten.
Syntax
set(DocumentReference documentReference, Struct data)
Parameters
- DocumentReference: The document to run transaction on.
- Data: The data to overwrite in the document.
Returns
A new buffered transaction object.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) db = getCloudService(this.cred, this.conf); db.collection("Cities_D").document("SF"); docData = ${ Country: "USA", Population: 860000 } docRef.set(docData).get(); returnValue = db.runTransaction(transaction => { try { number = transaction.getDocument(docRef).get().getData()["Population"]; transaction.update(docRef, {"Population" : number+1}); return transaction; } catch (any e) { return e; } }).get() </cfscript>
Description
Overwrites the document referred to by this DocumentReference. If no document exists yet, it will be created. If a document already exists, it will be overwritten.
Syntax
set(DocumentReference documentReference, CFObject data)
Parameters
- DocumentReference: The document to run transaction on.
- Data: The object to overwrite in the document.
Returns
A new buffered transaction object.
For Example,
_deleteDoc.cfc
component { function deleteDoc(docRef) { collections = docRef.listCollections(); for(collection in collections) deleteCol(collection); docRef.delete().get(); } function deleteCol(colRef) { documents = colRef.listDocuments(); for(document in documents) deleteDoc(document); } }
file.cfm
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) obj=CreateObject("component","_deleteDoc"); docRef = db.collection("Cities_D").document("SF3"); docData = ${ Country: "USA", Population: 860000 } docData1 = ${ Country: "USA", Population: 900000 } if(db.document("Cities_D/SF3").getDocument().get().exists()) obj.deleteDoc(docRef); docRef.create(docData).get(); returnValue = db.runTransaction(transaction => { try { Population = transaction.getDocument(docRef).get().getData()["Population"]; transaction.set(docRef,docData1); newPopulation= Population+1; return newPopulation; } catch (any e) { return e; } }).get() </cfscript>
Description
Updates the fields of the document referred by this DocumentReference.
Syntax
update(DocumentReference documentReference, Struct fields)
Parameters
- DocumentReference: The document to run transaction on.
- fields: The fields to update in the document.
Returns
A new buffered transaction object.
For Example,
docRef = db.collection("Cities_D").document("SF10"); docData = ${ Country: "USA", Population: 860000 } docData1 = ${ Country: "USA", Population: 900000 } docRef.create(docData).get(); db.runTransaction(trans => { try { Population = trans.getDocument(docRef).get().getData()["Population"]; trans.update(docRef,docData1); return trans; } catch (any e) { return e; } }).get()
Description
Deletes the document referred with updated time as pre-condition.
Syntax
delete(DocumentReference documentReference)
Parameters
- DocumentReference: The document to run the transaction on.
Returns
A new buffered transaction object.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docData = ${ Country: "USA", Population: 860000 } docRef.set(docData).get(); db.runTransaction(transaction => { try { Population = transaction.getDocument(docRef).get().getData()["Population"]; newPopulation= Population+1; if(Population <= 860000) { transaction.update(docRef, {"Population" : newPopulation}); transaction.delete(docRef); return "Document deleted successfully inside Transaction !!"; } else return "Sorry! Population is too big."; } catch (any e) { return e; } }).get() </cfscript>
Description
Returns the result set from the provided query. Holds a pessimistic lock on all returned documents.
Syntax
runQuery(Query query)
Parameters
- Query: The query to get the results from.
Returns
A future of query snapshot which contains the results of a query.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docRef = db.collection("Cities_D").document("SF8"); docData = ${ Country: "USA", Population: 860000, count: 8 } docRef.set(docData).get(); cities=db.collection("Cities_D"); query=cities.whereEqualTo("count",8); db.runTransaction(transaction => { try { number = transaction.runQuery(query).get().getDocuments()[1].getData()["Population"]; transaction.update(docRef, {"Population" : number+1}); return transaction; } catch (any e) { return e; } }).get() </cfscript>
Syntax
hasTransactionId()
Returns
True if there exists a valid Transaction Id.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docRef = db.collection("Cities_D").document("SF"); docData = ${ Country: "USA", Population: 860000 } docData1 = ${ Country: "USA", Population: 900000, count: 1 } docRef.set(docData).get(); returnValue = db.runTransaction(transaction => { try { Population = transaction.getDocument(docRef).get().getData()["Population"]; transaction.set(docRef,docData1); newPopulation= Population+1; transaction.update(docRef, {"Population" : newPopulation}); return transaction; } catch (any e) { return e; } }).get(); writeOutput("HasTransactionID " & returnValue.hasTransactionId()) </cfscript>
Gets the number of writes which include update, set, create and delete api's of the particular transaction.
Syntax
getMutationSize()
Returns
Buffered writes of a transaction.
For Example,
<cfscript> cred = { projectId : "my-project-id", vendorName: "GCP", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName: "firestore" }; db=getCloudService(cred, conf) docRef = db.collection("Cities_D").document("SF"); docData = ${ Country: "USA", Population: 860000 } docData1 = ${ Country: "USA", Population: 900000, count: 1 } docRef.set(docData).get(); returnValue = db.runTransaction(transaction => { try { Population = transaction.getDocument(docRef).get().getData()["Population"]; transaction.set(docRef,docData1); newPopulation= Population+1; transaction.update(docRef, {"Population" : newPopulation}); return transaction; } catch (any e) { return e; } }).get(); writeOutput("MutationSize is " & returnValue.getMutationSize()) </cfscript>
Asynchronous transaction
The add, set, update, and delete methods return a Future object as a return value, which means that you can make use of ColdFusion's Future abilities. The example below illustrates a different way through which you can process the call via chaining. As chaining uses worker threads, the results from these use separate buffers from the main thread and writing them to a file.
For Example,
<cfscript> aUser = ${ firstName: "Harry", lastName: "Potter", age: 14, address: "Hogwarts" } harry = db.document("users/harry"); fileHandle = fileOpen(ExpandPath("./crudDump.txt"), "write"); harry.set(aUser).then( resultFromFirestore => { fileappend(fileHandle, resultFromFirestore); harry.getDocument() .then(result => { fileappend(fileHandle, serialize(result.getData(),"json")); } ).error(ex => { fileappend(fileHandle, ex.getMessage()); }) } ) .error(ex => { fileappend(fileHandle, ex.getMessage()); }) </cfscript>
Add snapshot listener- document
Description
Using this method, you can listen to events to which this method is applied. On a successful event hit, the onSuccess method executes, else onFailure executes. The event gets triggered on writes to the document.
Syntax
addSnapshotListener(UDFMethod onSuccess, UDFMethod onFailure)
Returns
An object to remove the connection.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; pubSubClient=getCloudService(cred,conf) docFuture = db.collection("stock_p").document("doc"); path=ExpandPath("./documentSnapshot.txt") onSuccess = results => { fileAppend(path, serialize(results,"json")); } onFailure = exception => { fileAppend(path, exception.getMessage()); } docFuture.addSnapshotListener(onSuccess, onFailure) </cfscript>
Add snapshot listener- query
Description
The query starts listening to the query on which this method is applied on. On successful event hit, the onSuccess method executes, else onFailure executes. The event gets triggered on writes to the query.
Syntax
addSnapshotListener(UDFMethod onSuccess, UDFMethod onFailure)
Returns
An object to remove the connection.
For Example,
<cfscript> cred = { projectId : "my-project-id", credentialJsonFilePath : "Path-creds-file.json" }; conf = { serviceName : "firestore" }; pubSubClient=getCloudService(cred,conf) stocks = db.collection("stock_p") path=ExpandPath("./documentSnapshot.txt") onSuccess = result => { fileAppend(path, serialize(result.documentChanges,"json")); } onFailure = exception => { fileAppend(path, exception.getMessage()); } stocks.addSnapshotListener(onSuccess, onFailure) </cfscript>
DocumentReference is the interface returned by the document() method.
These are the supported operations:
- Create
- create(DocumentReference documentReference, Struct data)
- create(DocumentReference documentReference, CFObject data)
- Set
- set(DocumentReference documentReference, Struct data)
- set(DocumentReference documentReference, Struct data, Boolean merge)
- set(DocumentReference documentReference, CFObject data)
- set(DocumentReference documentReference, CFObject data, Boolean merge)
- set(DocumentReference documentReference, Struct data)
- Update
- update(DocumentReference documentReference, Struct fields)
- update(DocumentReference documentReference, Struct fields)
- Delete
- delete(DocumentReference documentReference)
- delete(DocumentReference documentReference)
- getMutationSize()
- commit()
Batch
Description
Commit multiple writes at once. Instead of making multiple write calls to the server, you can buffer them using batch and commit them at once.
Syntax
batch()
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) batch = db.batch(); docData1 = ${ Country: "USA", Population: 10 } docData2 = ${ Country: "India", Population: 200 } docData3 = ${ Country: "India", Population: 400 } docRef1 = db.collection("BW_S").document("BW1"); docRef2 = db.collection("BW_S").document("BW2"); batch.set(docRef1, docData1); batch.set(docRef2, docData2); batch.update(docRef2, docData3); batch.commit().get(); </cfscript>
Querying functions and filtering functions
Description
This method filters documents where the field name is equal to the specified value.
Parameters
- FieldName: The key to query in the document.
- Value: The value to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereEqualTo("age",16); results = query.runQuery().get(); documents=results.getdocuments() for(i=1;i<=results.size();i++){ writeDump(documents[i].getdata()) } </cfscript>
Description
This method returns documents where the field name is not equal to the specified value.
Parameters
- FieldName: The key to query in the document.
- Value: The value to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) reviews=db.collectionGroup("reviews"); query=reviews.whereNotEqualTo("author","ravi"); results = query.runQuery().get() documents=results.getdocuments() for(i=1;i<=results.size();i++){ writeDump(documents[i].getdata()) } </cfscript>
Description
This method returns documents where the field name is greater than or equal to the specified value.
Parameters
- FieldName: The key to query in the document.
- Value: The value to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) reviews=db.collection("restaurants_p/6gaKC7syRE1qUGOD0cZZ/reviews"); query=reviews.whereGreaterThanOrEqualTo("rating",4).select(["author"]); results = query.runQuery().get() writeDump(results) </cfscript>
Description
This method returns documents where the field name is less than or equal to the specified value.
Parameters
- FieldName: The key to query in the document.
- Value: The value to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereLessThanOrEqualTo("age",15); results = query.runQuery().get() writeDump(results) </cfscript>
Description
This method returns documents where the field name is greater than the specified value.
Parameters
- FieldName: The key to query in the document.
- Value: The value to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereGreaterThan("age",16).orderBy("age"); results = query.runQuery().get(); writeDump(results) </cfscript>
Description
This method returns documents where the field name is less than the specified value.
Parameters
- FieldName: The key to query in the document.
- Value: The value to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereLessThanOrEqualTo("age",15); results = query.runQuery().get() writeDump(results) </cfscript>
Description
This method filters documents based on the specified array values.
Parameters
- FieldName: The key to query in the document.
- Array: The array to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereArrayContains("marks",70); results = query.runQuery().get(); writeDump(results) </cfscript>
Description
This method filters documents based on the values in the specified array.
Parameters
- FieldName: The key to query in the document.
- Array: The array to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereIn("age",[16,17,25,7]); results = query.runQuery().get(); writeDump(results) </cfscript>
Description
This method filters documents based on the values that are not present in the specified array.
Parameters
- FieldName: The key to query in the document.
- Array: The array to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereNotIn("age",[16,17,25,7]); results = query.runQuery().get() writeDump(results) </cfscript>
Description
This method filters documents based on the presence of any value in the specified array.
Parameters
- FieldName: The key to query in the document.
- Array: The array to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereArrayContainsAny("marks",[71.0,15,0,65.5]); results = query.runQuery().get() writeDump(results) </cfscript>
Description
This method selects documents based on the values of the specified fields names as an array.
Parameters
- array: The array to query in the document.
Returns
A new query object with the filter applied.
For Example,
<cfscript> cred = { projectId : "my-gcp-project", credentialJsonFilePath : "File-path-cred.json" }; conf = { serviceName : "firestore" }; db=getCloudService(cred,conf) students=db.collection("students_p"); query=students.whereEqualTo("age",16).select(["first_name","age"]); results = query.runQuery().get() writeDump(results) </cfscript>