whereArrayContains limit to 10

2020-05-03 11:12发布

问题:

I want to filter questionCollection on basis of tagIDs . Everything working fine but whereArraycontains is working for max 10 id's.

How could I improve my structure to work for more than 10 tagIDs and also make sure to call as less as hit to server to reduce money spend.

Firestore-root
   |
   --- questions (collection)
   |     |
   |     --- qid (documents)
   |          |
   |          --- title: "Question Title"
   |          |
   |          --- qid: "autogeneratedID"
   |          |
   |          --- tagIDs =[tagID_1,tagID_2...tag_IDs_5] // array
   |
   --- tags (collection)
   |     |
   |     --- tagID (documents)
   |          |
   |          --- tagName: "Mathematics"
   |          |
   |          --- tagID: "autogeneratedID"
   |

fetch questions that contains specific tagIDs ( fails if tagIDs greater than 10)

private fun fetchQuestion(tagMap: HashMap<String, String>) {

        val tagIDList:MutableList<String> = ArrayList();
        for ((key) in tagMap) { 
            tagIDList.add(key);
        }
        var query: Query = db.collection(Constants.QUESTION_COLLECTION)
                .orderBy(Constants.KEY_QUESTION_ID, Query.Direction.DESCENDING).limit(50)
        if(!tagIDList.isNullOrEmpty())
            query = query.whereArrayContainsAny("tagIDs", tagIDList);//if list greater than 10 it's not working

        query.get().addOnSuccessListener { queryDocumentSnapshots ->
                if(!queryDocumentSnapshots.isEmpty){
                    for (documentSnapshot in queryDocumentSnapshots) {
                        val question = documentSnapshot.toObject(QuestionBO::class.java)
                    }
                }
            }.addOnFailureListener { e ->
                toast("No record found.")
                e.printStackTrace()
            }
    }

回答1:

The documentation for whereArrayContains queries is very specific. It can only work with 10 array items:

use the array-contains-any operator to combine up to 10 array-contains clauses on the same field with a logical OR

You should know that whereArrayContains does not reduce the number of billed document reads. If your array contains 10 items, it will still cost 10 document reads. If you perform 10 whereArrayContains queries, each with 10 array items, it will still cost 100 reads.

If you need N documents, there is no shortcut to make those N document reads cost less than the cost of N document reads.