PySpark foreachPartition write to Database in Parallel










0















I'm reading in hundreds of XML files into a Spark Dataframe, where each row consist of meta data and time series data for a particular event. Each one of these rows is converted into a rdd to be transformed into batches of documents with a particular key/vale structure and then written over to a database. The XML data need to be broken into batches <50Kb, hence the helper function to produce then batches shown below.



def build_documents(data):

# Make dataframe out of data tags
data = pd.DataFrame([i.split(',') for i in list(chain(*(data)))])

# Helper function to Get Batches
for batch in get_batches(data):
x = batch.T.to_dict()
yield x

def process_partition(partition):
client = document_client.DocumentClient(HOST, 'masterKey': MASTER_KEY )
for element in partition:
generator = build_documents(element)
for batch in generator:
client.CreateDocument(collection_link + 'data', batch)


# Write to Database
df.rdd.coalesce(20).foreachPartition(process_partition)


Still tuning the number of partitions, but any thoughts on how this can be improved? Performance is really slow, as expected with the code implemented so far. The cluster consist of 32 cores, 128.0 GB Memory for both driver and can scale up to 8 executors. As shown below, there is only two workers running, which obviously is not optimal when scaling up further. Thoughts?



enter image description here



enter image description here










share|improve this question
























  • While you seem to have some problems with data distribution it looks more like a problem with your Python code and / or service you use. 21 minutes for 73 records / 38MB looks just unrealistically long. Unless you provide more details it might be hard to help you.

    – hi-zir
    May 13 '18 at 19:17















0















I'm reading in hundreds of XML files into a Spark Dataframe, where each row consist of meta data and time series data for a particular event. Each one of these rows is converted into a rdd to be transformed into batches of documents with a particular key/vale structure and then written over to a database. The XML data need to be broken into batches <50Kb, hence the helper function to produce then batches shown below.



def build_documents(data):

# Make dataframe out of data tags
data = pd.DataFrame([i.split(',') for i in list(chain(*(data)))])

# Helper function to Get Batches
for batch in get_batches(data):
x = batch.T.to_dict()
yield x

def process_partition(partition):
client = document_client.DocumentClient(HOST, 'masterKey': MASTER_KEY )
for element in partition:
generator = build_documents(element)
for batch in generator:
client.CreateDocument(collection_link + 'data', batch)


# Write to Database
df.rdd.coalesce(20).foreachPartition(process_partition)


Still tuning the number of partitions, but any thoughts on how this can be improved? Performance is really slow, as expected with the code implemented so far. The cluster consist of 32 cores, 128.0 GB Memory for both driver and can scale up to 8 executors. As shown below, there is only two workers running, which obviously is not optimal when scaling up further. Thoughts?



enter image description here



enter image description here










share|improve this question
























  • While you seem to have some problems with data distribution it looks more like a problem with your Python code and / or service you use. 21 minutes for 73 records / 38MB looks just unrealistically long. Unless you provide more details it might be hard to help you.

    – hi-zir
    May 13 '18 at 19:17













0












0








0


1






I'm reading in hundreds of XML files into a Spark Dataframe, where each row consist of meta data and time series data for a particular event. Each one of these rows is converted into a rdd to be transformed into batches of documents with a particular key/vale structure and then written over to a database. The XML data need to be broken into batches <50Kb, hence the helper function to produce then batches shown below.



def build_documents(data):

# Make dataframe out of data tags
data = pd.DataFrame([i.split(',') for i in list(chain(*(data)))])

# Helper function to Get Batches
for batch in get_batches(data):
x = batch.T.to_dict()
yield x

def process_partition(partition):
client = document_client.DocumentClient(HOST, 'masterKey': MASTER_KEY )
for element in partition:
generator = build_documents(element)
for batch in generator:
client.CreateDocument(collection_link + 'data', batch)


# Write to Database
df.rdd.coalesce(20).foreachPartition(process_partition)


Still tuning the number of partitions, but any thoughts on how this can be improved? Performance is really slow, as expected with the code implemented so far. The cluster consist of 32 cores, 128.0 GB Memory for both driver and can scale up to 8 executors. As shown below, there is only two workers running, which obviously is not optimal when scaling up further. Thoughts?



enter image description here



enter image description here










share|improve this question
















