Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

blockchain - how to write a function in chaincode that simply count the total records and return total number.hyperledger fabric

For example, we have a bank record, we use a query to get all the bank's record, I just wanted to create a function who simply return the total bank record and return number only


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do you mean the total number of records in CouchDB or just a particular type of record?

Anyhow, I'll propose solutions for both assuming you're using CouchDB as your state DB.

Reading the total number of records present in CouchDB from chaincode will just be a big overhead. You can simply make a GET API call like this http://couchdb.server.com/mydatabase and you'd get a JSON back looking something like this:

{
 "db_name":"mydatabase",
 "update_seq":"2786-g1AAAAFreJzLYWBg4MhgTmEQTM4vTc5ISXLIyU9OzMnILy7JAUoxJTIkyf___z8riYGB0RuPuiQFIJlkD1Naik-pA0hpPExpDj6lCSCl9TClwXiU5rEASYYGIAVUPR-sPJqg8gUQ5fvBygMIKj8AUX4frDyOoPIHEOUQt0dlAQB32XIg",
 "sizes":{
    "file":13407816,
    "external":3760750,
    "active":4059261
 },
 "purge_seq":0,
 "other": {
    "data_size":3760750
 },
 "doc_del_count":0,
 "doc_count":2786,
 "disk_size":13407816,
 "disk_format_version":6,
 "data_size":4059261,
 "compact_running":false,
 "instance_start_time":"0"
}

From here, you can simply read the doc_count value.

However, if you want to read the total number of docs in chaincode, then I should mention that it'll be a very costly operation and you might get a timeout error if the number of records is very high. For a particular type of record, you can use Couchdb selector syntax.

If you want to read all the records, then you can use getStateByRange(startKey, endKey) method and count all the records.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...