I’m currently facing an issue with a Firestore query that requires a composite index, but I’m running into some limitations. Here’s the problem:
The Query: I’m trying to fetch questions from Firestore using the following query:
const questionsQuery = query( questionsRef, where("isVerified", "==", true), where("difficulty", "==", difficultyNumber), where("subCategory.en", "in", selectedChips), where("random", "<=", randomThreshold) );
The Error: When I run this query, I get an error stating that an index is required. I created a composite index with the following fields:
isVerified (Ascending)
difficulty (Ascending)
subCategory.en (Ascending)
random (Ascending)
However, the query only works if I comment out the random condition. It seems that Firestore has limitations on combining the in operator with inequality filters.
What I’ve Tried:
Reordering the query by moving the in condition to the end.
Simplifying the query by removing other conditions.
Splitting the query into two separate steps to fetch data and filter random values in memory.
Using orderBy with endAt for the random field.
Despite these efforts, I’m still encountering issues.
Now, when I successfully run the query without the random condition, I get an array of documents. What I want to achieve is to fetch a random document from the results.
Does anyone have insights or methods to get a random document from an array of fetched documents?
Firestore query successfully without encountering an index error. Specifically, I hoped to fetch a set of questions that meet the specified criteria and ultimately retrieve a random document from that set of results.