6

In hyperledger fabric chaincode I want to check whether a key already exists or not, so that if another record with the same key is tried to be stored in the ledger, it should show up error. What is the best way to do this in fabric?

  • If you are using GOLang, perform stub.GetState(key) before adding the record. If it returns value, then the record with the key already exists. – anjy Jan 11 '19 at 06:56
  • I must query whole ledger data whether the key existed before or not, but its very resource and time consuming once data grows. Is there any other efficient way to do it, rather than querying all the blocks ? @anjy – kailashsharan Jan 11 '19 at 07:08
  • you can set datType for each category of data and query the key based on that category alone. – anjy Jan 11 '19 at 08:41
  • @kailashsharan if by time consuming you mean search takes long, say in Couch, you can create an index to get results in near-constant time – adnan.c Jan 11 '19 at 17:25

1 Answers1

2

Use

stub.GetState(key)

and check if it returns any value. The key is indexed so it will not be so time-consuming even using couchdb. The history is maintained by levelDB that is very performative for key queries.

But a quick tip, avoid couchdb, try to design you chaincode to use composite key and dont use rich queries if you want more performance and throughput.

Hope it helps.

Rodolfo Leal
  • 527
  • 5
  • 15
  • A quiestion: I'm using java, and stub.getState(key) returns a byte array even for keys that doesn't exists. The documentation says nothing about this case, so, how I know if the key exists or not – Eduardo Pascual Aseff Jun 08 '20 at 22:25
  • 1
    @EduardoPascualAseff you can check the length of the byte array. If it is zero then the key does not exist. – Anil8753 Mar 12 '22 at 08:17