Tous les produits
Search
Centre de documentation

Hologres:INSERT OVERWRITE

Dernière mise à jour :Oct 10, 2026

Hologres prend en charge l'instruction INSERT OVERWRITE via la procédure stockée hg_insert_overwrite (V2.0+) et la syntaxe native INSERT OVERWRITE (V3.1+).

Comparaison des fonctionnalités

Le comportement de l'instruction INSERT OVERWRITE varie selon le type de table et la méthode utilisée :

  • Tables non partitionnées : les deux méthodes sont prises en charge.

  • Tables physiquement partitionnées : utilisez la procédure stockée hg_insert_overwrite.

  • Tables logiquement partitionnées : utilisez la procédure stockée hg_insert_overwrite (qui appelle en interne l'instruction native INSERT OVERWRITE).

  • Migration de tables physiquement partitionnées vers des tables logiquement partitionnées : Adapter les nœuds d'importation de données.

Type de table

Élément de comparaison

hg_insert_overwrite

Instruction native INSERT OVERWRITE

Table non partitionnée

Prise en charge

Prise en charge

Table physiquement partitionnée

Importation dans une table parente

  • Importation avec ou sans tables enfants

  • Importation dans des tables enfants spécifiques

Non pris en charge

Importation dans une table enfant

Prise en charge (traitée comme une table non partitionnée)

Prise en charge (traitée comme une table non partitionnée)

Table logiquement partitionnée

Importation dans la table parente (sans spécifier de table enfant)

Non pris en charge

Non pris en charge

Importation dans la table parente (avec une table enfant spécifiée)

Prise en charge

Prise en charge

Remarque

Pour utiliser hg_insert_overwrite ou l'instruction native INSERT OVERWRITE, vérifiez que votre instance répond aux exigences de version. Pour plus d'informations, consultez la rubrique Mettre à niveau une instance. Si vous ne pouvez pas effectuer la mise à niveau, utilisez une table temporaire pour effectuer une opération INSERT OVERWRITE.

Utiliser l'instruction native INSERT OVERWRITE

Aperçu

  • L'instruction native INSERT OVERWRITE est disponible à partir de Hologres V3.1.

  • L'instruction native INSERT OVERWRITE prend en charge les types de table suivants :

    • Tables non partitionnées.

    • Tables enfants de tables physiquement partitionnées (traitées comme des tables non partitionnées).

    • Tables logiquement partitionnées, avec une partition spécifiée.

Contraintes

  • L'instruction native INSERT OVERWRITE active par défaut les transactions DML mixtes : SET hg_experimental_enable_transaction = on;. Pour en savoir plus sur les capacités transactionnelles de Hologres, consultez la rubrique Transactions SQL.

    • Il est impossible de mélanger des instructions INSERT OVERWRITE et DDL au sein d'une même transaction.

    • Toutes les instructions DML d'une transaction sont validées uniquement lors de l'exécution de l'instruction COMMIT.

  • Avant Hologres V4.0, l'instruction native INSERT OVERWRITE ne génère pas de journaux binaires pour les tables ayant activé la journalisation binaire. À partir de Hologres V4.0, cette syntaxe génère des journaux binaires. La génération de journaux binaires peut entraîner une surcharge de stockage importante ; nous vous recommandons donc de la désactiver sauf si elle est nécessaire. Pour désactiver la génération de journaux binaires au niveau de la session, exécutez la commande suivante : SET hg_experimental_generate_binlog = off;.

  • L'atomicité en lecture est garantie par défaut, mais cela entraîne une surcharge métadonnée plus élevée et peut augmenter la latence des requêtes DQL (les entrepôts virtuels secondaires sont davantage affectés). Les opérations INSERT OVERWRITE de longue durée peuvent provoquer des échecs de lecture tels que Data version is inconsistent ou Insert overwrite version not match.

    • Si l'atomicité en lecture n'est pas requise, désactivez le paramètre GUC pour les tâches DQL : set hg_experimental_enable_check_data_version=off. Une tâche DQL pourrait alors analyser un mélange de fichiers de données antérieurs et postérieurs à l'opération INSERT OVERWRITE.

    • Si l'atomicité en lecture est requise mais que vous devez réduire la latence DQL, exécutez les tâches DQL sur l'entrepôt virtuel principal.

Syntaxe

INSERT OVERWRITE <target_table_name> 
  [ PARTITION (<partition_key> = '<partition_value>') [, ...]]
  VALUES ( <expression>  [, ...] ) [, ...] | <query>;

Paramètres

Paramètre

Obligatoire

Description

target_table_name

Oui

Nom de la table cible.

partition_key et partition_value

Non

Clé et valeur de partition. Requis pour les tables logiquement partitionnées.

expression

Non

Expression ou valeur correspondant à la colonne de la table cible.

query

Non

Instruction SELECT dont le résultat écrase les données de la table target_table_name.

Remarque

Si target_table_name est une table logiquement partitionnée et que partition_value spécifie une partition, seules les données appartenant à cette partition seront importées. Les données hors de la partition spécifiée sont ignorées et la partition sera vidée si aucune donnée correspondante n'est trouvée.

Exemples

Importation dans une table non partitionnée

-- Create table A as the target table.
CREATE TABLE public.tablea (
    cid INTEGER NOT NULL,
    cname TEXT,
    code INTEGER
    ,PRIMARY KEY (cid)
);

-- Create table B as the source.
CREATE TABLE public.tableb (
    cid INTEGER NOT NULL,
    cname TEXT,
    code INTEGER
    ,PRIMARY KEY (cid)
);

INSERT INTO public.tableb VALUES(1,'aaa',10001),(2,'bbb','10002');

-- Use the native INSERT OVERWRITE syntax to insert data from table B into table A.
INSERT OVERWRITE public.tablea SELECT * FROM public.tableb;

Importation dans une table logiquement partitionnée

-- Create table A as the target table.
CREATE TABLE public.tablea(
  a TEXT , 
  b INT, 
  c TIMESTAMP, 
  d TEXT,
  ds TEXT,
  PRIMARY KEY(ds,b)
  )
  LOGICAL PARTITION BY LIST(ds);

-- Create physical partitioned table B for the input.
BEGIN;
CREATE TABLE public.tableb(
  a TEXT, 
  b INT, 
  c TIMESTAMP, 
  d TEXT,
  ds TEXT,
  PRIMARY KEY(ds,b)
  )
  PARTITION BY LIST(ds);
CREATE TABLE public.holo_child_3a PARTITION OF public.tableb FOR VALUES IN('20201215');
CREATE TABLE public.holo_child_3b PARTITION OF public.tableb FOR VALUES IN('20201216');
CREATE TABLE public.holo_child_3c PARTITION OF public.tableb FOR VALUES IN('20201217');
COMMIT;

INSERT INTO public.holo_child_3a VALUES('a',1,'2034-10-19','a','20201215');
INSERT INTO public.holo_child_3b VALUES('b',2,'2034-10-20','b','20201216');
INSERT INTO public.holo_child_3c VALUES('c',3,'2034-10-21','c','20201217');

-- Use the native INSERT OVERWRITE syntax to insert data from table B into table A.
INSERT OVERWRITE public.tablea PARTITION (ds = '20201215') SELECT * FROM public.tableb WHERE ds='20201215';

Implémenter INSERT OVERWRITE via hg_insert_overwrite

Historique des versions

  • À partir de la V3.1, hg_insert_overwrite prend en charge les tables logiquement partitionnées (la partition doit être spécifiée).

  • À partir de la V3.0, hg_insert_overwrite permet l'importation directe dans les tables parentes.

  • Tables avec vues dépendantes : pour la V2.0.15+, activez cette fonctionnalité avec : set hg_experimental_hg_insert_overwrite_enable_view=on;. Les dépendances avec des vues matérialisées ne sont pas prises en charge.

    Pour la V3.0+, aucune configuration n'est requise, mais les dépendances avec des vues matérialisées restent non prises en charge.

  • En cas d'échec de hg_insert_overwrite, nettoyez manuellement les tables temporaires. À partir de la V3.0, utilisez le code SQL suivant.

    -- Delete the temporary tables that were created by the system before the time specified by before_time.
    CALL hg_clean_insert_overwrite_tmp_tables(before_time::timestamptz); 

Contraintes d'utilisation

  • Les imports de sous-ensembles de champs doivent respecter l'ordre des colonnes de la table source.

  • hg_insert_overwrite nécessite les autorisations de propriétaire de table (réservé aux superutilisateurs ou aux propriétaires de table).

  • La clé de partition prend en charge les types INT, TEXT ou VARCHAR.

  • À partir de la V3.0, hg_insert_overwrite ne peut pas être utilisé au sein de transactions.

    Remarque

    Dans les versions antérieures, l'utilisation de hg_insert_overwrite dans une transaction risquait de provoquer des interblocages ou des blocages.

  • À partir de la V3.0, le nombre de colonnes et les types de données dans sql de hg_insert_overwrite doivent correspondre exactement à ceux de target_table. Toute incompatibilité génère des erreurs telles que "error: table "hg_alias" has x columns available but x columns specified" or "error: column xx is of type xxx but expression is of type xxx".

Changements de comportement

Si seuls target_table (une table parente) et sql étaient fournis :

Avant la V3.0, cette opération échouait. À partir de la V3.0, les résultats possibles sont les suivants :

  • Si toutes les tables enfants présentes dans les résultats de sql existent, l'opération réussit.

  • Si une table enfant n'existe pas, une erreur se produit.

Syntaxe

-- Before V3.0
CALL hg_insert_overwrite('<target_table>' regclass, ['<partition_value>' TEXT], '<sql>' TEXT);

-- For Hologres V3.0 and later
CALL hg_insert_overwrite('<target_table>' regclass, ['<partition_value>' ARRAY], '<sql>' TEXT, ['<auto_create_partition>' BOOLEAN]);

Paramètres

Remarque

À partir de la V3.0, le paramètre partition_value de hg_insert_overwrite accepte le type ARRAY, ce qui permet d'écrire dans plusieurs tables enfants. Le type TEXT pour partition_value reste pris en charge, mais il est limité à une seule table enfant.

Paramètre

Description

target_table

Table interne Hologres existante.

partition_value

Partition cible.

  • Avant la V3.0 : si target_table est une table physiquement partitionnée, partition_value (type TEXT) est requis. Les partitions inexistantes sont créées automatiquement.

  • À partir de la V3.0 : si target_table est une table physiquement partitionnée, partition_value (type ARRAY ou TEXT) est facultatif. Consultez le tableau de comportement ci-dessous.

  • À partir de la V3.1 : si target_table est une table logiquement partitionnée, partition_value (type ARRAY ou TEXT) est requis.

sql

Instruction SELECT.

Peut interroger des tables MaxCompute ou Hologres. Échappez les guillemets simples avec $$sql$$.

  • Avant la V3.0 : les résultats doivent correspondre exactement à partition_value.

  • À partir de la V3.0 : cette limitation est supprimée. Consultez le tableau de comportement ci-dessous.

auto_create_partition

Contrôle la création automatique des partitions inexistantes. Disponible uniquement à partir de la V3.0, pour les tables physiquement partitionnées uniquement.

  • TRUE : crée automatiquement les partitions manquantes trouvées dans les résultats de sql.

  • FALSE (par défaut) : ne crée pas les partitions manquantes.

Le comportement dépend des paramètres auto_create_partition et partition_value. Une partition est dite « pertinente » si elle apparaît dans les résultats SQL.

  • Comportement de hg_insert_overwrite pour les tables physiquement partitionnées

    Valeur du paramètre

    auto_create_partition

    TRUE

    FALSE

    partition_value

    Non spécifié

    • Partitions pertinentes : les partitions existantes sont écrasées. Les partitions inexistantes sont créées automatiquement.

    • Partitions non pertinentes : ignorées.

    • Si toutes les partitions pertinentes existent déjà :

      • Les partitions pertinentes sont écrasées.

      • Les partitions non pertinentes sont ignorées.

    • Si une partition pertinente n'existe pas, une erreur est générée ; aucune opération d'écrasement n'a lieu sur les autres partitions.

    Spécifié

    Pour les partitions spécifiées :

    • La partition pertinente inexistante est créée automatiquement.

    • Les partitions pertinentes existantes sont écrasées.

    • Les données des partitions non pertinentes et existantes sont effacées.

    Pour les partitions non spécifiées :

    • Aucun effet.

    • Pour les partitions spécifiées :

      • Si une partition pertinente n'existe pas, une erreur est générée ; aucune opération d'écrasement n'a lieu sur les autres partitions.

      • Les partitions pertinentes existantes sont écrasées.

      • Les partitions existantes et non pertinentes sont effacées.

    • Pour les partitions non spécifiées :

      • Aucun effet.

  • Comportement de hg_insert_overwrite pour les tables logiquement partitionnées

    Les tables logiquement partitionnées ne prennent pas en charge le partitionnement automatique ; le paramètre auto_create_partition est ignoré.

    Valeur du paramètre

    Description

    partition_value

    Non spécifié

    Non pris en charge.

    Spécifié

    Pour les partitions spécifiées :

    • Les données de la partition pertinente sont écrasées.

    • Les partitions non pertinentes sont effacées.

    Pour les partitions non spécifiées :

    • Aucune n'est affectée.

Exemples

Exemple 1 : Importer des données dans une table non partitionnée

-- Create table A as the target table.
BEGIN;

CREATE TABLE public.tablea (
    cid INTEGER NOT NULL,
    cname TEXT,
    code INTEGER
    ,PRIMARY KEY (cid)
);

CALL set_table_property('public.tablea', 'orientation', 'column');
CALL set_table_property('public.tablea', 'storage_format', 'orc');
CALL set_table_property('public.tablea', 'bitmap_columns', 'cname');
CALL set_table_property('public.tablea', 'dictionary_encoding_columns', 'cname:auto');
CALL set_table_property('public.tablea', 'distribution_key', 'cid');
CALL set_table_property('public.tablea', 'time_to_live_in_seconds', '3153600000');
COMMIT;

-- Create table B for data input.
CREATE TABLE public.tableb (
    cid INTEGER NOT NULL,
    cname TEXT,
    code INTEGER
    ,PRIMARY KEY (cid)
);

INSERT INTO public.tableb VALUES(1,'aaa',10001),(2,'bbb','10002');

-- Insert data from table B into table A.
CALL hg_insert_overwrite('public.tablea' , 'SELECT * FROM public.tableb');

Exemple 2 : Importer des données dans une table partitionnée (physique et logique)

-- Create the target table.
BEGIN;
CREATE TABLE public.tableA(
  a TEXT, 
  b INT, 
  c TIMESTAMP, 
  d TEXT,
  ds TEXT,
  PRIMARY KEY(ds,b)
  )
  PARTITION BY LIST(ds);
CALL set_table_property('public.tableA', 'orientation', 'column');
CREATE TABLE public.holo_child_1 PARTITION OF public.tableA FOR VALUES IN('20201215');
CREATE TABLE public.holo_child_2 PARTITION OF public.tableA FOR VALUES IN('20201216');
CREATE TABLE public.holo_child_3 PARTITION OF public.tableA FOR VALUES IN('20201217');
COMMIT;

-- Or, a logical partitioned table.
CREATE TABLE public.tableA_lp(
  a TEXT, 
  b INT, 
  c TIMESTAMP, 
  d TEXT,
  ds TEXT,
  PRIMARY KEY(ds,b)
  )
  LOGICAL PARTITION BY LIST(ds);

-- Create table B for input.
BEGIN;
CREATE TABLE public.tableB(
  a TEXT, 
  b INT, 
  c TIMESTAMP, 
  d TEXT,
  ds TEXT,
  PRIMARY KEY(ds,b)
  )
  PARTITION BY LIST(ds);
CALL set_table_property('public.tableB', 'orientation', 'column');
CREATE TABLE public.holo_child_3a PARTITION OF public.tableB FOR VALUES IN('20201215');
CREATE TABLE public.holo_child_3b PARTITION OF public.tableB FOR VALUES IN('20201216');
CREATE TABLE public.holo_child_3c PARTITION OF public.tableB FOR VALUES IN('20201217');
COMMIT;

INSERT INTO public.holo_child_3a VALUES('a',1,'2034-10-19','a','20201215');
INSERT INTO public.holo_child_3b VALUES('b',2,'2034-10-20','b','20201216');
INSERT INTO public.holo_child_3c VALUES('c',3,'2034-10-21','c','20201217');

-- Physical partitioned table
CALL hg_insert_overwrite('public.tableA' , '{20201215,20201216,20201217}'::text[],$$SELECT * FROM public.tableB$$);
-- Logical partitioned table
CALL hg_insert_overwrite('public.tableA_lp' , '{20201215,20201216,20201217}'::text[],$$SELECT * FROM public.tableB$$);

Exemple 3 : Importer des données d'une table non partitionnée MaxCompute vers une table non partitionnée Hologres

-- Create a non-partitioned table in MaxCompute. This example uses data from the customer table in the public_data project, which is a public dataset in MaxCompute. The following code provides the DDL statement for the table.
CREATE TABLE IF NOT EXISTS public_data.customer(
  c_customer_sk BIGINT,
  c_customer_id STRING,
  c_current_cdemo_sk BIGINT,
  c_current_hdemo_sk BIGINT,
  c_current_addr_sk BIGINT,
  c_first_shipto_date_sk BIGINT,
  c_first_sales_date_sk BIGINT,
  c_salutation STRING,
  c_first_name STRING,
  c_last_name STRING,
  c_preferred_cust_flag STRING,
  c_birth_day BIGINT,
  c_birth_month BIGINT,
  c_birth_year BIGINT,
  c_birth_country STRING,
  c_login STRING,
  c_email_address STRING,
  c_last_review_date STRING,
  useless STRING);

-- Create a foreign table in Hologres to map to the source data table in MaxCompute.
CREATE FOREIGN TABLE customer (
    "c_customer_sk" INT8,
    "c_customer_id" TEXT,
    "c_current_cdemo_sk" INT8,
    "c_current_hdemo_sk" INT8,
    "c_current_addr_sk" INT8,
    "c_first_shipto_date_sk" INT8,
    "c_first_sales_date_sk" INT8,
    "c_salutation" TEXT,
    "c_first_name" TEXT,
    "c_last_name" TEXT,
    "c_preferred_cust_flag" TEXT,
    "c_birth_day" INT8,
    "c_birth_month" INT8,
    "c_birth_year" INT8,
    "c_birth_country" TEXT,
    "c_login" TEXT,
    "c_email_address" TEXT,
    "c_last_review_date" TEXT,
    "useless" TEXT
)
SERVER odps_server
OPTIONS (project_name 'public_data', table_name 'customer');

-- Create an internal table in Hologres, such as a column-oriented table, to receive data from the MaxCompute source table.
BEGIN;
CREATE TABLE public.holo_customer (
 "c_customer_sk" INT8,
 "c_customer_id" TEXT,
 "c_current_cdemo_sk" INT8,
 "c_current_hdemo_sk" INT8,
 "c_current_addr_sk" INT8,
 "c_first_shipto_date_sk" INT8,
 "c_first_sales_date_sk" INT8,
 "c_salutation" TEXT,
 "c_first_name" TEXT,
 "c_last_name" TEXT,
 "c_preferred_cust_flag" TEXT,
 "c_birth_day" INT8,
 "c_birth_month" INT8,
 "c_birth_year" INT8,
 "c_birth_country" TEXT,
 "c_login" TEXT,
 "c_email_address" TEXT,
 "c_last_review_date" TEXT,
 "useless" TEXT
);
COMMIT;

-- Import data into Hologres.
IMPORT FOREIGN SCHEMA <project_name> LIMIT TO
(customer) FROM server odps_server INTO PUBLIC options(if_table_exist 'update');-- Update the foreign table.
SELECT pg_sleep(30);-- Wait for some time before you import data to Hologres. This prevents synchronization failures that are caused by data inconsistency due to slow updates of the metadata cache in Hologres.

CALL  hg_insert_overwrite('holo_customer', 'SELECT * FROM customer where c_birth_year > 1980');

-- Query data from the MaxCompute source table in Hologres.
SELECT * FROM holo_customer limit 10;

Exemple 4 : Importer des données d'une table partitionnée MaxCompute vers une partition physique Hologres

-- Create a partitioned table in MaxCompute.
DROP TABLE IF EXISTS odps_sale_detail;

CREATE TABLE IF NOT EXISTS odps_sale_detail 
(
    shop_name STRING
    ,customer_id STRING
    ,total_price DOUBLE
)
PARTITIONED BY 
(
    sale_date STRING
)
;

-- Add the 20210815 partition to the source table.
ALTER TABLE odps_sale_detail ADD IF NOT EXISTS PARTITION(sale_date='20210815')
;

-- Write data to the partition.
INSERT OVERWRITE TABLE odps_sale_detail PARTITION(sale_date='20210815') VALUES 
('s1','c1',100.1),
('s2','c2',100.2),
('s3','c3',100.3)
;

-- Create a foreign table in Hologres to map to the source data table in MaxCompute.
DROP FOREIGN TABLE IF EXISTS odps_sale_detail;

-- Create a foreign table.
IMPORT FOREIGN SCHEMA <maxcompute_project> LIMIT TO
(
    odps_sale_detail
) 
FROM SERVER odps_server INTO public 
OPTIONS(if_table_exist 'error',if_unsupported_type 'error');

-- Create an internal table in Hologres to receive data from the MaxCompute source table.
DROP TABLE IF EXISTS holo_sale_detail;

-- Create a partitioned table (internal table) in Hologres.
BEGIN ;
CREATE TABLE IF NOT EXISTS holo_sale_detail
(
    shop_name TEXT
    ,customer_id TEXT 
    ,total_price FLOAT8
    ,sale_date TEXT
)
PARTITION BY LIST(sale_date);
COMMIT;

-- Import data into Hologres.
CALL hg_insert_overwrite('holo_sale_detail', '20210815', $$SELECT * FROM public.odps_sale_detail WHERE sale_date='20210815'$$);

-- Query data from the MaxCompute source table in Hologres.
SELECT * FROM holo_sale_detail;

Exemple 5 : Importer des données d'une table partitionnée MaxCompute vers une table physiquement partitionnée Hologres

-- Create a partitioned table in MaxCompute.
DROP TABLE IF EXISTS odps_sale_detail;

CREATE TABLE IF NOT EXISTS odps_sale_detail 
(
    shop_name STRING
    ,customer_id STRING
    ,total_price DOUBLE
)
PARTITIONED BY 
(
    sale_date STRING
)
;

-- Add the 20210815 and 20210816 partitions to the source table.
ALTER TABLE odps_sale_detail ADD IF NOT EXISTS PARTITION(sale_date='20210815')
;
ALTER TABLE odps_sale_detail ADD IF NOT EXISTS PARTITION(sale_date='20210816')
;

-- Write data to the partitions.
INSERT OVERWRITE TABLE odps_sale_detail PARTITION(sale_date='20210815') VALUES 
('s1','c1',100.1),
('s2','c2',100.2),
('s3','c3',100.3)
;
INSERT OVERWRITE TABLE odps_sale_detail PARTITION(sale_date='20210816') VALUES 
('s1','c1',100.1),
('s2','c2',100.2),
('s3','c3',100.3)
;

-- Create a foreign table in Hologres to map to the source data table in MaxCompute.
DROP FOREIGN TABLE IF EXISTS odps_sale_detail;

-- Create a foreign table.
IMPORT FOREIGN SCHEMA <maxcompute_project> LIMIT TO
(
    odps_sale_detail
) 
FROM SERVER odps_server INTO public 
OPTIONS(if_table_exist 'error',if_unsupported_type 'error');

-- Create an internal table in Hologres to receive data from the MaxCompute source table.
DROP TABLE IF EXISTS holo_sale_detail;

-- Create a partitioned table (internal table) in Hologres.
BEGIN ;
CREATE TABLE IF NOT EXISTS holo_sale_detail
(
    shop_name TEXT
    ,customer_id TEXT 
    ,total_price FLOAT8
    ,sale_date TEXT
)
PARTITION BY LIST(sale_date);
COMMIT;

-- Import data into Hologres. Do not specify child partitions and set auto_create_partition to TRUE. The system automatically creates two child partitions and imports data.
CALL hg_insert_overwrite ('holo_sale_detail', $$SELECT * FROM public.odps_sale_detail$$, TRUE);

-- Query data in Hologres.
SELECT * FROM holo_sale_detail;
Remarque

maxcompute_project : nom du projet où se trouve la table partitionnée MaxCompute.

Implémenter INSERT OVERWRITE via une table temporaire

Syntaxe

Utilisez le code SQL suivant pour implémenter l'instruction INSERT OVERWRITE.

BEGIN ;

-- Clear potential temporary tables.
DROP TABLE IF EXISTS <table_new>;

-- Create a temporary table.
SET hg_experimental_enable_create_table_like_properties=on;
CALL HG_CREATE_TABLE_LIKE ('<table_new>', 'select * from <table>');

COMMIT ;

-- Insert data into the temporary table.
INSERT INTO <table_new> [( <column> [, ...] )]
VALUES ( {<expression>}  [, ...] )
[, ...] | <query>}

