[ https://issues.apache.org/jira/browse/BEAM-9008?focusedWorklogId=501161&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-501161 ]
ASF GitHub Bot logged work on BEAM-9008: ---------------------------------------- Author: ASF GitHub Bot Created on: 15/Oct/20 16:44 Start Date: 15/Oct/20 16:44 Worklog Time Spent: 10m Work Description: vmarquez commented on a change in pull request #10546: URL: https://github.com/apache/beam/pull/10546#discussion_r505688957 ########## File path: sdks/java/io/cassandra/src/main/java/org/apache/beam/sdk/io/cassandra/ReadFn.java ########## @@ -0,0 +1,172 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.beam.sdk.io.cassandra; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.PreparedStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.Token; +import java.util.Collections; +import java.util.Iterator; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.beam.sdk.io.cassandra.CassandraIO.Read; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Joiner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class ReadFn<T> extends DoFn<Read<T>, T> { + + private static final Logger LOG = LoggerFactory.getLogger(ReadFn.class); + + private transient Cluster cluster; + + private transient Session session; + + private transient Read<T> lastRead; + + @ProcessElement + public void processElement(@Element Read<T> read, OutputReceiver<T> receiver) { + Session session = getSession(read); + Mapper<T> mapper = read.mapperFactoryFn().apply(session); + String partitionKey = + cluster.getMetadata().getKeyspace(read.keyspace().get()).getTable(read.table().get()) + .getPartitionKey().stream() + .map(ColumnMetadata::getName) + .collect(Collectors.joining(",")); + + String query = generateRangeQuery(read, partitionKey, read.ringRanges() != null); + PreparedStatement preparedStatement = session.prepare(query); + Set<RingRange> ringRanges = + read.ringRanges() == null ? Collections.<RingRange>emptySet() : read.ringRanges().get(); + + for (RingRange rr : ringRanges) { + Token startToken = cluster.getMetadata().newToken(rr.getStart().toString()); + Token endToken = cluster.getMetadata().newToken(rr.getEnd().toString()); + ResultSet rs = + session.execute(preparedStatement.bind().setToken(0, startToken).setToken(1, endToken)); + Iterator<T> iter = mapper.map(rs); + while (iter.hasNext()) { + T n = iter.next(); + receiver.output(n); + } + } + + if (read.ringRanges() == null) { + ResultSet rs = session.execute(preparedStatement.bind()); + Iterator<T> iter = mapper.map(rs); + while (iter.hasNext()) { + receiver.output(iter.next()); + } + } + } + + @Teardown + public void teardown() { + if (session != null) { + this.session.close(); + } + if (cluster != null) { + this.cluster.close(); + } + } + + private Session getSession(Read<T> read) { + if (cluster == null || !reuseCluster(this.lastRead, read)) { + this.cluster = + CassandraIO.getCluster( + read.hosts(), + read.port(), + read.username(), + read.password(), + read.localDc(), + read.consistencyLevel()); + } + if (session == null || !reuseSession(lastRead, read)) { + this.session = this.cluster.connect(read.keyspace().get()); + } + this.lastRead = read; + return this.session; + } + + private static <T> boolean reuseCluster(Read<T> readA, Read<T> readB) { + return readA != null Review comment: I didn't address this yet, wanted your thoughts on it. I agree it can be improved. The driver will handle Connection *pooling*, (handling N number of connections per cassandra host and sharing them in a thread safe way), but we still need to initiate a `Session` per Cassandra instance, and maintain a reference to the `Session` to keep those connections in scope (under the hood). So we could use something as simple as a `Map<?, Cluster>` and `Map<?, Session>`, but remember we have to do both, since each `Read<>` might be hitting an entirely different cassandra cluster (hence the need to maintain different `Cluster` objects as well). If we wanted something fancier, we could try a guava LRU or something on the off chance the user is initiating hundreds(thousands/millions?) of different Session objects. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org Issue Time Tracking ------------------- Worklog Id: (was: 501161) Time Spent: 15h 10m (was: 15h) > Add readAll() method to CassandraIO > ----------------------------------- > > Key: BEAM-9008 > URL: https://issues.apache.org/jira/browse/BEAM-9008 > Project: Beam > Issue Type: New Feature > Components: io-java-cassandra > Affects Versions: 2.16.0 > Reporter: vincent marquez > Priority: P3 > Time Spent: 15h 10m > Remaining Estimate: 0h > > When querying a large cassandra database, it's often *much* more useful to > programatically generate the queries needed to to be run rather than reading > all partitions and attempting some filtering. > As an example: > {code:java} > public class Event { > @PartitionKey(0) public UUID accountId; > @PartitionKey(1)public String yearMonthDay; > @ClusteringKey public UUID eventId; > //other data... > }{code} > If there is ten years worth of data, you may want to only query one year's > worth. Here each token range would represent one 'token' but all events for > the day. > {code:java} > Set<UUID> accounts = getRelevantAccounts(); > Set<String> dateRange = generateDateRange("2018-01-01", "2019-01-01"); > PCollection<TokenRange> tokens = generateTokens(accounts, dateRange); > {code} > > I propose an additional _readAll()_ PTransform that can take a PCollection > of token ranges and can return a PCollection<T> of what the query would > return. > *Question: How much code should be in common between both methods?* > Currently the read connector already groups all partitions into a List of > Token Ranges, so it would be simple to refactor the current read() based > method to a 'ParDo' based one and have them both share the same function. > Reasons against sharing code between read and readAll > * Not having the read based method return a BoundedSource connector would > mean losing the ability to know the size of the data returned > * Currently the CassandraReader executes all the grouped TokenRange queries > *asynchronously* which is (maybe?) fine when all that's happening is > splitting up all the partition ranges but terrible for executing potentially > millions of queries. > Reasons _for_ sharing code would be simplified code base and that both of > the above issues would most likely have a negligable performance impact. > > > -- This message was sent by Atlassian Jira (v8.3.4#803005)