Nota
O acesso a esta página requer autorização. Podes tentar iniciar sessão ou mudar de diretório.
O acesso a esta página requer autorização. Podes tentar mudar de diretório.
Applies to: ✅Microsoft Fabric✅Azure Data Explorer✅Azure Monitor✅Microsoft 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 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 suporta 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, shuffleou native. Esta dica define a estratégia de execução do operador de partição.
Se nenhuma estratégia for especificada, a estratégia legacy 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 instruções let. |
| 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 instruções let. |
| 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 estratégia shuffle. |
hint.materialized |
bool |
legacy | Se definido como true, materializa 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 nós de 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 estratégias native e shuffle permite que o chamador indique a cardinalidade e a estratégia de execução da subconsulta. Essa escolha pode afetar o tempo que a subconsulta leva para ser concluída, mas não altera o resultado final.
Native strategy
Esta estratégia deve ser aplicada quando o número de valores distintos da chave de partição não é grande, aproximadamente aos milhares.
A subconsulta deve ser uma transformação tabular que não especifique 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
Esta estratégia deve ser aplicada quando o número de valores distintos da chave de partição é grande, na casa dos milhões.
A subconsulta deve ser uma transformação tabular que não especifique 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 shuffle
A seguinte lista de operadores pode ser usada em subconsultas com as estratégias nativas ou shuffle:
- count
- distinct
- extend
- make-series (partially supported, see note)
- mv-apply
- mv-expand
- parse
- parse-where
- project
- project-away
- project-keep
- project-rename
- project-reorder
- reduce
- sample
- sample-distinct
- scan
- search
- serialize
- sort
- summarize
- take
- top
- top-hitters
- top-nested
- where
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 estratégias
nativeeshuffle. 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 byoperator. Ele é suportado somente quando osfromparâmetros etosão especificados.
Legacy strategy
Por razões históricas, a estratégia legacy é 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 estratégia legacy 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 estará 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
StormEventstable in the Samples database.
The examples in this article use publicly available tables, such as the
Weathertable in the Weather analytics sample gallery. Talvez seja necessário modificar o nome da tabela na consulta de exemplo para corresponder à tabela em seu espaço de trabalho.
Encontrar os melhores valores
Em alguns casos, é mais eficiente e mais fácil escrever uma consulta usando o operador partition do que usando o operador top-nested. A consulta a seguir executa uma subconsulta calculando summarize e top para cada 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 principais valores de EventType por TotalInjuries para cada State 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 principais valores de DamagedProperty para cada 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 deStormEventsque tenhamInjuriesIndirect == 1. - Quando
x == 2, a consulta retorna todas as linhas deStormEventsque tenhamInjuriesIndirect == 2.
O resultado final é a união dessas duas subconsultas.
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. Esta abordagem só é relevante para a estratégia legacy.
T
| partition by Dim
(
as Partition
| extend MetricPct = Metric * 100.0 / toscalar(Partition | summarize sum(Metric))
)