ANALYZE <table_new>;

BEGIN ;

-- Delete the old table.
DROP TABLE IF EXISTS  <table>;

-- Rename the temporary table.
ALTER TABLE <table_new> RENAME TO <table>;

COMMIT ;

Paramètres

Paramètre

Description

table_new

Nom de la table temporaire.

Prend en charge le format Schema.Table.

table

Nom de la table existante.

Prend en charge le format Schema.Table

DDL de la table temporaire

Il existe deux façons de créer une table temporaire :

  • Copie depuis une table existante :

    SET hg_experimental_enable_create_table_like_properties=on;
    CALL HG_CREATE_TABLE_LIKE ('<table_new>', 'select * from <table>');
  • Création à partir de zéro :

    CREATE TABLE IF NOT EXISTS <table_new> ([
          {
           column_name column_type [column_constraints, [...]]
           | table_constraints
           [, ...]
          }
        ]);
    
        CALL set_table_property('<table_new>', property, value);

Exemples d'interaction avec MaxCompute

Importation vers Hologres (non partitionné)

Écrasez les données Hologres avec les résultats par lots de MaxCompute. Cet exemple écrase complètement la table Hologres region en utilisant la table odps_region_10g de MaxCompute.

BEGIN ;

-- Clear the existing temporary table.
DROP TABLE IF EXISTS public.region_new;

