英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论