How to effectively refine a group query in Firestore to obtain specific results

My database structure is set up like this (simplified version):

Collection: item_A
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders_item_A
            -> Document: order_AA = {type: "A1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "A2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders_item_A
            -> Document: order_AC = {type: "A1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "A1", address: {pincode: "333333", city:"Paris"}
            ...

I am currently using a collection group query to fetch all orders under "item_A" (across all users). This is how I achieve this:

let orders = [];
await firestore()
    .collectionGroup("orders_item_A")
    .get()
    .then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            console.log(doc.id, ' => ', doc.data());
            orders.push(doc.data());
        });
    })

Now, I want to narrow down the above query to filter for orders from specific cities (e.g. Paris). I attempted to add a 'where' clause in this manner:

let orders = [];
await firestore()
    .collectionGroup("orders_item_A")
    .where("address.city", "==", "Paris")
    .get()
    .then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            console.log(doc.id, ' => ', doc.data());
            orders.push(doc.data());
        });
    })

However, this approach failed and I received the following error message:

Error: [Error: [firestore/failed-precondition] Operation was rejected because the system is not in a state required for the operation's execution. Ensure your query has been indexed via the Firebase console.]

I have already created a composite index in my FireStore database with the following specifications:

Collection ID = orders_item_A

Fields indexed = address.city Ascending type Ascending

Status = Enabled

I am uncertain about what I might be doing incorrectly. I considered if the issue lies with using an object property within the 'where' clause (which should not be the problem). Therefore, I also experimented with a simpler query like this:

.where("type", "==", "A1")

Nevertheless, this attempt also failed. Where am I going wrong?

Answer №1

I came across the solution to my issue. It turns out my mistake was creating a "Composite" index instead of a "Single field" index, which I mentioned in my initial question when selecting the "Indexes" option. Here is what I should have done:

https://i.sstatic.net/ovS7t.png

Upon removing the existing composite index, I created a new "single field" index with the following details:

https://i.sstatic.net/gwYX6.png

Proceed to click 'Next' and on the subsequent screen, be sure to "enable" one of the options under 'Collection group scope' (I opted for Ascending):

https://i.sstatic.net/nz0ja.png

Following these steps is crucial for the query to function correctly. After making these adjustments, everything fell into place, specifically with the original code snippet I had composed:

let orders = [];
await firestore()
    .collectionGroup("orders_item_A")
    .where("address.city", "==", "Paris")
    .get()
    .then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            console.log(doc.id, ' => ', doc.data());
            orders.push(doc.data());
        });
    })

Important reminder: If you delete a specific "index," it may take some time (potentially up to 10 minutes in certain instances) for the changes to take effect. During this period, you may encounter errors if attempting to create a new index for the same entry. It is advisable to wait and try again after some time has passed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to effectively utilize wrapAsync in MeteorJS when working with callbacks in the vzaar API?

Issue to Resolve: My current challenge involves retrieving an uploaded video ID asynchronously from an API in order to incorporate it into my code once the video upload process is completed. Unfortunately, I am encountering issues where the returned value ...

Retrieve the chosen item to automatically fill in the input fields using Ionic 2 and Angular

My goal is to create a dropdown menu populated with a list of items, and when a product is selected, its price should automatically appear in the quantity field. <ion-item> <ion-label>Item</ion-label> <ion-select (ionChange)="getP ...

"Enhance your listening experience with an audio player featuring album covers as captivating

Is there a way to create an audio player with the album cover image serving as the background, while ensuring all control buttons are displayed on top of that same image? I attempted using the following code snippet: <audio controls = 'controls&ap ...

Steps to implement an image zoom function triggered by a button click

I'm working on a school project that requires me to use only html, css, and javascript for creating a website. Currently, I'm designing a landing page with a button that will navigate the user to another page. My goal is to have the background im ...

Incorporate a map (using leafletjs or Google Maps) as a subtle backdrop

I am currently working on a one-page website and I would like to include a map as a background behind the "contact" section. The map can be set to float, draggable, or positioned at the back. I have experience using both the Google Maps API and LeafletJS, ...

Toggle the visibility of multiple divs by clicking on other divs

I have implemented a script on my webpage to toggle the visibility of certain divs by clicking on anchor tags. I found a solution that seems perfect for my needs, but unfortunately it is not working when I try to integrate it into my own website. I suspec ...

What techniques can I utilize to ensure Azure function generates JSON specifically for web browsers?

I have a functioning Azure function with the following code: module.exports = function(context, req) { // this is the complete source code, believe it or not context.done(null, {favoriteNumber: 3}); }; When I utilize a tool like Postman to access ...

Executing multiple setTimeout calls simultaneously can result in greater delays than anticipated

During my exploration of Node performance, I encountered an unexpected issue where an example involving 50 concurrent calls to setTimeout took over 4 seconds instead of the anticipated 500ms. The scenario involves a basic express server that waits for all ...

What is the process of creating a model instance in a Nodejs controller?

Trying to work with the model object in Node using the sequelize module. It looks something like this: File structure: models index.js user.js controllers userController.js routes route.js ========================== models/users.js //created us ...

Creating a specialized .toString() function for an array

When trying to create a custom .toString() method on the Array prototype, how can you access the actual array that the method is called on? This approach seems to work: Array.prototype.toString = () => 'custom'; "" + [1,2,3]; // 'custom ...

Error ER_NO_REFERENCED_ROW_2 occurred while attempting to use the function LAST_INSERT_ID

As a newcomer to Vue.js and Express, I've been trying to figure out how to transfer the GuestID from the Guest Table to the foreign key GuestID in my reservations table. app.post('/create',(req,res,next)=>{ var mysql = require(' ...

Is there a way to manipulate a DOM element using a component?

import { FlagIcon, ChartIcon, ShareIcon, ConnectIcon, HearIcon, AnalyticsIcon, AddIcon, RemoveIcon, } from "../../icons/Icons"; import "./Sidebar.scss"; import ReactDOM from "react-dom"; const Sidebar = () =&g ...

How can you showcase the content of an object within an array?

I am currently working on a project component that involves retrieving and logging data. However, I am facing an issue with accessing objects within my array of clients to display them properly in my table. Here is the script I am using: <script> ex ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

Issues with implementing Firebase web push notifications using NodeJS and troubleshooting them

I'm in the process of developing an application that sends web push notifications through Firebase and a NodeJs server, but I keep encountering a 'mismatched-credential' error. How can I resolve this issue? Initially, I am creating a JSON f ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Disable automatic browser scroll reset on inline onclick event

Currently, I am utilizing prototype to create an ajax request through an inline onclick on a link. The function is designed to display an element on the page and everything functions properly. However, there is an issue where the browser scroll bar reset ...

Utilizing HTTPS for OpenWeatherMap API in JavaScript encounters obstruction

I'm currently working on a project with free code camp where I am attempting to create a weather app using the OpenWeatherMap API. However, I have encountered an issue. My project needs to be submitted on Codepen and use HTTPS for geolocation. Due to ...