-- Create a temporary table.
SET hg_experimental_enable_create_table_like_properties=on;
CALL HG_CREATE_TABLE_LIKE ('public.region_new', 'select * from public.region');
COMMIT ;

-- Insert data into the temporary table.
INSERT INTO public.region_new
SELECT *
FROM public.odps_region_10g;

ANALYZE public.region_new;

BEGIN ;

-- Drop the old table.
DROP TABLE IF EXISTS public.region;

-- Rename the temporary table.
ALTER TABLE IF EXISTS public.region_new RENAME TO region;

COMMIT ;

Importation vers Hologres (partitionné)

Les mises à jour quotidiennes d'une table partitionnée MaxCompute peuvent écraser une table partitionnée Hologres afin de corriger les données en temps réel avec les résultats traités par lots. Cet exemple importe les données de la table odps_lineitem_10g de MaxCompute (partitionnée quotidiennement par ds) vers la table lineitem de Hologres.

BEGIN ;

-- Clear potential temporary tables.
DROP TABLE IF EXISTS public.lineitem_new_20210101;

-- Create a temporary table.
SET hg_experimental_enable_create_table_like_properties=on;
CALL HG_CREATE_TABLE_LIKE ('public.lineitem_new_20210101', 'select * from public.lineitem');
COMMIT ;

