Home > Software engineering >  Firebase Query using array-contains and a range filter JavaScript
Firebase Query using array-contains and a range filter JavaScript

Time:09-01

I am trying to query documents that have a specific genre and user rating.

In the document, genres is an array[] and userRating is a number out of 5.

Here's my query:

q = query(
            ColRef,
            where("genres", "array-contains", "Comedy"),
            where("userRating", ">=", 3)   
          );

I get this error when it's run

FirebaseError: [code=failed-precondition]

Firebase Documentation says

You can perform range (<, <=, >, >=) or not equals (!=) comparisons only on a single field, and you can include at most one array-contains or array-contains-any clause in a compound query:

Am using one array-contains and one not equals or am I not understanding what they meant is array-contains also considered a range filter?

CodePudding user response:

As mentioned earlier, you need a composite index to support this query:

[genres - Arrays, userRating - Ascending]

By default, the query will order results in ascending order based on value of userRating. But your index mode was Descending for userRating and hence the first index did not work.

That index would have supported your query if you had specified orderBy('userRating', 'desc') which orders the results in descending order.

You can read more about this in the documentation.

  • Related