Hub documentation
Executar operações SQL
Executar operações SQL
Executar operações SQL com DuckDB abre um mundo de possibilidades para consultar conjuntos de dados de forma eficiente. Vamos explorar alguns exemplos que demonstram o poder das funções do DuckDB.
Para nossa demonstração, exploraremos um dataset fascinante. O dataset MMLU é um teste multitarefa que contém perguntas de múltipla escolha abrangendo diversos domínios de conhecimento.
Para visualizar o conjunto de dados, vamos selecionar uma amostra de 3 linhas:
FROM 'hf://datasets/cais/mmlu/all/test-*.parquet' USING SAMPLE 3;
┌──────────────────────┬──────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬────────┐
│ question │ subject │ choices │ answer │
│ varchar │ varchar │ varchar[] │ int64 │
├──────────────────────┼──────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼────────┤
│ The model of light… │ conceptual_physics │ [wave model, particle model, Both of these, Neither of these] │ 1 │
│ A person who is lo… │ professional_psych… │ [his/her life scripts., his/her own feelings, attitudes, and beliefs., the emotional reactions and behaviors of the people he/she is interacting with.… │ 1 │
│ The thermic effect… │ nutrition │ [is substantially higher for carbohydrate than for protein, is accompanied by a slight decrease in body core temperature., is partly related to sympat… │ 2 │
└──────────────────────┴──────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────┘
Esse comando recupera uma amostra aleatória de 3 linhas do conjunto de dados para que possamos examiná-las.
Vamos começar examinando o esquema do nosso conjunto de dados. A tabela a seguir descreve a estrutura do nosso conjunto de dados:
DESCRIBE FROM 'hf://datasets/cais/mmlu/all/test-*.parquet' USING SAMPLE 3;
┌─────────────┬─────────────┬─────────┬─────────┬─────────┬─────────┐
│ column_name │ column_type │ null │ key │ default │ extra │
│ varchar │ varchar │ varchar │ varchar │ varchar │ varchar │
├─────────────┼─────────────┼─────────┼─────────┼─────────┼─────────┤
│ question │ VARCHAR │ YES │ │ │ │
│ subject │ VARCHAR │ YES │ │ │ │
│ choices │ VARCHAR[] │ YES │ │ │ │
│ answer │ BIGINT │ YES │ │ │ │
└─────────────┴─────────────┴─────────┴─────────┴─────────┴─────────┘
A seguir, vamos analisar se há registros duplicados em nosso conjunto de dados:
SELECT *,
COUNT(*) AS counts
FROM 'hf://datasets/cais/mmlu/all/test-*.parquet'
GROUP BY ALL
HAVING counts > 2;
┌──────────┬─────────┬───────────┬────────┬────────┐
│ question │ subject │ choices │ answer │ counts │
│ varchar │ varchar │ varchar[] │ int64 │ int64 │
├──────────┴─────────┴───────────┴────────┴────────┤
│ 0 rows │
└──────────────────────────────────────────────────┘
Felizmente, nosso conjunto de dados não contém nenhum registro duplicado.
Vamos ver a proporção de perguntas com base no assunto em uma representação de barras:
SELECT
subject,
COUNT(*) AS counts,
BAR(COUNT(*), 0, (SELECT COUNT(*) FROM 'hf://datasets/cais/mmlu/all/test-*.parquet')) AS percentage
FROM
'hf://datasets/cais/mmlu/all/test-*.parquet'
GROUP BY
subject
ORDER BY
counts DESC;
┌──────────────────────────────┬────────┬────────────────────────────────────────────────────────────────────────────────┐
│ subject │ counts │ percentage │
│ varchar │ int64 │ varchar │
├──────────────────────────────┼────────┼────────────────────────────────────────────────────────────────────────────────┤
│ professional_law │ 1534 │ ████████▋ │
│ moral_scenarios │ 895 │ █████ │
│ miscellaneous │ 783 │ ████▍ │
│ professional_psychology │ 612 │ ███▍ │
│ high_school_psychology │ 545 │ ███ │
│ high_school_macroeconomics │ 390 │ ██▏ │
│ elementary_mathematics │ 378 │ ██▏ │
│ moral_disputes │ 346 │ █▉ │
├──────────────────────────────┴────────┴────────────────────────────────────────────────────────────────────────────────┤
│ 57 rows (8 shown) 3 columns │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Agora, vamos preparar um subconjunto do conjunto de dados contendo perguntas relacionadas a nutrição e criar um mapeamento de perguntas para as respostas corretas. Observe que temos a coluna choices, da qual podemos obter a resposta correta usando a coluna answer como índice.
SELECT *
FROM 'hf://datasets/cais/mmlu/all/test-*.parquet'
WHERE subject = 'nutrition' LIMIT 3;
┌──────────────────────┬───────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬────────┐
│ question │ subject │ choices │ answer │
│ varchar │ varchar │ varchar[] │ int64 │
├──────────────────────┼───────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼────────┤
│ Which foods tend t… │ nutrition │ [Meat, Confectionary, Fruits and vegetables, Potatoes] │ 2 │
│ In which one of th… │ nutrition │ [If the incidence rate of the disease falls., If survival time with the disease increases., If recovery of the disease is faster., If the population in which the… │ 1 │
│ Which of the follo… │ nutrition │ [The flavonoid class comprises flavonoids and isoflavonoids., The digestibility and bioavailability of isoflavones in soya food products are not changed by proce… │ 0 │
└──────────────────────┴───────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────┘
SELECT question,
choices[answer] AS correct_answer
FROM 'hf://datasets/cais/mmlu/all/test-*.parquet'
WHERE subject = 'nutrition' LIMIT 3;
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────┐
│ question │ correct_answer │
│ varchar │ varchar │
├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────┤
│ Which foods tend to be consumed in lower quantities in Wales and Scotland (as of 2020)?\n │ Confectionary │
│ In which one of the following circumstances will the prevalence of a disease in the population increase, all else being constant?\n │ If the incidence rate of the disease falls. │
│ Which of the following statements is correct?\n │ │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────┘
Para garantir a limpeza dos dados, vamos remover quaisquer caracteres de quebra de linha no final das perguntas e filtrar respostas vazias:
SELECT regexp_replace(question, '\n', '') AS question,
choices[answer] AS correct_answer
FROM 'hf://datasets/cais/mmlu/all/test-*.parquet'
WHERE subject = 'nutrition' AND LENGTH(correct_answer) > 0 LIMIT 3;
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────┐
│ question │ correct_answer │
│ varchar │ varchar │
├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────┤
│ Which foods tend to be consumed in lower quantities in Wales and Scotland (as of 2020)? │ Confectionary │
│ In which one of the following circumstances will the prevalence of a disease in the population increase, all else being constant? │ If the incidence rate of the disease falls. │
│ Which vitamin is a major lipid-soluble antioxidant in cell membranes? │ Vitamin D │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────┘
Por fim, vamos destacar algumas das funções do DuckDB usadas nesta seção:
DESCRIBE, retorna o esquema da tabela.USING SAMPLE, as amostras são usadas para selecionar aleatoriamente um subconjunto de um conjunto de dados.BAR, desenha uma faixa cuja largura é proporcional a (x - min) e igual a width caracteres quando x = max. A largura padrão é 80.string[begin:end], extrai uma string usando convenções de fatiamento. Argumentos begin ou end ausentes são interpretados como o início ou o fim da lista, respectivamente. Valores negativos são aceitos.regexp_replace, se a string contém o padrão de expressão regular, substitui a parte correspondente pela substituição.LENGTH, obtém o número de caracteres na string.
Update on GitHubHá muitas funções úteis disponíveis no resumo das funções SQL do DuckDB. O melhor é que você pode usá-las diretamente em datasets do Hugging Face.