Unnest

Descrição

Gera um novo documento para cada elemento em uma matriz.

Os novos documentos contêm todos os campos da entrada, além de um elemento diferente da matriz. O elemento da matriz é armazenado no alias fornecido, podendo substituir qualquer valor preexistente com o mesmo nome de campo.

Opcionalmente, o argumento index_field pode ser especificado. Quando presente, ele inclui o índice baseado em zero do elemento da matriz de origem nos documentos de saída.

Essa etapa se comporta de maneira semelhante a CROSS JOIN UNNEST(...) em muitos sistemas SQL.

Sintaxe

Node.js

const userScore = await db.pipeline()
    .collection("/users")
    .unnest(field('scores').as('userScore'), /* index_field= */ 'attempt')
    .execute();

Comportamento

Alias e campo de índice

Os campos alias e index_field (opcional) vão substituir os campos originais se eles já existirem no documento de entrada. Se o index_field não for fornecido, os documentos de saída não vão conter esse campo.

Por exemplo, para a seguinte coleção:

Node.js

await db.collection('users').add({name: "foo", scores: [5, 4], userScore: 0});
await db.collection('users').add({name: "bar", scores: [1, 3], attempt: 5});

A etapa unnest pode ser usada para extrair cada pontuação individual por usuário.

Node.js

const userScore = await db.pipeline()
    .collection("/users")
    .unnest(field('scores').as('userScore'), /* index_field= */ 'attempt')
    .execute();

Nesse caso, userScore e attempt são substituídos.

  {name: "foo", scores: [5, 4], userScore: 5, attempt: 0}
  {name: "foo", scores: [5, 4], userScore: 4, attempt: 1}
  {name: "bar", scores: [1, 3], userScore: 1, attempt: 0}
  {name: "bar", scores: [1, 3], userScore: 3, attempt: 1}

Outros exemplos

Swift
let results = try await db.pipeline()
  .database()
  .unnest(Field("arrayField").as("unnestedArrayField"), indexField: "index")
  .execute()

Kotlin

val results = db.pipeline()
    .database()
    .unnest(field("arrayField").alias("unnestedArrayField"), UnnestOptions().withIndexField("index"))
    .execute()

Java

