How to create Cassandra tables with cequel (without using rails)

556 Views Asked by At

I am using Cequel as ORM for Cassandra without rails.
I have a problem when trying to create a simple list of projects. First I defined the model with three columns which should belong to a compound key.

class Project
  include Cequel::Record

  key :client, :text, { partition: true }
  key :type, :text, { partition: true }
  key :dep, :text, { partition: true }

end

Later when I try to create the Project via

project = Project.create!({client: "test", type: "test", dep: "test"})

I get an error that the table does not exist. The tables are not created automatically with Project.create! but I have to create the table manually first:

  connection.schema.create_table(:projects) do 
    partition_key :client, :text
    partition_key :type, :text
    partition_key :dept, :text
  end

But this syntax is different from the documented Record definition and I only found it by sifting through the source code. But this creates two problems.

  • Code overhead
  • I don't know the syntax for has_many and belongs_to so I cannot create the table correctly if the Record includes this

Am I overlooking a method to create the table automatically from the Project class definition?

1

There are 1 best solutions below

0
On

The tables can be created by calling the method synchronize_schema on the class. So, in your case, you should execute Project.synchronize_schema before actually attempting to read/write into it.

Given that you are building a broader project, you can consider using Rake tasks for it. You also need to migrate so that the tables are actually created in Cassandra. You can use rake cequel:migrate for that. There are more tasks which you can see via rake --tasks.

If you are creating your custom project with custom places for models, you probably need to hack the rake migration task a little. This is an implementation that I did for my project https://github.com/octoai/gems/blob/master/octo-core/Rakefile#L75. Also take a look at how models are defined https://github.com/octoai/gems/tree/master/octo-core/lib/octocore/models

Hope this helps.