|
| 1 | +/* |
| 2 | + * Copyright 2024 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.bigtable; |
| 18 | + |
| 19 | +// [START bigtable_writes_aggregate] |
| 20 | + |
| 21 | +import com.google.cloud.bigtable.data.v2.BigtableDataClient; |
| 22 | +import com.google.cloud.bigtable.data.v2.models.RowMutation; |
| 23 | +import java.time.Instant; |
| 24 | +import java.time.temporal.ChronoUnit; |
| 25 | + |
| 26 | +public class WriteAggregate { |
| 27 | + private static final String COUNT_COLUMN_FAMILY_NAME = "view_count"; |
| 28 | + private static final long MICROS_PER_MILLI = 1000; |
| 29 | + |
| 30 | + public static void writeAggregate(String projectId, String instanceId, String tableId) { |
| 31 | + // String projectId = "my-project-id"; |
| 32 | + // String instanceId = "my-instance-id"; |
| 33 | + // String tableId = "page-view-counter"; |
| 34 | + |
| 35 | + try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) { |
| 36 | + |
| 37 | + String rowKey = "page#index.html"; |
| 38 | + Instant viewTimestamp = Instant.parse("2024-03-13T12:41:34.123Z"); |
| 39 | + |
| 40 | + // Bucket the views for an hour into a single count, giving us an hourly view count for a |
| 41 | + // given page. |
| 42 | + Instant hourlyBucket = viewTimestamp.truncatedTo(ChronoUnit.HOURS); |
| 43 | + long hourlyBucketMicros = hourlyBucket.toEpochMilli() * MICROS_PER_MILLI; |
| 44 | + |
| 45 | + RowMutation rowMutation = |
| 46 | + RowMutation.create(tableId, rowKey) |
| 47 | + .addToCell(COUNT_COLUMN_FAMILY_NAME, "views", hourlyBucketMicros, 1); |
| 48 | + |
| 49 | + dataClient.mutateRow(rowMutation); |
| 50 | + System.out.printf("Successfully wrote row %s", rowKey); |
| 51 | + |
| 52 | + } catch (Exception e) { |
| 53 | + System.out.println("Error during WriteAggregate: \n" + e.toString()); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// [END bigtable_writes_aggregate] |
0 commit comments