gocql如何遍历来自SELECT查询的数据?

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

gocql how to walk through data come from a select query

问题

我一直在寻找一种从Cassandra中选择数据并加载到数组中的方法,因为我想处理系列数据,需要从前一个或下一个索引获取数据。
我找到的是一个迭代器,文档中的所有示例都是让它向下遍历。

谢谢。

英文:

I have looking for a way to select data from cassandra and load it to an array because I want to processing series data where I need to get data from previous or next indexes.
What I've found is an Iterator and all examples in doc make it walk to next

Thanks

答案1

得分: 2

看起来很简单。首先,确保你已连接到Cassandra:

// 连接
cluster := gocql.NewCluster(hostname)

if len(username) > 0 && len(password) > 0 {
    cluster.Authenticator = gocql.PasswordAuthenticator{Username: username, Password: password}
}

cluster.ProtoVersion = protocol_version
cluster.Consistency = consistency
session, _ := cluster.CreateSession()
defer session.Close()

接下来,我将查询system.peers表,遍历结果集,并使用append将对等节点存储在一个数组中。

var peer string
var peers []string

localCql := "SELECT peer FROM system.peers"

iter := session.Query(localCql).Iter()
for iter.Scan(&peer) {
    peers = append(peers, peer)
}
if err := iter.Close(); err != nil {
    log.Fatal(err)
}

fmt.Printf("peers = %s\n", peers)

运行代码将输出数组的内容:

» ./testCassandra 1.1.1.4 -u aploetz -p flynnLives
peers = [1.1.1.5 1.1.1.6 1.0.1.1 1.0.1.3 1.0.1.2]
英文:

> looking for a way to select data from cassandra and load it to an array

Sounds simple enough. First, make sure you're connecting:

//connect
cluster := gocql.NewCluster(hostname)

if len(username) > 0 && len(password) > 0 {
    cluster.Authenticator = gocql.PasswordAuthenticator{Username: username,Password: password}
}

cluster.ProtoVersion = protocol_version
cluster.Consistency = consistency
session, _ := cluster.CreateSession()
defer session.Close()

Next, I'll query the system.peers table, iterate through the result set and store the peers in an array using append.

var peer string
var peers []string

localCql := "SELECT peer FROM system.peers"

iter := session.Query(localCql).Iter()
for iter.Scan(&peer) {
    peers = append(peers, peer)
}
if err := iter.Close(); err != nil {
    log.Fatal(err)
}

fmt.Printf("peers = %s\n",peers)

And running it yields the contents of the array:

» ./testCassandra 1.1.1.4 -u aploetz -p flynnLives
peers = [1.1.1.5 1.1.1.6 1.0.1.1 1.0.1.3 1.0.1.2]

huangapple
  • 本文由 发表于 2021年6月16日 23:35:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/68005844.html
匿名

发表评论

匿名网友

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

确定