使用LevelDB 实现富查询

     超级账本也可以使用CouchDBCouchDB可以支持类似于SQLselect语句来实现富查询。CouchDB可以避免使用任何客户端,只需要通过HTTP请求就可以操作数据库了。但是CouchDB的效率并不高,在不建立索引的情况下,对2-3万条的数据使用select语句就会导致查询非常耗时,从而导致合约函数的执行超时而失败。而对于传统的关系型数据库,2-3万条的数据量,在不建立索引的情况下,对查询的影响不是很明显[1]。

使用LevelDB 实现富查询

能用LevelDB实现富查询,需要我们做一些额外的工作。https://www.jianshu.com/p/b131a8503559

建立索引。
运用shim包中关于组合键的方法。

    // GetStateByPartialCompositeKey queries the state in the ledger based on
    // a given partial composite key. This function returns an iterator
    // which can be used to iterate over all composite keys whose prefix matches
    // the given partial composite key. The `objectType` and attributes are
    // expected to have only valid utf8 strings and should not contain
    // U+0000 (nil byte) and U+10FFFF (biggest and unallocated code point).
    // See related functions SplitCompositeKey and CreateCompositeKey.
    // Call Close() on the returned StateQueryIteratorInterface object when done.
    // The query is re-executed during validation phase to ensure result set
    // has not changed since transaction endorsement (phantom reads detected).
    GetStateByPartialCompositeKey(objectType string, keys []string) (StateQueryIteratorInterface, error)

    // CreateCompositeKey combines the given `attributes` to form a composite
    // key
. The objectType and attributes are expected to have only valid utf8
    // strings and should not contain U+0000 (nil byte) and U+10FFFF
    // (biggest and unallocated code point).
    // The resulting composite key can be used as the key in PutState().
    CreateCompositeKey(objectType string, attributes []string) (string, error)

    // SplitCompositeKey splits the specified key into attributes on which the
    // composite key was formed. Composite keys found during range queries
    // or partial composite key queries can therefore be split into their
    // composite parts.
    SplitCompositeKey(compositeKey string) (string, []string, error)

GetStateByPartialCompositeKey方法是采用一种前缀匹配的方法来进行键的匹配返回的。

也就是说,只能拿前面的复合键进行匹配,而不是后面部分。

举例来说当你有一个 “”年份~颜色~车号“”的索引时,只能使用 “”年份“”、“”年份~颜色“”来进行查询,而不能用“”颜色“”来进行查询。因此当我们有多键的复合主键时,各个键的顺序需要仔细思考一下。

[1]https://learnblockchain.cn/article/3831 总结超级账本合约开发过程中遇到的坑

猜你喜欢

转载自blog.csdn.net/sjh2100/article/details/128062402