Funções de gerenciamento de coleções collection-management-functions

Sobre funções de coleção de consulta

A linguagem de expressão também introduz um conjunto de funções para consultar coleções. Essas funções são explicadas abaixo.

Nos exemplos a seguir, usamos um evento chamado “LobbyBeacon” que contém uma coleção de tokens de notificação por push. Os exemplos nesta página usam a estrutura de payload do evento mostrada abaixo:

                {
   "_experience":{
      "campaign":{
         "message":{
            "profile":{
               "pushNotificationTokens":[
                  {
                     "token":"token_1",
                     "application":{
                        "_id":"APP1",
                        "name":"MarltonMobileApp",
                        "version":"1.0"
                     }
                  },
                  {
                     "token":"token_2",
                     "application":{
                        "_id":"APP2",
                        "name":"MarketplaceApp",
                        "version":"1.0"
                     }
                  },
                  {
                     "token":"token_3",
                     "application":{
                        "_id":"APP3",
                        "name":"VendorApp",
                        "version":"2.0"
                     }
                  }
               ]
            }
         }
      }
   },
   "timestamp":"1536160728"
}
NOTE
Nos exemplos abaixo, essa carga é referenciada usando @event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens}, onde "LobbyBeacon" é o nome do evento e o restante do caminho corresponde à estrutura mostrada acima.

A função all(<condition>)

A função all habilita a definição de um filtro em uma determinada coleção usando uma expressão booliana.

<listExpression>.all(<condition>)

Exemplo conceitual: Entre todos os usuários do aplicativo, você pode obter os usuários usando o IOS 13 (expressão booleana “app used == IOS 13”). O resultado dessa função é a lista filtrada que contém itens correspondentes à expressão booleana (exemplo: usuário do aplicativo 1, usuário do aplicativo 34, usuário do aplicativo 432).

Em uma atividade Data Source Condition, você pode verificar se o resultado da função all é nulo ou não. Você também pode combinar essa função all com outras funções, como count. Para obter mais informações, consulte Atividade de Condição Data Source.

Exemplos de código usando a carga LobbyBeacon:

Os exemplos abaixo usam a carga do evento mostrada na parte superior desta página.

CAUTION
Não há suporte para o uso de eventos de experiência em expressões/condições de jornada. Se o seu caso de uso exigir o uso de eventos de experiência, considere métodos alternativos. Saiba mais

Exemplo 1

Queremos verificar se um usuário instalou uma versão específica de um aplicativo. Para isso, obtemos todos os tokens de notificação por push associados a aplicativos móveis para os quais a versão é 1.0. Em seguida, executamos uma condição com a função count para verificar se a lista retornada de tokens contém pelo menos um elemento.

count(@event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens.all(currentEventField.application.version == "1.0").token}) > 0

O resultado é true.

Exemplo 2

Aqui usamos a função count para verificar se há tokens de notificação por push na coleção.

count(@event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens.all().token}) > 0

O resultado é true.

count(@event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens.token})

O resultado da expressão é 3.

NOTE
  • Quando a condição de filtragem na função all() estiver vazia, o filtro retornará todos os elementos da lista. No entanto, para contar o número de elementos de uma coleção, a função all não é necessária.

  • currentEventField está disponível somente ao manipular coleções de eventos, currentDataPackField ao manipular coleções de fonte de dados e currentActionField ao manipular coleções de resposta de ação personalizada.

Ao processar coleções com all, first e last, repetimos cada elemento da coleção um por um. currentEventField, currentDataPackField e currentActionField correspondem ao elemento que está sendo repetido.

As funções first(<condition>) e last(<condition>)

As funções first e last também habilitam a definição de um filtro na coleção ao retornar o primeiro/último elemento da lista que atende ao filtro.

<listExpression>.first(<condition>)

<listExpression>.last(<condition>)

Exemplo 1

Essa expressão retorna o primeiro token de notificação por push associado aos aplicativos móveis para os quais a versão é 1.0.

@event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens.first(currentEventField.application.version == "1.0").token}

O resultado é token_1.

Exemplo 2

Essa expressão retorna o último token de notificação por push associado aos aplicativos móveis para os quais a versão é 1.0.

@event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens.last(currentEventField.application.version == "1.0").token}

O resultado é token_2.

A função at(<index>)

A função às permite fazer referência a um elemento específico em uma coleção de acordo com um índice.
O índice 0 é o primeiro índice da coleção.

<listExpression>.às(<index>)

Exemplo

Essa expressão retorna o segundo token de notificação por push da lista.

@event{LobbyBeacon._experience.campaign.message.profile.pushNotificationTokens.at(1).token}

O resultado é token_2.

AI Knowledge Reference

This section contains structured knowledge intended to support interpretation, retrieval, and question answering related to this topic.

For complete understanding, this information should be combined with the documentation on this page. Neither source is intended to stand alone; the page describes the feature, while this section provides additional context that helps disambiguate terminology, intent, applicability, and constraints.

  • TL;DR: This page documents the all(), first(), last(), and at() collection management functions used in the Journey advanced expression editor, illustrated with push notification token payload examples.

Intents:

  • Filter a collection of event or data source fields using a boolean condition with all(<condition>)
  • Count filtered or unfiltered collection elements using count() combined with collection functions
  • Retrieve the first or last matching element of a collection using first() or last()
  • Access a collection element at a specific zero-based index using at(<index>)
  • Understand which loop variable (currentEventField, currentDataPackField, currentActionField) applies to each collection context

Glossary:

  • all(condition): Filters a collection and returns all items matching the given boolean expression (product-specific)
  • first(condition): Returns the first (most recent for experience events) element in a collection matching the condition (product-specific)
  • last(condition): Returns the last (oldest for experience events) element in a collection matching the condition (product-specific)
  • at(index): Returns the element at the specified zero-based index of a collection (product-specific)
  • currentEventField: Loop variable available only when iterating over event collections (product-specific)
  • currentDataPackField: Loop variable available only when iterating over data source collections (product-specific)
  • currentActionField: Loop variable available only when iterating over custom action response collections (product-specific)

Guardrails:

  • Using experience events in journey expressions/conditions is not supported; consider alternative methods such as computed attributes
  • currentEventField, currentDataPackField, and currentActionField are only available inside their respective collection contexts
  • The all function is not required to count collection elements — count() can be applied directly to the field path
  • When all() is called with an empty condition, all elements in the collection are returned

Terminology:

  • Canonical name: Collection Management Functions — Acronym: none — variants: collection functions, query collection functions
  • Synonyms: “all()” = “collection filter function”; “at()” = “index accessor”
  • Do not confuse: first() (most recent experience event) ≠ first inserted element in general lists

FAQ:

  • Q: What is the difference between all() with an empty condition and all() with a condition? — An empty all() returns every element; a condition-based all() returns only elements matching that boolean expression.
  • Q: How do I count push notification tokens without using all()? — Call count() directly on the token field path, e.g. count(@event{LobbyBeacon...pushNotificationTokens.token}).
  • Q: Which variable do I use to reference the current element when looping over a data source collection? — Use currentDataPackField inside all(), first(), or last() on data source collections.
  • Q: How do I get the second item in a collection? — Use at(1) because index 0 is the first element.
  • Q: Why does last() return the oldest experience event? — Experience events are stored in reverse chronological order, so the last position in the collection corresponds to the oldest event.
recommendation-more-help
journey-optimizer-help