Avoid N+1 query in large data set












0















I have a migration which updates existing records with a new attribute value. The model is called 'MyRecord'. It has millions of records in the database with a new unit_id column of null. I want to update that unit_id column with a specific value:



MyRecord.find_each do |record|
unit_id = Unit.calculate_unit_from_old_columns(record.legacy_column_1, record.legacy_column_2).first.id
record.update unit_id: unit_id
end


This creates a lot of N+1 queries:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
UPDATE my_records SET unit_id='43' WHERE legacy_column_1 = 'Legacy Electronics' AND legacy_column_2 = 'Legacy Auto';


And some of these N+1 queries are duplicated. I see a lot of this in logs:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto'


I am familiar with eager loading via includes. But when this migration is run to update existing data, there will be no association yet. So I cannot do this:



record.includes(:unit)


How can I eliminate the N+1 queries and cache the query so it does not hit database again when s duplicate query?










share|improve this question

























  • How complicated is calculate_unit_from_old_columns? It'd be best to move everything to the updating query (SET unit_id = DO_STUFF(legacy_column_1, legacy_column_2). If it's too complicated, you should prepare batch updates (map 1000 records to (id, new_unit_id) pairs and use those for update queries.

    – Marcin Kołodziej
    Nov 14 '18 at 22:34











  • @MarcinKołodziej can you give me an example of batch updates or point me to a link?

    – Donato
    Nov 14 '18 at 22:37











  • calculate_unit_from_old_columns is a named scope: scope : calculate_unit_from_old_columns, ->(item1, item2) { where(item_1: item1, item2: item_2 ) }

    – Donato
    Nov 14 '18 at 22:38











  • Oh, right, it's quite a long line. Well, you can write a simple update with join. You tagged your question with MySQL and PostgreSQL and they have different syntax for that, it should be easily searchable.

    – Marcin Kołodziej
    Nov 14 '18 at 22:44











  • @MarcinKołodziej I am using MySQL

    – Donato
    Nov 14 '18 at 22:45
















0















I have a migration which updates existing records with a new attribute value. The model is called 'MyRecord'. It has millions of records in the database with a new unit_id column of null. I want to update that unit_id column with a specific value:



MyRecord.find_each do |record|
unit_id = Unit.calculate_unit_from_old_columns(record.legacy_column_1, record.legacy_column_2).first.id
record.update unit_id: unit_id
end


This creates a lot of N+1 queries:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
UPDATE my_records SET unit_id='43' WHERE legacy_column_1 = 'Legacy Electronics' AND legacy_column_2 = 'Legacy Auto';


And some of these N+1 queries are duplicated. I see a lot of this in logs:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto'


I am familiar with eager loading via includes. But when this migration is run to update existing data, there will be no association yet. So I cannot do this:



record.includes(:unit)


How can I eliminate the N+1 queries and cache the query so it does not hit database again when s duplicate query?










share|improve this question

























  • How complicated is calculate_unit_from_old_columns? It'd be best to move everything to the updating query (SET unit_id = DO_STUFF(legacy_column_1, legacy_column_2). If it's too complicated, you should prepare batch updates (map 1000 records to (id, new_unit_id) pairs and use those for update queries.

    – Marcin Kołodziej
    Nov 14 '18 at 22:34











  • @MarcinKołodziej can you give me an example of batch updates or point me to a link?

    – Donato
    Nov 14 '18 at 22:37











  • calculate_unit_from_old_columns is a named scope: scope : calculate_unit_from_old_columns, ->(item1, item2) { where(item_1: item1, item2: item_2 ) }

    – Donato
    Nov 14 '18 at 22:38











  • Oh, right, it's quite a long line. Well, you can write a simple update with join. You tagged your question with MySQL and PostgreSQL and they have different syntax for that, it should be easily searchable.

    – Marcin Kołodziej
    Nov 14 '18 at 22:44











  • @MarcinKołodziej I am using MySQL

    – Donato
    Nov 14 '18 at 22:45














0












0








0








I have a migration which updates existing records with a new attribute value. The model is called 'MyRecord'. It has millions of records in the database with a new unit_id column of null. I want to update that unit_id column with a specific value:



MyRecord.find_each do |record|
unit_id = Unit.calculate_unit_from_old_columns(record.legacy_column_1, record.legacy_column_2).first.id
record.update unit_id: unit_id
end


This creates a lot of N+1 queries:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
UPDATE my_records SET unit_id='43' WHERE legacy_column_1 = 'Legacy Electronics' AND legacy_column_2 = 'Legacy Auto';


And some of these N+1 queries are duplicated. I see a lot of this in logs:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto'


I am familiar with eager loading via includes. But when this migration is run to update existing data, there will be no association yet. So I cannot do this:



record.includes(:unit)


How can I eliminate the N+1 queries and cache the query so it does not hit database again when s duplicate query?










share|improve this question
















I have a migration which updates existing records with a new attribute value. The model is called 'MyRecord'. It has millions of records in the database with a new unit_id column of null. I want to update that unit_id column with a specific value:



MyRecord.find_each do |record|
unit_id = Unit.calculate_unit_from_old_columns(record.legacy_column_1, record.legacy_column_2).first.id
record.update unit_id: unit_id
end


This creates a lot of N+1 queries:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
UPDATE my_records SET unit_id='43' WHERE legacy_column_1 = 'Legacy Electronics' AND legacy_column_2 = 'Legacy Auto';


And some of these N+1 queries are duplicated. I see a lot of this in logs:



SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto' 
SELECT units.* FROM units WHERE units.item_1 = 'Electronics' AND units.item_2 = 'Auto'


I am familiar with eager loading via includes. But when this migration is run to update existing data, there will be no association yet. So I cannot do this:



record.includes(:unit)


How can I eliminate the N+1 queries and cache the query so it does not hit database again when s duplicate query?







mysql sql ruby-on-rails






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 22:45







Donato

















asked Nov 14 '18 at 22:27









DonatoDonato

2,07431434




2,07431434













  • How complicated is calculate_unit_from_old_columns? It'd be best to move everything to the updating query (SET unit_id = DO_STUFF(legacy_column_1, legacy_column_2). If it's too complicated, you should prepare batch updates (map 1000 records to (id, new_unit_id) pairs and use those for update queries.

    – Marcin Kołodziej
    Nov 14 '18 at 22:34











  • @MarcinKołodziej can you give me an example of batch updates or point me to a link?

    – Donato
    Nov 14 '18 at 22:37











  • calculate_unit_from_old_columns is a named scope: scope : calculate_unit_from_old_columns, ->(item1, item2) { where(item_1: item1, item2: item_2 ) }

    – Donato
    Nov 14 '18 at 22:38











  • Oh, right, it's quite a long line. Well, you can write a simple update with join. You tagged your question with MySQL and PostgreSQL and they have different syntax for that, it should be easily searchable.

    – Marcin Kołodziej
    Nov 14 '18 at 22:44











  • @MarcinKołodziej I am using MySQL

    – Donato
    Nov 14 '18 at 22:45



















  • How complicated is calculate_unit_from_old_columns? It'd be best to move everything to the updating query (SET unit_id = DO_STUFF(legacy_column_1, legacy_column_2). If it's too complicated, you should prepare batch updates (map 1000 records to (id, new_unit_id) pairs and use those for update queries.

    – Marcin Kołodziej
    Nov 14 '18 at 22:34











  • @MarcinKołodziej can you give me an example of batch updates or point me to a link?

    – Donato
    Nov 14 '18 at 22:37











  • calculate_unit_from_old_columns is a named scope: scope : calculate_unit_from_old_columns, ->(item1, item2) { where(item_1: item1, item2: item_2 ) }

    – Donato
    Nov 14 '18 at 22:38











  • Oh, right, it's quite a long line. Well, you can write a simple update with join. You tagged your question with MySQL and PostgreSQL and they have different syntax for that, it should be easily searchable.

    – Marcin Kołodziej
    Nov 14 '18 at 22:44











  • @MarcinKołodziej I am using MySQL

    – Donato
    Nov 14 '18 at 22:45

















How complicated is calculate_unit_from_old_columns? It'd be best to move everything to the updating query (SET unit_id = DO_STUFF(legacy_column_1, legacy_column_2). If it's too complicated, you should prepare batch updates (map 1000 records to (id, new_unit_id) pairs and use those for update queries.

– Marcin Kołodziej
Nov 14 '18 at 22:34





How complicated is calculate_unit_from_old_columns? It'd be best to move everything to the updating query (SET unit_id = DO_STUFF(legacy_column_1, legacy_column_2). If it's too complicated, you should prepare batch updates (map 1000 records to (id, new_unit_id) pairs and use those for update queries.

– Marcin Kołodziej
Nov 14 '18 at 22:34













@MarcinKołodziej can you give me an example of batch updates or point me to a link?

– Donato
Nov 14 '18 at 22:37





@MarcinKołodziej can you give me an example of batch updates or point me to a link?

– Donato
Nov 14 '18 at 22:37













calculate_unit_from_old_columns is a named scope: scope : calculate_unit_from_old_columns, ->(item1, item2) { where(item_1: item1, item2: item_2 ) }

– Donato
Nov 14 '18 at 22:38





calculate_unit_from_old_columns is a named scope: scope : calculate_unit_from_old_columns, ->(item1, item2) { where(item_1: item1, item2: item_2 ) }

– Donato
Nov 14 '18 at 22:38













Oh, right, it's quite a long line. Well, you can write a simple update with join. You tagged your question with MySQL and PostgreSQL and they have different syntax for that, it should be easily searchable.

– Marcin Kołodziej
Nov 14 '18 at 22:44





Oh, right, it's quite a long line. Well, you can write a simple update with join. You tagged your question with MySQL and PostgreSQL and they have different syntax for that, it should be easily searchable.

– Marcin Kołodziej
Nov 14 '18 at 22:44













@MarcinKołodziej I am using MySQL

– Donato
Nov 14 '18 at 22:45





@MarcinKołodziej I am using MySQL

– Donato
Nov 14 '18 at 22:45












1 Answer
1






active

oldest

votes


















0














Use a simple query, you can think of batching it if it runs for too long:



MyRecord.connection.execute(
"UPDATE my_records, units
SET unit_id = units.id
WHERE units.item_1 = legacy_column_1 AND units.item_2 = legacy_column_2"
)





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%2f53309663%2favoid-n1-query-in-large-data-set%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









    0














    Use a simple query, you can think of batching it if it runs for too long:



    MyRecord.connection.execute(
    "UPDATE my_records, units
    SET unit_id = units.id
    WHERE units.item_1 = legacy_column_1 AND units.item_2 = legacy_column_2"
    )





    share|improve this answer




























      0














      Use a simple query, you can think of batching it if it runs for too long:



      MyRecord.connection.execute(
      "UPDATE my_records, units
      SET unit_id = units.id
      WHERE units.item_1 = legacy_column_1 AND units.item_2 = legacy_column_2"
      )





      share|improve this answer


























        0












        0








        0







        Use a simple query, you can think of batching it if it runs for too long:



        MyRecord.connection.execute(
        "UPDATE my_records, units
        SET unit_id = units.id
        WHERE units.item_1 = legacy_column_1 AND units.item_2 = legacy_column_2"
        )





        share|improve this answer













        Use a simple query, you can think of batching it if it runs for too long:



        MyRecord.connection.execute(
        "UPDATE my_records, units
        SET unit_id = units.id
        WHERE units.item_1 = legacy_column_1 AND units.item_2 = legacy_column_2"
        )






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 22:54









        Marcin KołodziejMarcin Kołodziej

        4,4801315




        4,4801315
































            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%2f53309663%2favoid-n1-query-in-large-data-set%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

            Florida Star v. B. J. F.

            Error while running script in elastic search , gateway timeout

            Adding quotations to stringified JSON object values