Firestore search array contains for multiple values

前端 未结 5 1077
北海茫月
北海茫月 2020-11-30 04:52

If I have a simple collection such as:

Fruits:
  Banana:
   title: \"Banana\"
   vitamins: [\"potassium\",\"B6\",\"C\"]
  Apple:
   title: \"Apple\"
   vitam         


        
5条回答
  •  天命终不由人
    2020-11-30 05:22

    It has been commented upon, but the accepted answer isn't feasible if your query requires you to create a composite index, because it'll likely lead to your count of composite indexes quickly reaching the limit of 200. It's hacky, but the best solution I can think of is to store - in some kind of guaranteed order, e.g. alphabetically - an array of every combination of vitamin for a given fruit, each combination being concatenated as a string. For example, as bananas contain B6, C, and potassium, an array of vitamin combinations for bananas would be:

    • B6
    • B6||C
    • B6||C||potassium
    • B6||potassium
    • C
    • C||potassium
    • potassium

    Then, if your user was searching for every fruit that contains BOTH B6 AND potassium, your query would be:

    db.collection("Fruits").where("vitamins", "array-contains", "B6||potassium")
    

提交回复
热议问题