sql - 在 spark sql 中用 LIMIT 描述

标签 sql pyspark apache-spark-sql sql-limit

我正在使用 DESCRIBE 关键字来获取有关临时 View 的列信息。这是一个有用的方法,但是我有一个表,我只想描述列的一个子集。我正在尝试将 LIMITDESCRIBE 结合使用来实现此目的,但无法弄清楚。

这是一个玩具数据集(使用 pyspark 创建):

# make some test data
columns = ['id', 'dogs', 'cats', 'horses', 'people']
vals = [
     (1, 2, 0, 4, 3),
     (2, 0, 1, 2, 4)
]

# create DataFrame
df = spark.createDataFrame(vals, columns)
df.createOrReplaceTempView('df')

现在用sql描述:

%%sql

DESCRIBE df

输出:

col_name    data_type
id          bigint
dogs        bigint
cats        bigint
horses      bigint
people      bigint

实际上我有比这更多的列,我想做的是 LIMIT 这个查询的输出。以下是我尝试过的几件事:

尝试 #1:

DESCRIBE df
LIMIT 3

错误:

An error was encountered:
"\nextraneous input '3' expecting {<EOF>, '.'}(line 3, pos 6)\n\n== SQL ==\n\nDESCRIBE df\nLIMIT 3 \n------^^^\n"
Traceback (most recent call last):
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/session.py", line 603, in sql
    return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped)
  File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 73, in deco
    raise ParseException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.ParseException: "\nextraneous input '3' expecting {<EOF>, '.'}(line 3, pos 6)\n\n== SQL ==\n\nDESCRIBE df\nLIMIT 3 \n------^^^\n"

尝试#2:

SELECT a.*
FROM (
    DESCRIBE df
) AS a
LIMIT 3

错误:

An error was encountered:
'Table or view not found: DESCRIBE; line 4 pos 4'
Traceback (most recent call last):
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/session.py", line 603, in sql
    return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped)
  File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 69, in deco
    raise AnalysisException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.AnalysisException: 'Table or view not found: DESCRIBE; line 4 pos 4'

有谁知道是否可以限制 describe 的输出?

最佳答案

这是一种使用 pyspark.sql.dataframe.limit() 限制 DESCRIBE 输出的方法。使用 pyspark.sql.context.sql() 运行 DESCRIBE 查询。这会将结果作为 DataFrame 返回,您可以调用 limit():

df.registerTempTable('df')
spark.sql('DESCRIBE df').limit(3).show()
#+--------+---------+-------+
#|col_name|data_type|comment|
#+--------+---------+-------+
#|      id|   bigint|   null|
#|    dogs|   bigint|   null|
#|    cats|   bigint|   null|
#+--------+---------+-------+

但是,如果您只是查找列的数据类型,则可以使用 DataFrame 的 dtypes 属性:

df.dtypes
#[('id', 'bigint'),
# ('dogs', 'bigint'),
# ('cats', 'bigint'),
# ('horses', 'bigint'),
# ('people', 'bigint')]

这是一个元组列表,可以根据需要切片:

df.dtypes[0:3]
#[('id', 'bigint'), ('dogs', 'bigint'), ('cats', 'bigint')]

DataFrames 也有一个 describe() 方法返回汇总统计信息:

df.describe().show()
#+-------+------------------+------------------+------------------+------------------+------------------+
#|summary|                id|              dogs|              cats|            horses|            people|
#+-------+------------------+------------------+------------------+------------------+------------------+
#|  count|                 2|                 2|                 2|                 2|                 2|
#|   mean|               1.5|               1.0|               0.5|               3.0|               3.5|
#| stddev|0.7071067811865476|1.4142135623730951|0.7071067811865476|1.4142135623730951|0.7071067811865476|
#|    min|                 1|                 0|                 0|                 2|                 3|
#|    max|                 2|                 2|                 1|                 4|                 4|
#+-------+------------------+------------------+------------------+------------------+------------------+

如果你想限制列数,你可以使用 select() 并指定一片 df.columns:

df.select(df.columns[0:3]).describe().show()
#+-------+------------------+------------------+------------------+
#|summary|                id|              dogs|              cats|
#+-------+------------------+------------------+------------------+
#|  count|                 2|                 2|                 2|
#|   mean|               1.5|               1.0|               0.5|
#| stddev|0.7071067811865476|1.4142135623730951|0.7071067811865476|
#|    min|                 1|                 0|                 0|
#|    max|                 2|                 2|                 1|
#+-------+------------------+------------------+------------------+

关于sql - 在 spark sql 中用 LIMIT 描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48929831/

相关文章:

sql - ORACLE SQL 开发人员(查询)

sql - FreeText 查询很慢 - 包括 TOP 和 Order By

python - 在 PySpark 中使用微秒时间戳

python - PySpark 中的随机数生成

r - 在 SparkR 中删除 DataFrame 的列

mysql - 能否建议大型关系数据分析器的解决方案?

apache-spark - 无法将类型 <class 'pyspark.ml.linalg.SparseVector' > 转换为 Vector

SQL Server 2005 : Order with NULL values at the end

来自 2 个表的 SQL 匹配数据

python - 如何在 PySpark 中只打印 DataFrame 的某一列?