user6407048
user6407048

Reputation: 181

How to get the number of rows returned by a query using gocql

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.

Upvotes: 3

Views: 2886

Answers (3)

npocmaka
npocmaka

Reputation: 57282

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

Upvotes: 2

soul
soul

Reputation: 440

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.

Upvotes: 1

Ammar Bandukwala
Ammar Bandukwala

Reputation: 1572

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.

Upvotes: 1

Related Questions