Cloud Firestore - Composite query

Asked

Viewed 1,101 times

2

I’m making a query in my database in the firestore, but when I put two where nested, I get the following error:

Error getting documents Error: Firestore: Operation was rejected because the system is not in a state required for the operation`s execution. (firestore/failed-precondition).

When I consult with only one of the Where, the query works.

Code:

firebase
  .firestore()
  .collection('users')
  .doc(userId)
  .collection('cars')
  .where('available', '==', true)
  .where('createdAt', '<=', new Date(moment().format('MMMM DD, YYYY')))
  .get()
  .then((snapshot) => {
      const cars = [];
      snapshot.forEach((doc) => {
        cars.push(Object.assign({}, { id: doc.id }, doc.data()));
      });
      this.setState({ cars, loading: false });
  })
  .catch((err) => {
      console.log('Error getting documents', err);
      this.setState({ loading: false });
  });

2 answers

2


Seems related to this issue (and several others by the way).

That one answer in one of the related issues leads me to believe that the problem has to do with this excerpt in the firestore documentation, in the Indexes Compostos:

Cloud Firestore uses composite indexes to support composite queries that do not yet accept single field indexes. For example, you would need a composite index for the following queries:

citiesRef.where("country", "==", "USA").orderBy("population", "asc")
citiesRef.where("country", "==", "USA").where("population", "<", 3800000)
citiesRef.where("country", "==", "USA").where("population", ">", 690000)

For such consultations, for example, a composite index of country and population.

In your case, this index would have to be in available and createdAt.

1

Good afternoon,

Try the following, go to the firebase console, go to the firestore in the index tab and create a new composite Intel:

Collection: with the fields: available Ascending and createAt Ascending

i ran the following code successfully after creating the indices:

getCars(userId) {
    const now = new Date();
    this.db.firestore
      .collection('users')
      .doc(userId)
      .collection('cars')
      .where('available', '==', true)
      .where('createAt', '<=', now)
      .get()
      .then( res => {
        console.log(res.docs);
      });
  }
  • Why a composite index should be created?

  • Firestore requires the creation of compound indices when different fields are used, if it was a range in the createAt field with <= and then >= does not need, but if you try to use 2 different fields in Where as this case 'available' and 'createAr' you need to create the Indice right on the console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.