使用GoCQL驱动程序如何计算Cassandra表中的记录数?

huangapple go评论82阅读模式
英文:

How do I count the number of records in a Cassandra table using the GoCQL driver?

问题

我想用Go语言(最好使用GoCql)编写一个简单的程序来计算Cassandra表中记录的数量,这样我就可以减少一次性对数据库的负载量,并降低超时的概率。我只想计算带有where子句的元素数量。

如果可能的话,请简要提供答案,因为我是一个完全的新手。这将对我有很大帮助。

比如,查询给定userId的用户订单数量的查询语句可以是:

Select * from KeySpace.OrderTable where userid = userId
英文:

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

答案1

得分: 1

这是一个非常简化的应用程序,使用GoCQL驱动程序计算system.local表中local分区的行数:

package main

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

func main() {
    // 连接到本地运行的Cassandra集群
    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)
    }
}

请记住,你只应该计算分区内的行数。不受限制的查询(不限于分区键)将执行完整的表扫描,这是昂贵的,正如我在为什么在Cassandra中使用COUNT()是不好的中所记录的那样。祝好!

英文:

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!

huangapple
  • 本文由 发表于 2022年9月15日 18:23:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/73729475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定