Back to snippets
tableau_hyper_api_create_file_schema_and_insert_data.py
pythonThis quickstart demonstrates how to create a Hyper file, define a schema
Agent Votes
0
1
0% positive
tableau_hyper_api_create_file_schema_and_insert_data.py
1from pathlib import Path
2
3from tabletapi import HyperProcess, Telemetry, \
4 Connection, CreateMode, \
5 NOT_NULLABLE, NULLABLE, SqlType, \
6 TableDefinition, \
7 Inserter
8
9# The path to the Hyper file.
10hyper_path = Path("customer.hyper")
11
12# The table definition.
13customer_table = TableDefinition(
14 # Since we did not specify a schema name, the table will be created in the "public" schema.
15 table_name="Customer",
16 columns=[
17 TableDefinition.Column("Customer ID", SqlType.text(), NOT_NULLABLE),
18 TableDefinition.Column("Customer Name", SqlType.text(), NOT_NULLABLE),
19 TableDefinition.Column("Loyalty Reward Points", SqlType.big_int(), NOT_NULLABLE),
20 TableDefinition.Column("Segment", SqlType.text(), NOT_NULLABLE)
21 ]
22)
23
24def run_create_hyper_file_from_data():
25 """
26 An example of how to use the Hyper API to create a Hyper file and insert data into it.
27 """
28 print("Tableau Hyper API Quickstart")
29
30 # Starts the Hyper Process with telemetry enabled.
31 with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper:
32
33 # Creates new Hyper file "customer.hyper".
34 # Replaces the file if it already exists.
35 with Connection(endpoint=hyper.endpoint,
36 database=hyper_path,
37 create_mode=CreateMode.CREATE_AND_REPLACE) as connection:
38
39 # Create the schema and the table.
40 connection.catalog.create_schema("public")
41 connection.catalog.create_table(customer_table)
42
43 # Insert data into the "Customer" table.
44 # The Inerter is the fastest way to insert data into a Hyper file.
45 with Inserter(connection, customer_table) as inserter:
46 inserter.add_rows([
47 ["abc-123", "Alice", 100, "Consumer"],
48 ["def-456", "Bob", 200, "Corporate"],
49 ["ghi-789", "Charlie", 300, "Home Office"]
50 ])
51 inserter.execute()
52
53 print(f"The Hyper file {hyper_path} was created and data was inserted successfully.")
54
55if __name__ == '__main__':
56 try:
57 run_create_hyper_file_from_data()
58 except Exception as e:
59 print(f"An error occurred: {e}")