Compartilhar via


partition operator

Applies to: ✅Microsoft FabricAzure Data ExplorerAzure MonitorMicrosoft Sentinel

O operador de partição particiona os registros de sua tabela de entrada em várias subtabelas de acordo com os valores em uma coluna de chave. O operador executa uma subconsulta em cada subtabela e produz uma única tabela de saída que é a união dos resultados de todas as subconsultas.

O operador de partição é útil quando você precisa executar uma subconsulta somente em um subconjunto de linhas que pertencem à mesma chave de partição e não a uma consulta de todo o conjunto de dados. These subqueries could include aggregate functions, window functions, top N and others.

O operador de partição dá suporte a várias estratégias de operação de subconsulta:

  • Native - use with an implicit data source with thousands of key partition values.
  • Shuffle - use with an implicit source with millions of key partition values.
  • Legacy - use with an implicit or explicit source for 64 or less key partition values.

Syntax

T|partition [ hint.strategy=Strategy ] [ Hints ] byColumn(TransformationSubQuery)

T|partition [ hint.strategy=legacy ] [ Hints ] byColumn{SubQueryWithSource}

Learn more about syntax conventions.

Parameters

Name Tipo Required Description
T string ✔️ A fonte tabular de entrada.
Strategy string O valor legacy, shuffle, ou native. Essa dica define a estratégia de execução do operador de partição.

Se nenhuma estratégia for especificada, a legacy estratégia será usada. For more information, see Strategies.
Column string ✔️ The name of a column in T whose values determine how to partition the input tabular source.
TransformationSubQuery string ✔️ Uma expressão de transformação tabular. The source is implicitly the subtables produced by partitioning the records of T. Each subtable is homogenous on the value of Column.

A expressão deve fornecer apenas um resultado tabular e não deve ter outros tipos de instruções, como let instruções.
SubQueryWithSource string ✔️ Uma expressão tabular que inclui sua própria fonte tabular, como uma referência de tabela. This syntax is only supported with the legacy strategy. The subquery can only reference the key column, Column, from T. To reference the column, use the syntax toscalar(Column).

A expressão deve fornecer apenas um resultado tabular e não deve ter outros tipos de instruções, como let instruções.
Hints string Zero or more space-separated parameters in the form of: HintName=Value that control the behavior of the operator. See the supported hints per strategy type.

Supported hints

Hint name Tipo Strategy Description
hint.shufflekey string shuffle A chave de partição usada para executar o operador de partição com a shuffle estratégia.
hint.materialized bool legacy Se definido como true, materializará a origem do operador partition. O valor padrão é false.
hint.concurrency int legacy Determina quantas partições devem ser executadas em paralelo. O valor padrão é 16.
hint.spread int legacy Determina como distribuir as partições entre os nós do cluster. O valor padrão é 1.

For example, if there are N partitions and the spread hint is set to P, then the N partitions are processed by P different cluster nodes equally, in parallel/sequentially depending on the concurrency hint.

Returns

O operador retorna uma união dos resultados das subconsultas individuais.

Strategies

The partition operator supports several strategies of subquery operation: native, shuffle, and legacy.

Note

A distinção entre as native estratégias and shuffle permite que o chamador indique a cardinalidade e a estratégia de execução da subconsulta. Essa escolha pode afetar quanto tempo a subconsulta leva para ser concluída, mas não altera o resultado final.

Native strategy

Essa estratégia deve ser aplicada quando o número de valores distintos da chave de partição não for grande, aproximadamente na casa dos milhares.

A subconsulta deve ser uma transformação tabular que não especifica uma fonte tabular. A fonte é implícita e é atribuída de acordo com as partições da subtabela. Only certain supported operators can be used in the subquery. Não há restrição quanto ao número de partições.

Para usar essa estratégia, especifique hint.strategy=native.

Shuffle strategy

Essa estratégia deve ser aplicada quando o número de valores distintos da chave de partição for grande, na casa dos milhões.

A subconsulta deve ser uma transformação tabular que não especifica uma fonte tabular. A fonte é implícita e é atribuída de acordo com as partições da subtabela. Only certain supported operators can be used in the subquery. Não há restrição quanto ao número de partições.

Para usar essa estratégia, especifique hint.strategy=shuffle. For more information about shuffle strategy and performance, see shuffle query.

Operadores suportados para as estratégias nativas e aleatórias

A seguinte lista de operadores pode ser usada em subconsultas com as estratégias nativas ou aleatórias:

