[eos8]智能合约开发-非主索引(附属索引)

2020-02-02  本文已影响0人  FriendOfTime

https://developers.eos.io/welcome/latest/getting-started/smart-contract-development/secondary-indices

开发者官网最近进行了更新,内容布局更加合理了。

secondary indices:附属索引,或者叫非主索引(纯个人翻译)。也就是除了primary index之外的其他索引。目前eos可以支持最多16个索引。

其实也就是类似关系数据库的索引,通过附属索引,可以快速对table进行排序或者查找。

流程参考官网即可,这里主要总结需要注意的点:

1、增加一列或者索引之前需要删除现有的数据

可以先通过这个命令查询当前数据:

然后再通过此命令删除:

问题:这简直是致命的啊,不明白为啥有这样的要求。还不如重新建一个multi-index table,在生产环境真有这么做的吗?有懂的可以留言讲解下

2、为multi-index table增加附属索引

语法:

typedef eosio::multi_index<"people"_n, person,indexed_by<"byage"_n, const_mem_fun<person, uint64_t, &person::get_secondary_1>>

  > address_index;

说明:

1)第三个参数indexed_by用于初始化一个索引

2)索引名字:byage

3)indexed_by的第三个参数是一个函数适配器(函数对象),用于指定作用于该索引上的排序方法

3、测试

注意:

--index 2表示使用附属索引查询。(Here the --index 2 parameter is used to indicate that the query applies to the secondary index)

问题:如果有多个附属索引如何显示?

4、附代码

#include <eosio/eosio.hpp>

#include <eosio/print.hpp>

using namespace eosio;

class [[eosio::contract("addressbook")]] addressbook : public eosio::contract {

public:

  addressbook(name receiver, name code,  datastream<const char*> ds): contract(receiver, code, ds) {}

  [[eosio::action]]

  void upsert(name user, std::string first_name, std::string last_name, uint64_t age, std::string street, std::string city, std::string state) {

    require_auth( user );

    address_index addresses( get_self(), get_first_receiver().value );

    auto iterator = addresses.find(user.value);

    if( iterator == addresses.end() )

    {

      addresses.emplace(user, [&]( auto& row ) {

      row.key = user;

      row.first_name = first_name;

      row.last_name = last_name;

      row.age = age;

      row.street = street;

      row.city = city;

      row.state = state;

      });

    }

    else {

      addresses.modify(iterator, user, [&]( auto& row ) {

        row.key = user;

        row.first_name = first_name;

        row.last_name = last_name;

        row.age = age;

        row.street = street;

        row.city = city;

        row.state = state;

      });

    }

  }

  [[eosio::action]]

  void erase(name user) {

    require_auth(user);

    address_index addresses( get_self(), get_first_receiver().value);

    auto iterator = addresses.find(user.value);

    check(iterator != addresses.end(), "Record does not exist");

    addresses.erase(iterator);

  }

private:

  struct [[eosio::table]] person {

    name key;

    std::string first_name;

    std::string last_name;

    uint64_t age;

    std::string street;

    std::string city;

    std::string state;

    uint64_t primary_key() const { return key.value; }

    uint64_t get_age() const { return age; }

  };

  // typedef eosio::multi_index<"people"_n, person> address_index;

  typedef eosio::multi_index<"people"_n, person,

    indexed_by<"byage"_n, const_mem_fun<person, uint64_t,

      &person::get_age>>> address_index;

};   

上一篇 下一篇

猜你喜欢

热点阅读