2

I wanted write a simple program in golang (prefer GoCql) to count the number of records in a Cassandra table. so I can reduce the amount of load on db at a time and reduce the probability of timeouts. I just wanted to count the number of elements with where clause.

Please suggest the answers in brief if possible, I'm a complete newbie. It will help me a lot.

Like a query of count number of order of a user with a given userId

Select * from KeySpace.OrderTable where userid = userId
James Z
  • 12,209
  • 10
  • 24
  • 44
Ravi
  • 31
  • 4

1 Answers1

1

Here's an extremely simplified app that counts the number of rows in the system.local table for the partition local using the GoCQL driver:

package main

import (
    "fmt"
    "github.com/gocql/gocql"
)

func main() {
    // connect to a Cassandra cluster running locally
    cluster := gocql.NewCluster("127.0.0.1:9042")
    session, _ := _cluster.CreateSession()

    iter := session.Query(`SELECT COUNT(version) FROM system.local WHERE key = 'local'`).Iter()
    for iter.Scan(&rows) {
        fmt.Printf("%d rows\n", rows)
    }
}

Just remember that you should only count rows within a partition. Unbounded queries (not restricted to a partition key) will do a full table scan which is expensive as I've documented in Why COUNT() is bad in Cassandra. Cheers!

Erick Ramirez
  • 13,964
  • 1
  • 18
  • 23