freakish
freakish

Reputation: 56477

Using dates with Cassandra

I've just started my adventure with Cassandra database. I've managed to learn some basics but what I still can't understand is how to work with dates in Cassandra?

So for example in MySQL we have a datetime type for a field and we can query (for example) all fields with creation date less then 2010-01-01. Furthermore we can order the result by creation date field.

How can we achieve the same with Cassandra? How to define the corresponding Column Family and how to query (CQL) it to get the same result?

Upvotes: 3

Views: 7465

Answers (1)

Jasonw
Jasonw

Reputation: 5064

You can use type DateType to define a column of type DateType in your column family. You should really read this page, it has description and example how to do range query (that is creationdate < 2010-01-01). For ordering, you can refer to the SliceRange but this will probably cover in the cassandra client already. You will probably want to look into the cassandra client to do the query.

This is a snippet on how to do query in cassandra using hector client.

// 2010-01-01
Date date = new Date(1262275200L);

try
{
    getConnection();
    IndexedSlicesQuery<String, String, String> indexedSlicesQuery = HFactory.createIndexedSlicesQuery(keyspace, ss, ss, ss);
    indexedSlicesQuery.setColumnNames("name");          
    indexedSlicesQuery.addLtExpression("timestamp", ByteBufferUtil.string(date_s.toByteBuffer(date)));
    indexedSlicesQuery.addEqualsExpression("searchall", ByteBufferUtil.string(bs.toByteBuffer(true)));
    indexedSlicesQuery.setColumnFamily(column_family);
    indexedSlicesQuery.setStartKey("");
    System.out.println(indexedSlicesQuery.toString());
    QueryResult<OrderedRows<String, String, String>> res = indexedSlicesQuery.execute();


    List<Row<String, String, String>> list = res.get().getList();
    for (Row<?, ?, ?> row : list)
    {
        System.out.println(row.getKey());               
    }

}

Upvotes: 5

Related Questions