Firestore query with multiple filters

Using Dart/Flutter and the package firebase_storage: ^11.7.7, I am building the method getQuestions that receives the following parameters below. I need to search for questions in the database using these filters that can be null, considering that they are lists coming from multiple selects and firestore does not accept multiple where in, what is the best solution for this problem, since the limit in a first search can harm the filtering if done locally and if the limit parameter is removed the search can be very costly because there are millions of questions records in the database?

String? creatorUserId;
String? type;
bool? isAnnulled;
String? statement;
List<String>? examCompanyIds;
List<String>? institutionIds;
List<String>? disciplineIds;
List<String>? topicIds;
List<String>? positionIds;
List<String>? educationFieldIds;
List<String>? regionIds;
List<String>? areaIds;
List<String>? scholarityIds;
List<String>? difficultyIds;
List<String>? yearIds;
DateTime? createdAtStart;
DateTime? createdAtEnd;
int limit;

I’ve tried what’s below and it didn’t work. I’m not a NoSQL expert, I would actually like to know from you what the best solution is.

Note: The questions collection data is denormalized.

Future<List<QuestionModel>> getQuestions({
    required GetQuestionsParams params,
  }) async {
    try {
      // Authorize the user with Firebase Authentication.
      await DataSourceUtils.authorizeUser(_auth);

      final querySnapshots = <QuerySnapshot>[];

      // Base query
      Query query = _firestore.collection('questions');

      // Adds common filters
      if (params.creatorUserId != null) {
        query = query.where('creatorUserId', isEqualTo: params.creatorUserId);
      }
      if (params.type != null) {
        query = query.where('type', isEqualTo: params.type);
      }
      if (params.isAnnulled != null) {
        query = query.where('isAnnulled', isEqualTo: params.isAnnulled);
      }
      if (params.statement != null && params.statement!.isNotEmpty) {
        query = query
            .where('statementText', isGreaterThanOrEqualTo: params.statement)
            .where(
              'statementText',
              isLessThanOrEqualTo: '${params.statement}uf8ff',
            );
      }
      if (params.createdAtStart != null) {
        query = query.where(
          'createdAt',
          isGreaterThanOrEqualTo: Timestamp.fromDate(params.createdAtStart!),
        );
      }
      if (params.createdAtEnd != null) {
        query = query.where(
          'createdAt',
          isLessThanOrEqualTo: Timestamp.fromDate(params.createdAtEnd!),
        );
      }

      // Helper function to apply `whereIn` to the first parameter with list
      // greater than 1
      var appliedWhereIn = false;
      void applyWhereIn(List<String>? ids, String fieldName) {
        if (!appliedWhereIn && ids != null && ids.length > 1) {
          query = query.where(fieldName, whereIn: ids);
          appliedWhereIn = true;
        }
      }

      // Apply `whereIn` to relevant parameters
      applyWhereIn(params.yearIds, 'year.uid');
      applyWhereIn(params.positionIds, 'position.uid');
      applyWhereIn(params.institutionIds, 'institution.uid');
      applyWhereIn(params.examCompanyIds, 'examCompany.uid');
      applyWhereIn(params.topicIds, 'topic.uid');
      applyWhereIn(params.disciplineIds, 'discipline.uid');
      applyWhereIn(params.educationFieldIds, 'educationField.uid');
      applyWhereIn(params.areaIds, 'area.uid');
      applyWhereIn(params.regionIds, 'region.uid');
      applyWhereIn(params.scholarityIds, 'scholarity.uid');
      applyWhereIn(params.difficultyIds, 'difficulty.uid');

      // Executes the base query
      querySnapshots.add(await query.get());

      // Filter results with `whereIn` manually
      List<DocumentSnapshot> filteredDocs =
          querySnapshots.expand((qs) => qs.docs).toList();

      // Helper function to apply filter manually
      void applyManualFilter(List<String>? ids, String fieldName) {
        if (ids != null && ids.length > 1 && !appliedWhereIn) {
          filteredDocs = filteredDocs.where((doc) {
            return ids.contains((doc[fieldName] as DataMap)['uid']);
          }).toList();
        } else if (ids != null && ids.length == 1) {
          query = query.where('$fieldName.uid', isEqualTo: ids.first);
        }
      }

      // Apply manual or `where` filters depending on the case
      applyManualFilter(params.yearIds, 'year');
      applyManualFilter(params.positionIds, 'position');
      applyManualFilter(params.institutionIds, 'institution');
      applyManualFilter(params.examCompanyIds, 'examCompany');
      applyManualFilter(params.topicIds, 'topic');
      applyManualFilter(params.disciplineIds, 'discipline');
      applyManualFilter(params.educationFieldIds, 'educationField');
      applyManualFilter(params.regionIds, 'region');
      applyManualFilter(params.areaIds, 'area');
      applyManualFilter(params.scholarityIds, 'scholarity');
      applyManualFilter(params.difficultyIds, 'difficulty');

      // Applies the final limit to manually filtered documents
      filteredDocs = filteredDocs.take(params.limit).toList();

      // Converts filtered documents into QuestionModel
      return filteredDocs
          .map((doc) => QuestionModel.fromMap(doc.data()! as DataMap))
          .toList();
    } catch (exception) {
      final serverException = ExceptionHandler.handleException(
        exception,
        'QuestionRemoteDataSrcImp | getQuestions',
      );

      throw serverException;
    }
  }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật