Update a materialized view

Use the API to change materialized view properties.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Go

Before trying this sample, follow the Go setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Go API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import (
	"context"
	"fmt"
	"time"

	"cloud.google.com/go/bigquery"
)

// updateMaterializedView updates a materialized view by manipulating MV properties.
func updateMaterializedView(projectID, datasetID, viewID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// viewID := "myview"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Retrieve current view metadata.
	viewRef := client.Dataset(datasetID).Table(viewID)
	meta, err := viewRef.Metadata(ctx)
	if err != nil {
		return fmt.Errorf("couldn't retrieve view metadata: %w", err)
	}

	if meta.MaterializedView == nil {
		return fmt.Errorf("provided view %q is not a materialized view", viewID)
	}

	// construct an updated MV definition.
	newMV := &bigquery.MaterializedViewDefinition{
		Query:           meta.MaterializedView.Query,
		EnableRefresh:   true,
		RefreshInterval: meta.MaterializedView.RefreshInterval + time.Minute,
	}

	// Issue the update to alter the view.
	_, err = viewRef.Update(ctx, bigquery.TableMetadataToUpdate{
		MaterializedView: newMV,
	}, meta.ETag)
	if err != nil {
		return fmt.Errorf("Update(): %w", err)
	}
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Java API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.MaterializedViewDefinition;
import com.google.cloud.bigquery.Table;
import com.google.cloud.bigquery.TableId;

// Sample to update materialized view
public class UpdateMaterializedView {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String materializedViewName = "MY_MATERIALIZED_VIEW_NAME";
    updateMaterializedView(datasetName, materializedViewName);
  }

  public static void updateMaterializedView(String datasetName, String materializedViewName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      TableId tableId = TableId.of(datasetName, materializedViewName);

      // Get existing materialized view
      Table table = bigquery.getTable(tableId);
      MaterializedViewDefinition materializedViewDefinition = table.getDefinition();
      // Update materialized view
      materializedViewDefinition
          .toBuilder()
          .setEnableRefresh(true)
          .setRefreshIntervalMs(1000L)
          .build();
      table.toBuilder().setDefinition(materializedViewDefinition).build().update();
      System.out.println("Materialized view updated successfully");
    } catch (BigQueryException e) {
      System.out.println("Materialized view was not updated. \n" + e.toString());
    }
  }
}

Python

Before trying this sample, follow the Python setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Python API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import datetime

from google.cloud import bigquery

bigquery_client = bigquery.Client()

view_id = "my-project.my_dataset.my_materialized_view"
view = bigquery.Table(view_id)
view.mview_enable_refresh = True
view.mview_refresh_interval = datetime.timedelta(hours=1)

# Make an API request to update the materialized view.
view = bigquery_client.update_table(
    view,
    # Pass in a list of any fields you need to modify.
    ["mview_enable_refresh", "mview_refresh_interval"],
)
print(f"Updated {view.table_type}: {str(view.reference)}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.