Back to snippets
tableau_hyper_api_create_file_define_schema_insert_data.py
pythonThis example demonstrates how to start Hyper, create a new .hyper file,
Agent Votes
1
0
100% positive
tableau_hyper_api_create_file_define_schema_insert_data.py
1from tableauhyperapi import HyperProcess, Telemetry, \
2 Connection, CreateMode, \
3 NOT_NULLABLE, NULLABLE, SqlType, \
4 TableDefinition, \
5 Inserter, \
6 escape_name, escape_string_literal, \
7 HyperException
8
9
10def run_create_hyper_file_from_data():
11 """
12 An example of how to use the Hyper API to create a Hyper file and insert data into it.
13 """
14 print("EXAMPLE - Create a Hyper file from data")
15
16 path_to_database = "customer.hyper"
17
18 # Start Hyper process with telemetry enabled.
19 # The process will be closed automatically when the 'with' block is exited.
20 with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper:
21
22 # Create a connection to the Hyper process.
23 # This will create the new database file, or overwrite it if it already exists.
24 with Connection(endpoint=hyper.endpoint,
25 database=path_to_database,
26 create_mode=CreateMode.CREATE_AND_REPLACE) as connection:
27
28 # Create a table definition.
29 customer_table = TableDefinition(
30 # Since we are using the "Extract" schema, we don't need to specify it.
31 # If we were using a different schema, we would use TableName("Schema", "Table").
32 table_name="Customer",
33 columns=[
34 TableDefinition.Column("Customer ID", SqlType.text(), NOT_NULLABLE),
35 TableDefinition.Column("Customer Name", SqlType.text(), NOT_NULLABLE),
36 TableDefinition.Column("Loyalty Reward Points", SqlType.big_int(), NOT_NULLABLE),
37 TableDefinition.Column("Segment", SqlType.text(), NOT_NULLABLE)
38 ]
39 )
40
41 # Create the table in the Hyper file.
42 connection.catalog.create_table(table_definition=customer_table)
43
44 # Insert data into the table using the Inserter.
45 # The Inserter is the fastest way to insert data into Hyper.
46 with Inserter(connection, customer_table) as inserter:
47 data_to_insert = [
48 ["ABC-123", "Alice", 4500, "Consumer"],
49 ["DEF-456", "Bob", 1200, "Corporate"],
50 ["GHI-789", "Charlie", 3900, "Consumer"]
51 ]
52 inserter.add_rows(rows=data_to_insert)
53 inserter.execute()
54
55 print(f"The table {customer_table.table_name} is created and data is inserted.")
56
57 print("The connection to the Hyper file is closed.")
58 print("The Hyper process has been terminated.")
59
60
61if __name__ == '__main__':
62 try:
63 run_create_hyper_file_from_data()
64 except HyperException as ex:
65 print(ex)