-- Insert data into the temporary table.
INSERT INTO public.lineitem_new_20210101
SELECT *
FROM public.odps_lineitem_10g
WHERE DS = '20210101'

ANALYZE public.lineitem_new_20210101;

BEGIN ;

-- Delete the old partition.
DROP TABLE IF EXISTS public.lineitem_20210101;

-- Rename the temporary table.
ALTER TABLE public.lineitem_new_20210101 RENAME TO lineitem_20210101;

-- Attach the temporary table to the specified partitioned table.
ALTER TABLE public.lineitem ATTACH PARTITION lineitem_20210101 FOR VALUES IN ('20210101');

COMMIT ;

Importation vers MaxCompute (non partitionné)

Pour exporter des données de Hologres (holotable) vers la table mc_holotable de MaxCompute, écrivez d'abord dans une table temporaire, puis renommez-la pour écraser complètement mc_holotable.

-- Create a temporary table for the sink table in MaxCompute.
CREATE  TABLE if not exists mc_holotable_temp(
    age INT,
    job STRING,
    name STRING
);

-- Create a mapping for the temporary table in Hologres.
CREATE FOREIGN TABLE "public"."mapping_holotable_temp" (
 "age" INT,
 "job" TEXT,
 "name" TEXT
)
SERVER odps_server
OPTIONS (project_name 'DLF_test',table_name 'mc_holotable_temp');
-- Update the source table in Hologres.
UPDATE holotable SET "job" = 'president' WHERE "name" = 'Lily';
-- Write the updated data to the mapping of the temporary table.
INSERT INTO mapping_holotable_temp SELECT * FROM holotable;

-- Delete the old sink table in MaxCompute.
DROP TABLE IF EXISTS mc_holotable;
-- Rename the temporary table to the sink table.
ALTER TABLE mc_holotable_temp RENAME TO mc_holotable;

L'importation de données prend en charge à la fois l'importation partielle et complète :

  • Exportation de certains champs :

    INSERT INTO mapping_holotable_temp
    SELECT x,x,x FROM holotable;  --You can replace x,x,x with the names of the fields that you want to export.
  • Exportation de tous les champs :

    INSERT INTO mapping_holotable_temp
    SELECT * FROM holotable;