Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3855916
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T17:50:59+00:00 2026-05-19T17:50:59+00:00

In my rails app, I have a terms model, that stores a term (a

  • 0

In my rails app, I have a “terms” model, that stores a term (a keyword), and the frequency with which it appears in a particular document set (an integer). Whenever a new document gets added to the set, I parse out the words, and then I need to either insert new terms, and their frequency, into the terms table, or I need to update the frequency of an existing term.

The easiest way to do this would be to do a find, then if it’s empty do an insert, or if it’s not empty, increment the frequency of the existing record by the correct amount. That’s two queries per word, however, and documents with high word counts will result in a ludicrously long list of queries. Is there a more efficient way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T17:51:00+00:00Added an answer on May 19, 2026 at 5:51 pm

    You can do this really efficiently, actually. Well, if you’re not afraid to tweak Rails’s default table layout a bit, and if you’re not afraid to generate your own raw SQL…

    I’m going to assume you’re using MySQL for your database (I’m not sure what other DBs support this): you can use INSERT … ON DUPLICATE KEY UPDATE to do this.

    You’ll have to tweak your count table to get it to work, though – “on duplicate key” only refers to the primary key, and Rails’s default ID, which is just an arbitrary number, won’t help you. You’ll need to change your primary key so that it identifies what makes each record unique – in your case, I’d say PRIMARY KEY(word, document_set_id). This might not be supported by Rails by default, but there’s at least one plugin, and probably a couple more, if you don’t like that one.

    Once your database is set up, you can build one giant insert statement, and throw that at MySQL, letting the “on duplicate key” part of the query take care of the nasty existence-checking stuff for you (NOTE: there are plugins to do batch inserts, too, but I don;t know how they work – particularly in regards to “on duplicate key”):

    counts = {}
    #This is just demo code!  Untested, and it'll leave in punctuation...
    @document.text.split(' ').each do |word|
        counts[word] ||= 0
        counts[word] += 1
    end
    
    values = []
    counts.each_pair do |word, count|
        values << ActiveRecord::Base.send(:sanitize_sql_array, [
            '(?, ?, ?)',
            word,
            @document.set_id,
            count
        ])
    end
    
    #Massive line - sorry...
    ActiveRecord::Base.connection.execute("INSERT INTO word_counts (word, document_set_id, occurences) VALUES ${values.join(', ')} ON DUPLICATE KEY UPDATE occurences = occurences + VALUES(occurences)")
    

    And that’ll do it – one SQL query for the entire new document. Should be much faster, half because you’re only running a single query, and half because you’ve sidestepped ActiveRecord’s sluggish query building.

    Hope that helps!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The story so far: I have a rails app with a model named Term.
I have a micro-mini-search engine that highlights the search terms in my rails app.
In a Rails 3.2 app I have a model Project, which has many Tasks.
In my Rails 3.2 app, I have a signup form that includes a terms
Simple rails app: I have 2 models, user and intro [which is simply a
In my rails app I have user, school, and course models. I have set
I have rails app which are working perfectly in the local computer. But when
So I have a Rails app (which in this case seems like it would
I have a Rails app running Mongoid on Heroku and I need to set
I have a Rails app with the usual application_controller, and a controller (and model)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.