Note

  • Os operadores que fazem referência a uma fonte de tabela diferente das partições de subtabela não são compatíveis com as native estratégias and shuffle . For example, join, union, externaldata, and evaluate (plugins). For such scenarios, resort to the legacy strategy.
  • The fork operator isn't supported for any strategy type, as the subquery must return a single tabular result.
  • The make-series operator is only partially supported within the partition by operator. Ele só tem suporte quando os parâmetros e from os to parâmetros são especificados.

Legacy strategy

Por razões históricas, a legacy estratégia é a estratégia padrão. However, we recommend favoring the native or shuffle strategies, as the legacy approach is limited to 64 partitions and is less efficient.

Em alguns cenários, a legacy estratégia pode ser necessária devido ao seu suporte para incluir uma fonte tabular na subconsulta. In such cases, the subquery can only reference the key column, Column, from the input tabular source, T. To reference the column, use the syntax toscalar(Column).

Se a subconsulta for uma transformação tabular sem uma fonte tabular, a origem será implícita e se baseará nas partições da subtabela.

Para usar essa estratégia, especifique hint.strategy=legacy ou omita qualquer outra indicação de estratégia.

Note

An error occurs if the partition column, Column, contains more than 64 distinct values.

Examples

Os exemplos nesta seção mostram como usar a sintaxe para ajudá-lo a começar.

The examples in this article use publicly available tables in the help cluster, such as the StormEvents table in the Samples database.

The examples in this article use publicly available tables, such as the Weather table in the Weather analytics sample gallery. Talvez seja necessário modificar o nome da tabela na consulta de exemplo para corresponder à tabela em seu workspace.

Encontre os melhores valores

Em alguns casos, é mais eficiente e fácil escrever uma consulta usando o partition operador do que usando o top-nested operador. A consulta a seguir executa uma subconsulta calculando summarize e top para cada um State começando com W: "WYOMING", "WASHINGTON", "WEST VIRGINIA" e "WISCONSIN".

StormEvents
| where State startswith 'W'
| partition hint.strategy=native by State 
    (
    summarize Events=count(), Injuries=sum(InjuriesDirect) by EventType, State
    | top 3 by Events 
    ) 

Output

EventType State Events Injuries
Hail WYOMING 108 0
High Wind WYOMING 81 5
Winter Storm WYOMING 72 0
Heavy Snow WASHINGTON 82 0
High Wind WASHINGTON 58 13
Wildfire WASHINGTON 29 0
Thunderstorm Wind WEST VIRGINIA 180 1
Hail WEST VIRGINIA 103 0
Winter Weather WEST VIRGINIA 88 0
Thunderstorm Wind WISCONSIN 416 1
Winter Storm WISCONSIN 310 0
Hail WISCONSIN 303 1

Native strategy

A consulta a seguir retorna os 2 EventType principais valores por TotalInjuries para cada State um que começa com 'W':

StormEvents
| where State startswith 'W'
| partition hint.strategy = native by State
    (
    summarize TotalInjueries = sum(InjuriesDirect) by EventType
    | top 2 by TotalInjueries
    )

Output

EventType TotalInjueries
Tornado 4
Hail 1
Thunderstorm Wind 1
Excessive Heat 0
High Wind 13
Lightning 5
High Wind 5
Avalanche 3

Shuffle strategy

A consulta a seguir retorna os 3 DamagedProperty principais valores foreach EpisodeId e as colunas EpisodeId e State.

StormEvents
| partition hint.strategy=shuffle by EpisodeId
    (
    top 3 by DamageProperty
    | project EpisodeId, State, DamageProperty
    )
| count

Output

Count
22345

Estratégia legada com fonte explícita

A consulta a seguir executa duas subconsultas:

  • Quando x == 1, a consulta retorna todas as linhas que StormEvents têm InjuriesIndirect == 1.
  • Quando x == 2, a consulta retorna todas as linhas que StormEvents têm InjuriesIndirect == 2.

O resultado final é a união dessas duas subquestões.

range x from 1 to 2 step 1
| partition hint.strategy=legacy by x {StormEvents | where x == InjuriesIndirect}
| count 

Output

Count
113

Partition reference

The following example shows how to use the as operator to give a "name" to each data partition and then reuse that name within the subquery. Essa abordagem é relevante apenas para a legacy estratégia.

T
| partition by Dim
(
    as Partition
    | extend MetricPct = Metric * 100.0 / toscalar(Partition | summarize sum(Metric))
)