5

Is there a chaincode shim function with which I can retrieve all the keys (maybe including values) of the world state in a Hyperledger Fabric chaincode?

Foo L
  • 10,977
  • 8
  • 40
  • 52

2 Answers2

5

In chaincode API GetStateByRange(startKey, endKey string), the startKey and endKey can be empty string, which implies an unbounded range query on start or end. Leave them both as empty string to get the full set of key/values returned.

Dave Enyeart
  • 2,523
  • 14
  • 23
2

It is possible to iterate over all the keys in the chaincode state of a particular chaincode using the stub.GetStateByRange() function.

Eg:

    keysIter, err := stub.GetStateByRange(startKey, endKey)
    if err != nil {
        return shim.Error(fmt.Sprintf("keys operation failed. Error accessing state: %s", err))
    }
    defer keysIter.Close()

    var keys []string
    for keysIter.HasNext() {
        key, _, iterErr := keysIter.Next()
        if iterErr != nil {
            return shim.Error(fmt.Sprintf("keys operation failed. Error accessing state: %s", err))
        }
        keys = append(keys, key)
    }

See the complete chaincode in the Hyperledger fabric repo

Clyde D'Cruz
  • 1,915
  • 1
  • 14
  • 36
  • 2
    I'm looking at the doc here: https://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub.GetStateByRange . Lexical order means I should go to get all keys from "a" to "ZZZZZZZZZZZZZZZZZ" (depending on the maximum length of keys)? – Foo L Mar 07 '17 at 04:25
  • 1
    why don't you mention that startKey and endKey can be empty? otherwise, the answer doesn't look useful – Next Developer May 21 '19 at 21:19
  • @FooL that link is not working anymore. If I put a range from "a" to "{", does it works for getting all keys starting with a letter? – Eduardo Pascual Aseff Jun 10 '20 at 03:11
  • 1
    @EduardoPascualAseff I'm not working on hyperledger now, but from others' comments, it seems you can leave the `startKey` & `endKey` blank to get the full range – Foo L Jun 11 '20 at 01:35
  • 1
    @FooL thanks, I resolved yet, my problem was that I'm using compositeKeys, that are not returned by `getStateByRange` – Eduardo Pascual Aseff Jun 11 '20 at 04:46