Search code examples
firebasegoogle-cloud-firestorefirebase-cli

What is the JSON format for a firestore individual field index within a collection group query?


We can now retrieve documents from a collection group which is great. To do so, I need to create an index through an error message on the Firebase console. How can I add this new index to the firestore.indexes.json file?

Example of the documentation:

let museums = db.collectionGroup('landmarks').where('type', '==', 'museum');
museums.get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
    console.log(doc.id, ' => ', doc.data());
  });
});

Solution

  • At the top level of your index file, add a new element called fieldOverrides and populate it like this:

    {
      "fieldOverrides": [
        {
          "collectionGroup": "landmarks",
          "fieldPath": "type",
          "indexes": [
            {
              "order": "ASCENDING",
              "queryScope": "COLLECTION"
            },
            {
              "order": "DESCENDING",
              "queryScope": "COLLECTION"
            },
            {
              "arrayConfig": "CONTAINS",
              "queryScope": "COLLECTION"
            },
            {
              "order": "ASCENDING",
              "queryScope": "COLLECTION_GROUP"
            }
          ]
        }
      ]
    }
    

    This preserves the all the default automatic indexing for the type field in landmarks at the COLLECTION scope, and allows for type also to be used at the COLLECTION_GROUP scope.