【问题标题】:How to iterate through the list in aerospike using golang?如何使用golang遍历aerospike中的列表?
【发布时间】:2017-10-17 18:43:22
【问题描述】:

我正在使用列表数据类型(http://www.aerospike.com/docs/guide/cdt-list.html ) 在 aerospike 中使用 golang 客户端。我可以使用 ListInsertOp (https://godoc.org/github.com/aerospike/aerospike-client-go#ListInsertOp) 在给定条目的列表中插入值。

但是,我想使用 ListSetOp (https://godoc.org/github.com/aerospike/aerospike-client-go#ListSetOp) 或 ListRemoveOp (https://godoc.org/github.com/aerospike/aerospike-client-go#ListRemoveOp) 更新/删除给定的列表值

为了做到这一点,我需要一个索引。我怎样才能得到这个索引?有没有办法可以遍历所有列表值并获取索引,然后执行更新或删除操作?

【问题讨论】:

    标签: go aerospike


    【解决方案1】:

    假设您有一个名为List 的列表。 假设您想用newItem 替换名为value 的元素 你可以这样做:

    ...
    
    for index, item := range List {
         if item == value {
                 List[index] = newItem
         }
    }
    
    ...
    

    在上面的 sn-p 中,index 是元素 item 所在的索引。通过这种方式,您还可以将列表中特定索引上的元素替换为value

    操场上的示例:https://play.golang.org/p/qOmsY9fbL2

    【讨论】:

    • 问题不在于在 Go 中替换切片内的项目。 ListSetOp 背后的想法是替换列表中的单个项目而不写回整个列表。
    【解决方案2】:

    像往常一样,列表中的项目由它们从零开始的整数位置索引。 Aerospike 还支持从列表末尾向后开始的负索引。

    Lists documentation in the Aerospike:

    元素按整数位置排序。

    Lists documentation in the Aerospike's Node.js client:

    列表操作支持负索引。如果索引为负数,则解析的索引从列表末尾向后开始。

    索引/范围示例:

    • 索引 0:列表中的第一项。
    • 索引 4:列表中的第五项。
    • 索引 -1:列表中的最后一项。
    • 索引 -3:列表中倒数第三项。

    Go client source 中也提到过。

    list := []string{“a”, “b”, “c”, “d”, “e”}
    bin := aerospike.NewBin("listbin", list)
    err := client.PutBins(nil, key, bin)
    
    // to replace “d”:
    op := aerospike.ListSetOp(bin.Name, 3, "replaced")
    _, err = client.Operate(nil, key, op)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 2018-08-25
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      相关资源
      最近更新 更多