3

I am using the gocql library which is documented here: https://godoc.org/github.com/relops/cqlc/cqlc#Fetchable and am trying to write an API call in golang that will ask for all of the elements in my database that fulfill a particular field and return the total number of elements returned. I know when I am in the Cassandra interface I can use the call SELECT COUNT(*) from table1 WHERE ...; where table1 is the table name. I have been going through the documentation and all I can find is the limit function that limits the number of entries that are returned.

For example, just say I have a database table of events in Cassandra that take place on different days. I just want to return the number of events that take place on Tuesday, and I want to do this using gocql.

Currently I do something like:

cx := cqlc.NewContext()
iter, err := cx.Select().
            From(db.EVENTLOG).
            Where(db.EVENTLOG.DAY.Eq(day).
            Limit(10000).       
            Fetch(cass)
data, err = db.BindEventlog(iter)

The BindEventLog function returns an array of the events that happen on 'day' but again, I just want the number of events, not the events themselves. Is there a way to get this without iterating through this array because I am anyways going to throw out the array so it would be really slow to get the database to give me the entire array of data.

I am a beginner at this so if you need more information please ask, I tried to make this as specific as possible. Thanks.

user6407048
  • 181
  • 1
  • 3
  • 11

3 Answers3

2

I would prefer :

var count int
tc.Session.Query(`SELECT COUNT(*) FROM ks.tbl WHERE something = ? ALLOW FILTERING`, "something_else").Iter().Scan(&count)
print(count)

As the counting will be performed by the database itself but not by the application. soul's answer will also work but I prefer the count to be saved as integer and scanning to be done directly but not with additional loop

npocmaka
  • 55,367
  • 18
  • 148
  • 187
1

The closest thing I could find that would help you out is Iter.NumRows

If they paginate rows that won't give you what you're looking for. In the event that they do, this is a reasonable feature to request on their Github.

Ammar Bandukwala
  • 1,512
  • 10
  • 13
  • Thanks, I saw the NumRows thing too, but I didn't want to have to iterate through. I have contacted the developers already. I am asking for this functionality. – user6407048 Jun 14 '16 at 17:12
  • @user6407048 did you figure out any solution for the same yet? I am currently looking into it. I wish to get the count of total rows for a query. – Tanny Aug 21 '17 at 12:45
1

You can do like this

var count string
iter := session.Query(`SELECT count(*) FROM tablename`).Iter()
for iter.Scan(&count) {
    print(count)
}

You will get the count in count variable.

soul
  • 420
  • 1
  • 3
  • 11