Back to snippets
tableau_hyper_api_create_file_define_schema_insert_data.py
pythonThis example shows how to create a new Hyper file, define a schema, and
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
8def run_create_hyper_file_from_scratch():
9 """
10 An example of how to use the Hyper API to create a Hyper file and insert data into it
11 """
12 path_to_database = "customer.hyper"
13
14 # Starts the Hyper Process with telemetry enabled
15 with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper:
16
17 # Creates a new Hyper file "customer.hyper".
18 # Replaces any existing file with the same name.
19 with Connection(endpoint=hyper.endpoint,
20 database=path_to_database,
21 create_mode=CreateMode.CREATE_AND_REPLACE) as connection:
22
23 schema = TableDefinition(
24 # Since the table name is not prefixed with an explicit schema name,
25 # the table will reside in the default "public" namespace.
26 table_name="Customer",
27 columns=[
28 TableDefinition.Column("Customer ID", SqlType.text(), NOT_NULLABLE),
29 TableDefinition.Column("Customer Name", SqlType.text(), NOT_NULLABLE),
30 TableDefinition.Column("Loyalty Reward Points", SqlType.big_int(), NOT_NULLABLE),
31 TableDefinition.Column("Segment", SqlType.text(), NOT_NULLABLE)
32 ]
33 )
34
35 connection.catalog.create_table(table_definition=schema)
36
37 # Inserter provides the fastest way to write data into a Hyper table
38 with Inserter(connection, schema) as inserter:
39 inserter.add_rows([
40 ["ck-12205", "Chris Krueger", 1234, "Consumer"],
41 ["hc-14965", "Henry Cortney", 522, "Corporate"]
42 ])
43 inserter.execute()
44
45 print("The connection to the Hyper file has been closed.")
46 print("The Hyper process has been shut down.")
47
48if __name__ == '__main__':
49 try:
50 run_create_hyper_file_from_scratch()
51 except Exception as e:
52 print(f"An error occurred: {e}")