Task<Pipeline.Snapshot> results = db.pipeline()
    .database()
    .unnest(field("arrayField").alias("unnestedArrayField"), new UnnestOptions().withIndexField("index"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field
from google.cloud.firestore_v1.pipeline_stages import UnnestOptions

results = (
    client.pipeline()
    .database()
    .unnest(
        Field.of("arrayField").as_("unnestedArrayField"),
        options=UnnestOptions(index_field="index"),
    )
    .execute()
)
Java
Pipeline.Snapshot results =
    firestore
        .pipeline()
        .database()
        .unnest("arrayField", "unnestedArrayField", new UnnestOptions().withIndexField("index"))
        .execute()
        .get();

Valores não de matriz

Se a expressão de entrada for avaliada como um valor que não é uma matriz, essa etapa vai retornar o documento de entrada como está com o index_field definido como NULL, se especificado.

Por exemplo, para a seguinte coleção:

Node.js

await db.collection('users').add({name: "foo", scores: 1});
await db.collection('users').add({name: "bar", scores: null});
await db.collection('users').add({name: "qux", scores: {backupScores: 1}});

A etapa unnest pode ser usada para extrair cada pontuação individual por usuário.

Node.js

const userScore = await db.pipeline()
    .collection("/users")
    .unnest(field('scores').as('userScore'), /* index_field= */ 'attempt')
    .execute();

Isso produz os seguintes documentos com attempt definido como NULL.

  {name: "foo", scores: 1, attempt: null}
  {name: "bar", scores: null, attempt: null}
  {name: "qux", scores: {backupScores: 1}, attempt: null}

Valores de matriz vazios

Se a expressão de entrada for avaliada como uma matriz vazia, nenhum documento será retornado para esse documento de entrada.

Por exemplo, para a seguinte coleção:

Node.js

await db.collection('users').add({name: "foo", scores: [5, 4]});
await db.collection('users').add({name: "bar", scores: []});

A etapa unnest pode ser usada para extrair cada pontuação individual por usuário.

Node.js

const userScore = await db.pipeline()
    .collection("/users")
    .unnest(field('scores').as('userScore'), /* index_field= */ 'attempt')
    .execute();

Isso produz os seguintes documentos com o usuário bar ausente da saída.

  {name: "foo", scores: [5, 4], userScore: 5, attempt: 0}
  {name: "foo", scores: [5, 4], userScore: 4, attempt: 1}

Para retornar documentos com matrizes vazias também, coloque o valor sem aninhamento em uma matriz. Exemplo:

Node.js

const userScore = await db.pipeline()
    .collection("/users")
    .unnest(
      conditional(
        equal(field('scores'), []),
        array([field('scores')]),
        field('scores')
      ).as("userScore"),
    /* index_field= */ "attempt")
    .execute();

Agora, isso vai retornar o documento com o usuário bar.

  {name: "foo", scores: [5, 4], userScore: 5, attempt: 0}
  {name: "foo", scores: [5, 4], userScore: 4, attempt: 1}
  {name: "bar", scores: [], userScore: [], attempt: 0}

Outros exemplos

Node.js
    // Input
    // { identifier : 1, neighbors: [ "Alice", "Cathy" ] }
    // { identifier : 2, neighbors: []                   }
    // { identifier : 3, neighbors: "Bob"                }

    const results = await db.pipeline()
      .database()
      .unnest(Field.of('neighbors'), 'unnestedNeighbors', 'index')
      .execute();

    // Output
    // { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Alice", index: 0 }
    // { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Cathy", index: 1 }
    // { identifier: 3, neighbors: "Bob", index: null}
    
Swift
// Input
// { identifier : 1, neighbors: [ "Alice", "Cathy" ] }
// { identifier : 2, neighbors: []                   }
// { identifier : 3, neighbors: "Bob"                }

let results = try await db.pipeline()
  .database()
  .unnest(Field("neighbors").as("unnestedNeighbors"), indexField: "index")
  .execute()

// Output
// { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Alice", index: 0 }
// { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Cathy", index: 1 }
// { identifier: 3, neighbors: "Bob", index: null}

Kotlin

// Input
// { identifier : 1, neighbors: [ "Alice", "Cathy" ] }
// { identifier : 2, neighbors: []                   }
// { identifier : 3, neighbors: "Bob"                }

val results = db.pipeline()
    .database()
    .unnest(field("neighbors").alias("unnestedNeighbors"), UnnestOptions().withIndexField("index"))
    .execute()

// Output
// { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Alice", index: 0 }
// { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Cathy", index: 1 }
// { identifier: 3, neighbors: "Bob", index: null}

Java

// Input
// { identifier : 1, neighbors: [ "Alice", "Cathy" ] }
// { identifier : 2, neighbors: []                   }
// { identifier : 3, neighbors: "Bob"                }

Task<Pipeline.Snapshot> results = db.pipeline()
    .database()
    .unnest(field("neighbors").alias("unnestedNeighbors"), new UnnestOptions().withIndexField("index"))
    .execute();

// Output
// { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Alice", index: 0 }
// { identifier: 1, neighbors: [ "Alice", "Cathy" ], unnestedNeighbors: "Cathy", index: 1 }
// { identifier: 3, neighbors: "Bob", index: null}
Python
from google.cloud.firestore_v1.pipeline_expressions import Field
from google.cloud.firestore_v1.pipeline_stages import UnnestOptions

# Input
# { "identifier" : 1, "neighbors": [ "Alice", "Cathy" ] }
# { "identifier" : 2, "neighbors": []                   }
# { "identifier" : 3, "neighbors": "Bob"                }

results = (
    client.pipeline()
    .database()
    .unnest(
        Field.of("neighbors").as_("unnestedNeighbors"),
        options=UnnestOptions(index_field="index"),
    )
    .execute()
)

# Output
# { "identifier": 1, "neighbors": [ "Alice", "Cathy" ],
#   "unnestedNeighbors": "Alice", "index": 0 }
# { "identifier": 1, "neighbors": [ "Alice", "Cathy" ],
#   "unnestedNeighbors": "Cathy", "index": 1 }
# { "identifier": 3, "neighbors": "Bob", "index": null}
Java
// Input
// { "identifier" : 1, "neighbors": [ "Alice", "Cathy" ] }
// { "identifier" : 2, "neighbors": []                   }
// { "identifier" : 3, "neighbors": "Bob"                }

Pipeline.Snapshot results =
    firestore
        .pipeline()
        .database()
        .unnest("neighbors", "unnestedNeighbors", new UnnestOptions().withIndexField("index"))
        .execute()
        .get();

// Output
// { "identifier": 1, "neighbors": [ "Alice", "Cathy" ],
//   "unnestedNeighbors": "Alice", "index": 0 }
// { "identifier": 1, "neighbors": [ "Alice", "Cathy" ],
//   "unnestedNeighbors": "Cathy", "index": 1 }
// { "identifier": 3, "neighbors": "Bob", "index": null}

Unnest aninhado

Se a expressão for avaliada como uma matriz aninhada, várias etapas unnest precisarão ser usadas para simplificar cada nível aninhado.

Por exemplo, para a seguinte coleção:

Node.js

await db.collection('users').add({name: "foo", record: [{scores: [5, 4], avg: 4.5}, {scores: [1, 3], old_avg: 2}]});

A etapa unnest pode ser usada sequencialmente para extrair a matriz mais interna.

Node.js

const userScore = await db.pipeline()
    .collection("/users")
    .unnest(field('record').as('record'))
    .unnest(field('record.scores').as('userScore'), /* index_field= */ 'attempt')
    .execute();

Isso produz os seguintes documentos:

  {name: "foo", record: [{scores: [5, 4], avg: 4.5}], userScore: 5, attempt: 0}
  {name: "foo", record: [{scores: [5, 4], avg: 4.5}], userScore: 4, attempt: 1}
  {name: "foo", record: [{scores: [1, 3], avg: 2}], userScore: 1, attempt: 0}
  {name: "foo", record: [{scores: [1, 3], avg: 2}], userScore: 3, attempt: 1}