Getting started with Spanner in Java Stay organized with collections Save and categorize content based on your preferences.
Objectives
This tutorial walks you through the following steps using the Spannerclient library for Java:
- Create a Spanner instance and database.
- Write, read, and execute SQL queries on data in the database.
- Update the database schema.
- Update data using a read-write transaction.
- Add a secondary index to the database.
- Use the index to read and execute SQL queries on data.
- Retrieve data using a read-only transaction.
Costs
This tutorial uses Spanner, which is a billable component of theGoogle Cloud. For information on the cost of using Spanner, seePricing.
Before you begin
Complete the steps described inSet up, which cover creating andsetting a default Google Cloud project, enabling billing, enabling theCloud Spanner API, and setting up OAuth 2.0 to get authentication credentials to usethe Cloud Spanner API.
In particular, make sure that you rungcloud authapplication-default loginto set up your local development environment with authenticationcredentials.
Prepare your local Java environment
Install the following on your development machine if they are not already installed:
Clone the sample app repository to your local machine:
gitclonehttps://github.com/googleapis/java-spanner.gitChange to the directory that contains the Spanner sample code:
cdjava-spanner/samples/snippetsGenerate the sample JAR file:
mvncleanpackage
Create an instance
When you first use Spanner, you must create an instance, which is anallocation of resources that are used by Spanner databases. When youcreate an instance, you choose aninstance configuration, which determineswhere your data is stored, and also the number of nodes to use, which determinesthe amount of serving and storage resources in your instance.
SeeCreate an instanceto learn how to create a Spanner instance using any of thefollowing methods. You can name your instancetest-instance to use it withother topics in this document that reference an instance namedtest-instance.
- The Google Cloud CLI
- The Google Cloud console
- A client library (C++, C#, Go, Java, Node.js, PHP, Python, or Ruby)
Look through sample files
The samples repository contains a sample that shows how to use Spannerwith Java.
Create a database
GoogleSQL
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\createdatabasetest-instanceexample-dbPostgreSQL
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\createpgdatabasetest-instanceexample-dbYou should see:
Createddatabase[example-db]GoogleSQL
staticvoidcreateDatabase(DatabaseAdminClientdbAdminClient,InstanceNameinstanceName,StringdatabaseId){CreateDatabaseRequestcreateDatabaseRequest=CreateDatabaseRequest.newBuilder().setCreateStatement("CREATE DATABASE `"+databaseId+"`").setParent(instanceName.toString()).addAllExtraStatements(Arrays.asList("CREATE TABLE Singers ("+" SingerId INT64 NOT NULL,"+" FirstName STRING(1024),"+" LastName STRING(1024),"+" SingerInfo BYTES(MAX),"+" FullName STRING(2048) AS "+" (ARRAY_TO_STRING([FirstName, LastName], \" \")) STORED"+") PRIMARY KEY (SingerId)","CREATE TABLE Albums ("+" SingerId INT64 NOT NULL,"+" AlbumId INT64 NOT NULL,"+" AlbumTitle STRING(MAX)"+") PRIMARY KEY (SingerId, AlbumId),"+" INTERLEAVE IN PARENT Singers ON DELETE CASCADE")).build();try{// Initiate the request which returns an OperationFuture.com.google.spanner.admin.database.v1.Databasedb=dbAdminClient.createDatabaseAsync(createDatabaseRequest).get();System.out.println("Created database ["+db.getName()+"]");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}PostgreSQL
staticvoidcreatePostgreSqlDatabase(DatabaseAdminClientdbAdminClient,StringprojectId,StringinstanceId,StringdatabaseId){finalCreateDatabaseRequestrequest=CreateDatabaseRequest.newBuilder().setCreateStatement("CREATE DATABASE \""+databaseId+"\"").setParent(InstanceName.of(projectId,instanceId).toString()).setDatabaseDialect(DatabaseDialect.POSTGRESQL).build();try{// Initiate the request which returns an OperationFuture.Databasedb=dbAdminClient.createDatabaseAsync(request).get();System.out.println("Created database ["+db.getName()+"]");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}staticvoidcreateTableUsingDdl(DatabaseAdminClientdbAdminClient,DatabaseNamedatabaseName){try{// Initiate the request which returns an OperationFuture.dbAdminClient.updateDatabaseDdlAsync(databaseName,Arrays.asList("CREATE TABLE Singers ("+" SingerId bigint NOT NULL,"+" FirstName character varying(1024),"+" LastName character varying(1024),"+" SingerInfo bytea,"+" FullName character varying(2048) GENERATED "+" ALWAYS AS (FirstName || ' ' || LastName) STORED,"+" PRIMARY KEY (SingerId)"+")","CREATE TABLE Albums ("+" SingerId bigint NOT NULL,"+" AlbumId bigint NOT NULL,"+" AlbumTitle character varying(1024),"+" PRIMARY KEY (SingerId, AlbumId)"+") INTERLEAVE IN PARENT Singers ON DELETE CASCADE")).get();System.out.println("Created Singers & Albums tables in database: ["+databaseName+"]");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throwSpannerExceptionFactory.asSpannerException(e);}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}The next step is to write data to your database.
Create a database client
Before you can do reads or writes, you must create aDatabaseClient.You can think of aDatabaseClient as a database connection: all of yourinteractions with Spanner must go through aDatabaseClient. Typicallyyou create aDatabaseClient when your application starts up, then you re-usethatDatabaseClient to read, write, and execute transactions.SpannerOptionsoptions=SpannerOptions.newBuilder().build();Spannerspanner=options.getService();DatabaseAdminClientdbAdminClient=null;try{DatabaseClientdbClient=spanner.getDatabaseClient(db);dbAdminClient=spanner.createDatabaseAdminClient();}finally{if(dbAdminClient!=null){if(!dbAdminClient.isShutdown()||!dbAdminClient.isTerminated()){dbAdminClient.close();}}spanner.close();}Each client uses resources in Spanner, so it is good practice to closeunneeded clients by callingclose().
Read more in theDatabaseClientJavadoc reference.
Write data with DML
You can insert data using Data Manipulation Language (DML) in a read-writetransaction.
You use theexecuteUpdate() method to execute a DML statement.
staticvoidwriteUsingDml(DatabaseClientdbClient){// Insert 4 singer recordsdbClient.readWriteTransaction().run(transaction->{Stringsql="INSERT INTO Singers (SingerId, FirstName, LastName) VALUES "+"(12, 'Melissa', 'Garcia'), "+"(13, 'Russell', 'Morales'), "+"(14, 'Jacqueline', 'Long'), "+"(15, 'Dylan', 'Shaw')";longrowCount=transaction.executeUpdate(Statement.of(sql));System.out.printf("%d records inserted.\n",rowCount);returnnull;});}Run the sample using thewriteusingdml argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\writeusingdmltest-instanceexample-dbYou should see:
4recordsinserted.Write data with mutations
You can also insert data usingmutations.
You can write data usingaMutation object.AMutation object is a container for mutation operations. AMutationrepresents a sequence of inserts, updates, and deletes that Spannerapplies atomically to different rows and tables in a Spanner database.
ThenewInsertBuilder()method in theMutation class constructs anINSERT mutation, which inserts anew row in a table. If the row already exists, the write fails. Alternatively,you can use thenewInsertOrUpdateBuildermethod to construct anINSERT_OR_UPDATE mutation, which updates column valuesif the row already exists.
write()method in theDatabaseClient class writes the mutations. All mutations in asingle batch are applied atomically.This code shows how to write the data using mutations:
staticfinalList<Singer>SINGERS=Arrays.asList(newSinger(1,"Marc","Richards"),newSinger(2,"Catalina","Smith"),newSinger(3,"Alice","Trentor"),newSinger(4,"Lea","Martin"),newSinger(5,"David","Lomond"));staticfinalList<Album>ALBUMS=Arrays.asList(newAlbum(1,1,"Total Junk"),newAlbum(1,2,"Go, Go, Go"),newAlbum(2,1,"Green"),newAlbum(2,2,"Forever Hold Your Peace"),newAlbum(2,3,"Terrified"));staticvoidwriteExampleData(DatabaseClientdbClient){List<Mutation>mutations=newArrayList<>();for(Singersinger:SINGERS){mutations.add(Mutation.newInsertBuilder("Singers").set("SingerId").to(singer.singerId).set("FirstName").to(singer.firstName).set("LastName").to(singer.lastName).build());}for(Albumalbum:ALBUMS){mutations.add(Mutation.newInsertBuilder("Albums").set("SingerId").to(album.singerId).set("AlbumId").to(album.albumId).set("AlbumTitle").to(album.albumTitle).build());}dbClient.write(mutations);}Run the sample using thewrite argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\writetest-instanceexample-dbYou should see the command run successfully.
Note: There are limits to commit size. SeeCRUD limitfor more information.Query data using SQL
Spanner supports a SQL interface for reading data, which you canaccess on the command line using the Google Cloud CLI orprogrammatically usingthe Spanner client library for Java.
On the command line
Execute the following SQL statement to read the values of all columns from theAlbums table:
gcloudspannerdatabasesexecute-sqlexample-db--instance=test-instance\--sql='SELECTSingerId,AlbumId,AlbumTitleFROMAlbums'The result shows:
SingerIdAlbumIdAlbumTitle11TotalJunk12Go,Go,Go21Green22ForeverHoldYourPeace23TerrifiedUse the Spanner client library for Java
In addition to executing a SQL statement on the command line, you can issue thesame SQL statement programmatically using the Spanner client library forJava.
The following methods and classes are used to run the SQL query:- The
singleUse()method in theDatabaseClientclass: use this to read the value of one or morecolumns from one or more rows in a Spanner table.singleUse()returnsaReadContextobject, which is used for running a read or SQL statement. - The
executeQuery()method of theReadContextclass: use this method to execute a query againsta database. - The
Statementclass: use this to construct a SQL string. - The
ResultSetclass: use this to access the data returned by a SQL statement or read call.
Here's how to issue the query and access the data:
staticvoidquery(DatabaseClientdbClient){try(ResultSetresultSet=dbClient.singleUse()// Execute a single read or query against Cloud Spanner..executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))){while(resultSet.next()){System.out.printf("%d %d %s\n",resultSet.getLong(0),resultSet.getLong(1),resultSet.getString(2));}}}Run the sample using thequery argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\querytest-instanceexample-dbYou should see the following result:
11TotalJunk12Go,Go,Go21Green22ForeverHoldYourPeace23TerrifiedQuery using a SQL parameter
If your application has a frequently executed query, you can improve its performanceby parameterizing it. The resulting parametric query can be cached and reused, whichreduces compilation costs. For more information, seeUse query parameters to speed up frequently executed queries.
Here is an example of using a parameter in theWHERE clause toquery records containing a specific value forLastName.
GoogleSQL
staticvoidqueryWithParameter(DatabaseClientdbClient){Statementstatement=Statement.newBuilder("SELECT SingerId, FirstName, LastName "+"FROM Singers "+"WHERE LastName = @lastName").bind("lastName").to("Garcia").build();try(ResultSetresultSet=dbClient.singleUse().executeQuery(statement)){while(resultSet.next()){System.out.printf("%d %s %s\n",resultSet.getLong("SingerId"),resultSet.getString("FirstName"),resultSet.getString("LastName"));}}}PostgreSQL
staticvoidqueryWithParameter(DatabaseClientdbClient){Statementstatement=Statement.newBuilder("SELECT singerid AS \"SingerId\", "+"firstname as \"FirstName\", lastname as \"LastName\" "+"FROM Singers "+"WHERE LastName = $1").bind("p1").to("Garcia").build();try(ResultSetresultSet=dbClient.singleUse().executeQuery(statement)){while(resultSet.next()){System.out.printf("%d %s %s\n",resultSet.getLong("SingerId"),resultSet.getString("FirstName"),resultSet.getString("LastName"));}}}Run the sample using the queryWithParameter argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\querywithparametertest-instanceexample-dbYou should see the following result:
12MelissaGarciaRead data using the read API
In addition to Spanner's SQL interface, Spanner also supports aread interface.
Use theread()method of theReadContext class to read rows from the database. Use aKeySetobject to define a collection of keys and key ranges to read.Here's how to read the data:
staticvoidread(DatabaseClientdbClient){try(ResultSetresultSet=dbClient.singleUse().read("Albums",KeySet.all(),// Read all rows in a table.Arrays.asList("SingerId","AlbumId","AlbumTitle"))){while(resultSet.next()){System.out.printf("%d %d %s\n",resultSet.getLong(0),resultSet.getLong(1),resultSet.getString(2));}}}Run the sample using theread argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\readtest-instanceexample-dbYou should see output similar to:
11TotalJunk12Go,Go,Go21Green22ForeverHoldYourPeace23TerrifiedUpdate the database schema
Assume you need to add a new column calledMarketingBudget to theAlbumstable. Adding a new column to an existing table requires an update to yourdatabase schema. Spanner supports schema updates to a database while thedatabase continues to serve traffic. Schema updates don't require taking thedatabase offline and they don't lock entire tables or columns; you can continuewriting data to the database during the schema update. Read more about supportedschema updates and schema change performance inMake schema updates.
Add a column
You can add a column on the command line using the Google Cloud CLI orprogrammatically usingthe Spanner client library for Java.
On the command line
Use the followingALTER TABLE command toadd the new column to the table:
GoogleSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance\--ddl='ALTERTABLEAlbumsADDCOLUMNMarketingBudgetINT64'PostgreSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance\--ddl='ALTERTABLEAlbumsADDCOLUMNMarketingBudgetBIGINT'You should see:
Schemaupdating...done.Use the Spanner client library for Java
Use theupdateDatabaseDdl()method of theDatabaseAdminClient class to modify the schema:GoogleSQL
staticvoidaddMarketingBudget(DatabaseAdminClientadminClient,DatabaseNamedatabaseName){try{// Initiate the request which returns an OperationFuture.adminClient.updateDatabaseDdlAsync(databaseName,Arrays.asList("ALTER TABLE Albums ADD COLUMN MarketingBudget INT64")).get();System.out.println("Added MarketingBudget column");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}PostgreSQL
staticvoidaddMarketingBudget(DatabaseAdminClientadminClient,DatabaseNamedatabaseName){try{// Initiate the request which returns an OperationFuture.adminClient.updateDatabaseDdlAsync(databaseName,Arrays.asList("ALTER TABLE Albums ADD COLUMN MarketingBudget bigint")).get();System.out.println("Added MarketingBudget column");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}Run the sample using theaddmarketingbudget argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\addmarketingbudgettest-instanceexample-dbYou should see:
AddedMarketingBudgetcolumn.Write data to the new column
The following code writes data to the new column. It setsMarketingBudget to100000 for the row keyed byAlbums(1, 1) and to500000 for the row keyedbyAlbums(2, 2).
staticvoidupdate(DatabaseClientdbClient){// Mutation can be used to update/insert/delete a single row in a table. Here we use// newUpdateBuilder to create update mutations.List<Mutation>mutations=Arrays.asList(Mutation.newUpdateBuilder("Albums").set("SingerId").to(1).set("AlbumId").to(1).set("MarketingBudget").to(100000).build(),Mutation.newUpdateBuilder("Albums").set("SingerId").to(2).set("AlbumId").to(2).set("MarketingBudget").to(500000).build());// This writes all the mutations to Cloud Spanner atomically.dbClient.write(mutations);}Run the sample using theupdate argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\updatetest-instanceexample-dbYou can also execute a SQL query or a read call to fetch the values that youjust wrote.
Here's the code to execute the query:
GoogleSQL
staticvoidqueryMarketingBudget(DatabaseClientdbClient){// Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to// null. A try-with-resource block is used to automatically release resources held by// ResultSet.try(ResultSetresultSet=dbClient.singleUse().executeQuery(Statement.of("SELECT SingerId, AlbumId, MarketingBudget FROM Albums"))){while(resultSet.next()){System.out.printf("%d %d %s\n",resultSet.getLong("SingerId"),resultSet.getLong("AlbumId"),// We check that the value is non null. ResultSet getters can only be used to retrieve// non null values.resultSet.isNull("MarketingBudget")?"NULL":resultSet.getLong("MarketingBudget"));}}}PostgreSQL
staticvoidqueryMarketingBudget(DatabaseClientdbClient){// Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to// null. A try-with-resource block is used to automatically release resources held by// ResultSet.try(ResultSetresultSet=dbClient.singleUse().executeQuery(Statement.of("SELECT singerid as \"SingerId\", "+"albumid as \"AlbumId\", marketingbudget as \"MarketingBudget\" "+"FROM Albums"))){while(resultSet.next()){System.out.printf("%d %d %s\n",resultSet.getLong("SingerId"),resultSet.getLong("AlbumId"),// We check that the value is non null. ResultSet getters can only be used to retrieve// non null values.resultSet.isNull("MarketingBudget")?"NULL":resultSet.getLong("MarketingBudget"));}}}To execute this query, run the sample using thequerymarketingbudget argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\querymarketingbudgettest-instanceexample-dbYou should see:
1110000012NULL21NULL2250000023NULLUpdate data
You can update data using DML in a read-write transaction.
You use theexecuteUpdate()method to execute a DML statement.
GoogleSQL
staticvoidwriteWithTransactionUsingDml(DatabaseClientdbClient){dbClient.readWriteTransaction().run(transaction->{// Transfer marketing budget from one album to another. We do it in a transaction to// ensure that the transfer is atomic.Stringsql1="SELECT MarketingBudget from Albums WHERE SingerId = 2 and AlbumId = 2";ResultSetresultSet=transaction.executeQuery(Statement.of(sql1));longalbum2Budget=0;while(resultSet.next()){album2Budget=resultSet.getLong("MarketingBudget");}// Transaction will only be committed if this condition still holds at the time of// commit. Otherwise it will be aborted and the callable will be rerun by the// client library.longtransfer=200000;if(album2Budget>=transfer){Stringsql2="SELECT MarketingBudget from Albums WHERE SingerId = 1 and AlbumId = 1";ResultSetresultSet2=transaction.executeQuery(Statement.of(sql2));longalbum1Budget=0;while(resultSet2.next()){album1Budget=resultSet2.getLong("MarketingBudget");}album1Budget+=transfer;album2Budget-=transfer;StatementupdateStatement=Statement.newBuilder("UPDATE Albums "+"SET MarketingBudget = @AlbumBudget "+"WHERE SingerId = 1 and AlbumId = 1").bind("AlbumBudget").to(album1Budget).build();transaction.executeUpdate(updateStatement);StatementupdateStatement2=Statement.newBuilder("UPDATE Albums "+"SET MarketingBudget = @AlbumBudget "+"WHERE SingerId = 2 and AlbumId = 2").bind("AlbumBudget").to(album2Budget).build();transaction.executeUpdate(updateStatement2);}returnnull;});}PostgreSQL
staticvoidwriteWithTransactionUsingDml(DatabaseClientdbClient){dbClient.readWriteTransaction().run(transaction->{// Transfer marketing budget from one album to another. We do it in a transaction to// ensure that the transfer is atomic.Stringsql1="SELECT marketingbudget as \"MarketingBudget\" from Albums WHERE "+"SingerId = 2 and AlbumId = 2";ResultSetresultSet=transaction.executeQuery(Statement.of(sql1));longalbum2Budget=0;while(resultSet.next()){album2Budget=resultSet.getLong("MarketingBudget");}// Transaction will only be committed if this condition still holds at the time of// commit. Otherwise it will be aborted and the callable will be rerun by the// client library.longtransfer=200000;if(album2Budget>=transfer){Stringsql2="SELECT marketingbudget as \"MarketingBudget\" from Albums WHERE "+"SingerId = 1 and AlbumId = 1";ResultSetresultSet2=transaction.executeQuery(Statement.of(sql2));longalbum1Budget=0;while(resultSet2.next()){album1Budget=resultSet2.getLong("MarketingBudget");}album1Budget+=transfer;album2Budget-=transfer;StatementupdateStatement=Statement.newBuilder("UPDATE Albums "+"SET MarketingBudget = $1 "+"WHERE SingerId = 1 and AlbumId = 1").bind("p1").to(album1Budget).build();transaction.executeUpdate(updateStatement);StatementupdateStatement2=Statement.newBuilder("UPDATE Albums "+"SET MarketingBudget = $1 "+"WHERE SingerId = 2 and AlbumId = 2").bind("p1").to(album2Budget).build();transaction.executeUpdate(updateStatement2);}returnnull;});}Run the sample using thewritewithtransactionusingdml argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\writewithtransactionusingdmltest-instanceexample-dbUse a secondary index
Suppose you wanted to fetch all rows ofAlbums that haveAlbumTitle valuesin a certain range. You could read all values from theAlbumTitle column usinga SQL statement or a read call, and then discard the rows that don't meet thecriteria, but doing this full table scan is expensive, especially for tableswith a lot of rows. Instead you can speed up the retrieval of rows whensearching by non-primary key columns by creating asecondary index on the table.
Adding a secondary index to an existing table requires a schema update. Likeother schema updates, Spanner supports adding an index while thedatabase continues to serve traffic. Spanner automatically backfills theindex with your existing data. Backfills might take a few minutes to complete,but you don't need to take the database offline or avoid writing to the indexedtable during this process. For more details, seeAdd a secondary index.
After you add a secondary index, Spanner automatically uses it forSQL queries that are likely to run faster with the index. If you use the readinterface, you must specify the index that you want to use.
Add a secondary index
You can add an index on the command line using the gcloud CLI orprogrammatically using the Spanner client library for Java.
On the command line
Use the followingCREATE INDEX commandto add an index to the database:
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance\--ddl='CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'You should see:
Schemaupdating...done.Using the Spanner client library for Java
Use theupdateDatabaseDdl()method of theDatabaseAdminClient class to add an index:staticvoidaddIndex(DatabaseAdminClientadminClient,DatabaseNamedatabaseName){try{// Initiate the request which returns an OperationFuture.adminClient.updateDatabaseDdlAsync(databaseName,Arrays.asList("CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)")).get();System.out.println("Added AlbumsByAlbumTitle index");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}Run the sample using theaddindex argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\addindextest-instanceexample-dbAdding an index can take a few minutes. After the index is added, you shouldsee:
AddedtheAlbumsByAlbumTitleindex.Read using the index
For SQL queries, Spanner automatically uses an appropriate index. In theread interface, you must specify the index in your request.
To use the index in the read interface, use thereadUsingIndex() method of theReadContext class.
The following code fetches allAlbumId, andAlbumTitlecolumns from theAlbumsByAlbumTitle index.
staticvoidreadUsingIndex(DatabaseClientdbClient){try(ResultSetresultSet=dbClient.singleUse().readUsingIndex("Albums","AlbumsByAlbumTitle",KeySet.all(),Arrays.asList("AlbumId","AlbumTitle"))){while(resultSet.next()){System.out.printf("%d %s\n",resultSet.getLong(0),resultSet.getString(1));}}}Run the sample using thereadindex argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\readindextest-instanceexample-dbYou should see:
2ForeverHoldYourPeace2Go,Go,Go1Green3Terrified1TotalJunkAdd an index for index-only reads
You might have noticed that the previous read example doesn't include readingtheMarketingBudget column. This is because Spanner's read interfacedoesn't support the ability to join an index with a data table to look up valuesthat are not stored in the index.
Create an alternate definition ofAlbumsByAlbumTitle that stores a copy ofMarketingBudget in the index.
On the command line
GoogleSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance\--ddl='CREATEINDEXAlbumsByAlbumTitle2ONAlbums(AlbumTitle)STORING(MarketingBudget)PostgreSQL
gcloudspannerdatabasesddlupdateexample-db--instance=test-instance\--ddl='CREATEINDEXAlbumsByAlbumTitle2ONAlbums(AlbumTitle)INCLUDE(MarketingBudget)Adding an index can take a few minutes. After the index is added, you shouldsee:
Schemaupdating...done.Using the Spanner client library for Java
Use theupdateDatabaseDdl()method of theDatabaseAdminClient class to add an index with aSTORINGclause for GoogleSQL andINCLUDE clause for PostgreSQL:
GoogleSQL
staticvoidaddStoringIndex(DatabaseAdminClientadminClient,DatabaseNamedatabaseName){try{// Initiate the request which returns an OperationFuture.adminClient.updateDatabaseDdlAsync(databaseName,Arrays.asList("CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) "+"STORING (MarketingBudget)")).get();System.out.println("Added AlbumsByAlbumTitle2 index");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}PostgreSQL
staticvoidaddStoringIndex(DatabaseAdminClientadminClient,DatabaseNamedatabaseName){try{// Initiate the request which returns an OperationFuture.adminClient.updateDatabaseDdlAsync(databaseName,Arrays.asList("CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) "+"INCLUDE (MarketingBudget)")).get();System.out.println("Added AlbumsByAlbumTitle2 index");}catch(ExecutionExceptione){// If the operation failed during execution, expose the cause.throw(SpannerException)e.getCause();}catch(InterruptedExceptione){// Throw when a thread is waiting, sleeping, or otherwise occupied,// and the thread is interrupted, either before or during the activity.throwSpannerExceptionFactory.propagateInterrupt(e);}}Run the sample using theaddstoringindex argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\addstoringindextest-instanceexample-dbAdding an index can take a few minutes. After the index is added, you shouldsee:
AddedAlbumsByAlbumTitle2indexNow you can execute a read that fetches allAlbumId,AlbumTitle, andMarketingBudget columns from theAlbumsByAlbumTitle2 index:
staticvoidreadStoringIndex(DatabaseClientdbClient){// We can read MarketingBudget also from the index since it stores a copy of MarketingBudget.try(ResultSetresultSet=dbClient.singleUse().readUsingIndex("Albums","AlbumsByAlbumTitle2",KeySet.all(),Arrays.asList("AlbumId","AlbumTitle","MarketingBudget"))){while(resultSet.next()){System.out.printf("%d %s %s\n",resultSet.getLong(0),resultSet.getString(1),resultSet.isNull("MarketingBudget")?"NULL":resultSet.getLong("MarketingBudget"));}}}Run the sample using thereadstoringindex argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\readstoringindextest-instanceexample-dbYou should see output similar to:
2ForeverHoldYourPeace3000002Go,Go,GoNULL1GreenNULL3TerrifiedNULL1TotalJunk300000Retrieve data using read-only transactions
Suppose you want to execute more than one read at the same timestamp.Read-onlytransactions observe a consistentprefix of the transaction commit history, so your application always getsconsistent data. Use aReadOnlyTransactionobject for executing read-only transactions. Use thereadOnlyTransaction()method of theDatabaseClient class to get aReadOnlyTransaction object.
The following shows how to run a query and perform a read in the same read-onlytransaction:
staticvoidreadOnlyTransaction(DatabaseClientdbClient){// ReadOnlyTransaction must be closed by calling close() on it to release resources held by it.// We use a try-with-resource block to automatically do so.try(ReadOnlyTransactiontransaction=dbClient.readOnlyTransaction()){try(ResultSetqueryResultSet=transaction.executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))){while(queryResultSet.next()){System.out.printf("%d %d %s\n",queryResultSet.getLong(0),queryResultSet.getLong(1),queryResultSet.getString(2));}}// queryResultSet.close() is automatically called heretry(ResultSetreadResultSet=transaction.read("Albums",KeySet.all(),Arrays.asList("SingerId","AlbumId","AlbumTitle"))){while(readResultSet.next()){System.out.printf("%d %d %s\n",readResultSet.getLong(0),readResultSet.getLong(1),readResultSet.getString(2));}}// readResultSet.close() is automatically called here}// transaction.close() is automatically called here}Run the sample using thereadonlytransaction argument.
java-jartarget/spanner-snippets/spanner-google-cloud-samples.jar\readonlytransactiontest-instanceexample-dbYou should see output similar to:
22ForeverHoldYourPeace12Go,Go,Go21Green23Terrified11TotalJunk11TotalJunk12Go,Go,Go21Green22ForeverHoldYourPeace23TerrifiedCleanup
To avoid incurring additional charges to your Cloud Billing account for theresources used in this tutorial, drop the database and delete the instance thatyou created.
Delete the database
If you delete an instance, all databases within it are automatically deleted.This step shows how to delete a database without deleting an instance (you wouldstill incur charges for the instance).
On the command line
gcloudspannerdatabasesdeleteexample-db--instance=test-instanceUsing the Google Cloud console
Go to theSpanner Instances page in the Google Cloud console.
Click the instance.
Click the database that you want to delete.
In theDatabase details page, clickDelete.
Confirm that you want to delete the database and clickDelete.
Delete the instance
Deleting an instance automatically drops all databases created in that instance.
On the command line
gcloudspannerinstancesdeletetest-instanceUsing the Google Cloud console
Go to theSpanner Instances page in the Google Cloud console.
Click your instance.
ClickDelete.
Confirm that you want to delete the instance and clickDelete.
What's next
- Try theSpring Data module for Spanner.
Learn how toaccess Spanner with a virtual machine instance.
Learn about authorization and authentication credentials inAuthenticate toCloud services using client libraries.
Learn more about SpannerSchema design best practices.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.