Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection.
Still the firebase documentation about querying firestore by REST API lacks examples and the details are not obvious. Therefor I like to share this guidline with you.
Use a http-request flow function
Set the url in the formula to: "https://firestore.googleapis.com/v1/projects/YOUR_PROJECT/databases/(default)/documents/COLLECTION_WHERE_APPLICABLE/DOCUMENT_WHERE_APPLICABLE + “:runQuery”
Set the HTTP method to POST
if your security rules in firestore require authentication, set the header e.g.:
the main part for the query goes into the body:
You can visualize the above body e.g. with https://jsoneditoronline.org/ . With example content it looks like this:
Remarks regarding “orderBy”:
- this is only required, if you need to download the data in a specific order or need to use “startAt” like below.
- to make it work, there needs to be a related ‘composite index’ in firestore. You can either create the composite index in the firebase manually
or just click the link from the error-response to create it automatically.
Remarks regarding “startAt” and “limit”:
- this is only required, if you need to use pagination to limit the number of documents returned.
- I recommend to do tests with your app and determine, how much data it can handle. The responsiveness will depend on your logic and the components, you are connecting to this data e.g. in a “repeat with”-table. From my experience: when the data is connected to checkboxes and in “repeat with”-rows, the user experience turns ugly with more than 25 documents.
- in order to define the document correctly where to resume on the next page (referred to as ‘cursor’): the values of the “KEY_YOU_WANT_TO_ORDER_BY” need to be unique. While it should be possible to define the cursor by its ID, the syntax for REST API isn’t available at the time of writing this guideline. (in the future there might be information about this on stackoverflow).
in case that you need more complex queries, you can adapt the body according to the structuredQuery-documentation.
check if the returned collection does not contain any documents. E.g. by
using the formula
FIRST_ITEM( KEYS(FIRST_ITEM(outputs["HTTP request "].resBodyParsed))) == "readTime"
use the output of the ‘HTTP request’ to set a data variable
using the formula
MAP(outputs["HTTP request"].resBodyParsed, item.document)
Best practice for the use of this community guide:
- experiment with your code on postman.com, to learn about the details and how to adapt it to your app.
- only reply to this community guide to improve its content.
- for any questions, please start a new thread in the forum.