Managing indexes in Firebase Firestore

时间:2019-03-19 15:06:20

标签: swift firebase google-cloud-firestore

I am trying to have custom order to String collection elements in I fetch from Firebase FireStore.

I am quite confused with the documentation with custom indexes and composite indexes. I have several categories lets say Restaurants, Exits, Shops and I simply want them to be ordered the same way in when I fetch them. I want to receive Exits then Restaurants then Shops.

In the admin panel, they are not ordered properly and I would like to reorder them. The client code that fetches data is swift code.

1 个答案:

答案 0 :(得分:2)

Firestore会自动为文档(read more)上的所有字段创建单字段索引。这意味着简单的查询将立即可用。

因此,这样的查询应为您提供所需的结果:按类别按字母顺序排序的任何地方。之所以可行,是因为您仅查询一个字段。

placesCollectionRef.order(by: "category", descending: false)

但是通常您想匹配一个字段,并排序另一个字段。在这种情况下,您将需要一个复合索引。

placesCollectionRef
  .whereField("state", isEqualTo: "CA")
  .order(by: "category", descending: false)

Firebase在确定何时需要索引方面非常有用。如果您对应用程序进行测试运行,如果有任何查询缺少必要的索引,则Firebase会引发错误。 The error message will contain a URL that links to your Firebase project console并打开一个用于创建索引的对话框。