|
| 1 | +""" |
| 2 | +Using `sqlframe` with CrateDB: Basic usage. |
| 3 | +
|
| 4 | + pip install --upgrade sqlframe |
| 5 | +
|
| 6 | +A few basic operations using the `sqlframe` library with CrateDB. |
| 7 | +
|
| 8 | +- https://pypi.org/project/sqlframe/ |
| 9 | +""" |
| 10 | + |
| 11 | +from psycopg2 import connect |
| 12 | +from sqlframe import activate |
| 13 | +from sqlframe.base.functions import col |
| 14 | + |
| 15 | +from patch import monkeypatch |
| 16 | + |
| 17 | + |
| 18 | +def connect_spark(): |
| 19 | + # Connect to database. |
| 20 | + conn = connect( |
| 21 | + dbname="crate", |
| 22 | + user="crate", |
| 23 | + password="", |
| 24 | + host="localhost", |
| 25 | + port="5432", |
| 26 | + ) |
| 27 | + # Activate SQLFrame to run directly on CrateDB. |
| 28 | + activate("postgres", conn=conn) |
| 29 | + |
| 30 | + from pyspark.sql import SparkSession |
| 31 | + |
| 32 | + spark = SparkSession.builder.getOrCreate() |
| 33 | + return spark |
| 34 | + |
| 35 | + |
| 36 | +def sqlframe_select_sys_summits(): |
| 37 | + """ |
| 38 | + Query CrateDB's built-in `sys.summits` table. |
| 39 | + :return: |
| 40 | + """ |
| 41 | + spark = connect_spark() |
| 42 | + df = spark.sql( |
| 43 | + spark.table("sys.summits") |
| 44 | + .where(col("region").ilike("ortler%")) |
| 45 | + .sort(col("height").desc()) |
| 46 | + .limit(3) |
| 47 | + ) |
| 48 | + print(df.sql()) |
| 49 | + df.show() |
| 50 | + return df |
| 51 | + |
| 52 | + |
| 53 | +def sqlframe_export_sys_summits_pandas(): |
| 54 | + """ |
| 55 | + Query CrateDB's built-in `sys.summits` table, returning a pandas dataframe. |
| 56 | + """ |
| 57 | + spark = connect_spark() |
| 58 | + df = spark.sql( |
| 59 | + spark.table("sys.summits") |
| 60 | + .where(col("region").ilike("ortler%")) |
| 61 | + .sort(col("height").desc()) |
| 62 | + .limit(3) |
| 63 | + ).toPandas() |
| 64 | + return df |
| 65 | + |
| 66 | + |
| 67 | +def sqlframe_export_sys_summits_csv(): |
| 68 | + """ |
| 69 | + Query CrateDB's built-in `sys.summits` table, saving the output to CSV. |
| 70 | + """ |
| 71 | + spark = connect_spark() |
| 72 | + df = spark.sql( |
| 73 | + spark.table("sys.summits") |
| 74 | + .where(col("region").ilike("ortler%")) |
| 75 | + .sort(col("height").desc()) |
| 76 | + .limit(3) |
| 77 | + ) |
| 78 | + df.write.csv("summits.csv", mode="overwrite") |
| 79 | + return df |
| 80 | + |
| 81 | + |
| 82 | +def sqlframe_get_table_names(): |
| 83 | + """ |
| 84 | + Inquire table names of the system schema `sys`. |
| 85 | + """ |
| 86 | + spark = connect_spark() |
| 87 | + tables = spark.catalog.listTables(dbName="sys") |
| 88 | + return tables |
| 89 | + |
| 90 | + |
| 91 | +monkeypatch() |
| 92 | + |
| 93 | + |
| 94 | +if __name__ == "__main__": |
| 95 | + print(sqlframe_select_sys_summits()) |
| 96 | + print(sqlframe_export_sys_summits_pandas()) |
| 97 | + print(sqlframe_export_sys_summits_csv()) |
| 98 | + print(sqlframe_get_table_names()) |
0 commit comments