-
Notifications
You must be signed in to change notification settings - Fork 10
/
SpannerBulkWrite.java
222 lines (159 loc) · 6.08 KB
/
SpannerBulkWrite.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.spanner_migration;
import static org.apache.beam.sdk.io.Compression.GZIP;
import com.google.cloud.Date;
import com.google.cloud.spanner.Mutation;
import com.google.gson.Gson;
import java.io.Serializable;
import java.util.Optional;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.spanner.SpannerIO;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
## How to run
mvn clean
mvn compile
mvn exec:java \
-Dexec.mainClass=com.example.spanner_migration.SpannerBulkWrite \
-Pdataflow-runner \
-Dexec.args="--project=my-project-id \
--instanceId=my-instance-id \
--databaseId=my-database-id \
--table=my-table \
--importBucket=my-import-bucket \
--runner=DataflowRunner \
--region=my-gcp-region"
Note: After a successful DynamoDB export to the import bucket,
the bucket should contain gzip JSON files.
*/
@SuppressWarnings("serial")
public class SpannerBulkWrite {
private static final Logger LOG = LoggerFactory.getLogger(SpannerBulkWrite.class);
public interface Options extends PipelineOptions {
@Description("Spanner instance ID to write to")
@Validation.Required
String getInstanceId();
void setInstanceId(String value);
@Description("Spanner database name to write to")
@Validation.Required
String getDatabaseId();
void setDatabaseId(String value);
@Description("Spanner table name to write to")
@Validation.Required
String getTable();
void setTable(String value);
@Description("Location of your GCS Bucket with your exported database files")
@Validation.Required
String getImportBucket();
void setImportBucket(String value);
}
static class ParseRecords extends DoFn<String, Record> {
@ProcessElement
public void processElement(ProcessContext c) {
c.output(new Gson().fromJson(c.element(), Record.class));
//In a production system, you should use a dead letter queue
}
}
static class CreateRecordMutations extends DoFn<Record, Mutation> {
String table;
public CreateRecordMutations(String table) {
this.table = table;
}
@ProcessElement
public void processElement(ProcessContext c) {
Record record = c.element();
Mutation.WriteBuilder mutation = Mutation.newInsertOrUpdateBuilder(table);
try {
// [START mapping]
mutation.set("Username").to(record.Item.Username.S);
Optional.ofNullable(record.Item.Zipcode).ifPresent(x -> {
mutation.set("Zipcode").to(Integer.parseInt(x.N));
});
Optional.ofNullable(record.Item.Subscribed).ifPresent(x -> {
mutation.set("Subscribed").to(Boolean.parseBoolean(x.BOOL));
});
Optional.ofNullable(record.Item.ReminderDate).ifPresent(x -> {
mutation.set("ReminderDate").to(Date.parseDate(x.S));
});
Optional.ofNullable(record.Item.PointsEarned).ifPresent(x -> {
mutation.set("PointsEarned").to(Integer.parseInt(x.N));
});
// [END mapping]
c.output(mutation.build());
} catch (Exception ex) {
LOG.error("Unable to create mutation", ex);
}
}
}
public static void main(String[] args) {
Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
Pipeline p = Pipeline.create(options);
// file pattern to only grab data export files (which contain dashes in filename)
// and ignore export job metadata files
String inputFiles = "gs://" + options.getImportBucket() + "/**/*.json.gz";
// (Source) read DynamoDB items from export files
PCollection<String> input = p.apply("ReadItems",
TextIO.read().from(inputFiles).withCompression(GZIP));
// Parse the DynamoDB items into objects
PCollection<Record> records = input.apply("ParseRecords", ParDo.of(new ParseRecords()));
// Create Cloud Spanner mutations using parsed Record objects
PCollection<Mutation> mutations = records.apply("CreateRecordMutations",
ParDo.of(new CreateRecordMutations(options.getTable())));
// (Sink) write the Mutations to Spanner
mutations.apply("WriteRecords", SpannerIO.write()
.withInstanceId(options.getInstanceId())
.withDatabaseId(options.getDatabaseId()));
p.run().waitUntilFinish();
}
// JSON mapping item to object
// [START GSON]
public static class Record implements Serializable {
private Item Item;
}
public static class Item implements Serializable {
private Username Username;
private PointsEarned PointsEarned;
private Subscribed Subscribed;
private ReminderDate ReminderDate;
private Zipcode Zipcode;
}
public static class Username implements Serializable {
private String S;
}
public static class PointsEarned implements Serializable {
private String N;
}
public static class Subscribed implements Serializable {
private String BOOL;
}
public static class ReminderDate implements Serializable {
private String S;
}
public static class Zipcode implements Serializable {
private String N;
}
// [END GSON]
}