Querying Cassandra in Rails by Cequel

1.1k Views Asked by At

I am using Cequel in Rails. I would like to query something like

Event.where("started_at >?", Time.now) 

in ActiveRecord. But I don't know how to do that in cequel.

2

There are 2 best solutions below

0
On

In order to perform efficient range queries over a timestamp, you'll need to group your events under a parent object, and use the started_at as your clustering column (the last column in your primary key). So, for instance, if events belong to venues, you might set up something like this:

class Venue
  include Cequel::Record

  key :id, :uuid, auto: true
  column :name, :text

  has_many :events
end

class Event
  include Cequel::Record

  belongs_to :venue
  key :started_at, :timeuuid
  column :ended_at, :timestamp
  column :title, :text
end

This means you can efficiently perform queries over ranges of start times. A few things to note:

  • The started_at key is a TimeUUID to ensure uniqueness. TimeUUIDs encapsulate a timestamp, and can be queried over time ranges
  • Unlike ActiveRecord, a model can only have one belongs_to declaration. It describes a parent/child relationship.

So to create an event, you'd do something like:

venue.events.new(started_at: Cequel.uuid(started_at), ended_at: ended_at)

Then to query for a range of events by start time:

venue.events.after(Time.now)

Note that you can't do range queries by arbitrary columns—only by clustering columns in the primary key. So you can't have a table that allows queries over start_time and end_time, for instance.

0
On

Thank you outoftime. But I found a solution to query by providing range in hash value. The answer is

Event.where(started_at: Time.now..Time.now+30.minutes)