I'm reading in hundreds of XML files into a Spark Dataframe, where each row consist of meta data and time series data for a particular event. Each one of these rows is converted into a rdd to be transformed into batches of documents with a particular key/vale structure and then written over to a database. The XML data need to be broken into batches <50Kb, hence the helper function to produce then batches shown below.



def build_documents(data):

# Make dataframe out of data tags
data = pd.DataFrame([i.split(',') for i in list(chain(*(data)))])

# Helper function to Get Batches
for batch in get_batches(data):
x = batch.T.to_dict()
yield x

def process_partition(partition):
client = document_client.DocumentClient(HOST, 'masterKey': MASTER_KEY )
for element in partition:
generator = build_documents(element)
for batch in generator:
client.CreateDocument(collection_link + 'data', batch)


# Write to Database
df.rdd.coalesce(20).foreachPartition(process_partition)


Still tuning the number of partitions, but any thoughts on how this can be improved? Performance is really slow, as expected with the code implemented so far. The cluster consist of 32 cores, 128.0 GB Memory for both driver and can scale up to 8 executors. As shown below, there is only two workers running, which obviously is not optimal when scaling up further. Thoughts?



enter image description here



enter image description here







apache-spark pyspark






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 13 '18 at 1:17







Trace Smith

















asked May 12 '18 at 21:17









Trace SmithTrace Smith

3514




3514












  • While you seem to have some problems with data distribution it looks more like a problem with your Python code and / or service you use. 21 minutes for 73 records / 38MB looks just unrealistically long. Unless you provide more details it might be hard to help you.

    – hi-zir
    May 13 '18 at 19:17

















  • While you seem to have some problems with data distribution it looks more like a problem with your Python code and / or service you use. 21 minutes for 73 records / 38MB looks just unrealistically long. Unless you provide more details it might be hard to help you.

    – hi-zir
    May 13 '18 at 19:17
















While you seem to have some problems with data distribution it looks more like a problem with your Python code and / or service you use. 21 minutes for 73 records / 38MB looks just unrealistically long. Unless you provide more details it might be hard to help you.

– hi-zir
May 13 '18 at 19:17





While you seem to have some problems with data distribution it looks more like a problem with your Python code and / or service you use. 21 minutes for 73 records / 38MB looks just unrealistically long. Unless you provide more details it might be hard to help you.

– hi-zir
May 13 '18 at 19:17












1 Answer
1






active

oldest

votes


















1














df.rdd.coalesce(20).foreachPartition(process_partition) will write sequential entries to database. and morever your logic for function process_partition will also be sequential.



You need to multithread the logic for def process_partition. That will speed up the process. Also use df.rdd.coalesce(20).foreachPartitionAsync(process_partition)






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50310742%2fpyspark-foreachpartition-write-to-database-in-parallel%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    df.rdd.coalesce(20).foreachPartition(process_partition) will write sequential entries to database. and morever your logic for function process_partition will also be sequential.



    You need to multithread the logic for def process_partition. That will speed up the process. Also use df.rdd.coalesce(20).foreachPartitionAsync(process_partition)






    share|improve this answer





























      1














      df.rdd.coalesce(20).foreachPartition(process_partition) will write sequential entries to database. and morever your logic for function process_partition will also be sequential.



      You need to multithread the logic for def process_partition. That will speed up the process. Also use df.rdd.coalesce(20).foreachPartitionAsync(process_partition)






      share|improve this answer



























        1












        1








        1







        df.rdd.coalesce(20).foreachPartition(process_partition) will write sequential entries to database. and morever your logic for function process_partition will also be sequential.



        You need to multithread the logic for def process_partition. That will speed up the process. Also use df.rdd.coalesce(20).foreachPartitionAsync(process_partition)






        share|improve this answer















        df.rdd.coalesce(20).foreachPartition(process_partition) will write sequential entries to database. and morever your logic for function process_partition will also be sequential.



        You need to multithread the logic for def process_partition. That will speed up the process. Also use df.rdd.coalesce(20).foreachPartitionAsync(process_partition)







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 15:46









        K.Dᴀᴠɪs

        7,219112439




        7,219112439










        answered Nov 14 '18 at 15:29









        ShyamShyam

        412




        412





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50310742%2fpyspark-foreachpartition-write-to-database-in-parallel%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            27

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            Category:Rhetoric