如何在Android中使用复合查询从“ Firestore”获取文档

时间:2019-02-15 10:40:12

标签: android firebase indexing google-cloud-firestore

我已经为我在应用程序中的所有下拉微调器构建了一个像这样的firebase查询。

实际上,我的Android应用程序中有20多个微调器,可以根据所选的任何下拉列表从Firebase Firestore集合中搜索用户。目前,我通过使用if条件来处理所有可能的情况,并根据任何选定的微调器进行复合查询。但这不是我当前正在使用的好方法。我需要在任何查询旁边附加查询,但不进行任何微调检查。.她是我的代码。

Query query;
CollectionReference collection = 
firestore.collection(Constants.MEMBERS);
query  = collection;

if (rangeBarRating.getRightIndex() != 0 && spinnerReligion.getSelectedItemPosition() != 0){
        query =  collection.whereEqualTo(Constants.RELIGION,spinnerReligion.getSelectedItem()).whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
    } else if (spinnerCountry.getSelectedItemPosition() != 0){
        query =  collection.whereEqualTo(Constants.COUNTRY_LIVING_IN,spinnerCountry.getSelectedItem());
    }else if (rangeBarRating.getRightIndex() != 0){
        query =  collection.whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
    }else if ((rangeBarAge.getLeftIndex()+18) > 18){
        query =  collection.whereGreaterThanOrEqualTo(Constants.AGE,(rangeBarAge.getLeftIndex()+18));
    }

我需要动态的方法,就像我只使用if语句而不使用if else一样。如果选择了一些微调器,则将该微调器值附加到我的查询中并获得所需的结果。

1 个答案:

答案 0 :(得分:1)

在分配条件查询的方式上有一个小错误。您希望将每个条件添加到现有查询中,但实际上是不断从集合中重建新查询。要解决此问题,请在每次添加条件时从query进行构建:

firestore.collection(Constants.MEMBERS);
query = collection;

if (rangeBarRating.getRightIndex() != 0 && spinnerReligion.getSelectedItemPosition() != 0){
    query =  query.whereEqualTo(Constants.RELIGION,spinnerReligion.getSelectedItem()).whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
} else if (spinnerCountry.getSelectedItemPosition() != 0){
    query =  query.whereEqualTo(Constants.COUNTRY_LIVING_IN,spinnerCountry.getSelectedItem());
}else if (rangeBarRating.getRightIndex() != 0){
    query =  query.whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
}else if ((rangeBarAge.getLeftIndex()+18) > 18){
    query =  query.whereGreaterThanOrEqualTo(Constants.AGE,(rangeBarAge.getLeftIndex()+18));
}