grapql api oh the graph

596 阅读2分钟

graphql scheme 定义

我们在schema.graphql中定义了Entity

  1. 对于我们定义的Entitythe graph都会在内部为我们生成entity(查询单个对象)entities(查询对象列表)两个顶级的Query type
    • 假设我们定义了一个下面的Entity
    type ExampleEntity @entity {
      id: ID!
      count: BigInt!
      hash: Bytes! # bytes32
      exchange: Bytes! # address
    }
    
    • query a single entity
    {
       exampleEntity(id: "0x1121211212") {
           id
       }
    }
    
    • query a list of entities
    {
      exampleEntities {
          hash
          id
      }  
    }
    

支持的查询能力

  1. 排序(Sorting
{
   exampleEntities(sortBy: count, orderDirection: asc) {
         hash
         count
   }   
}
  1. 分页(Pagenation
// 查询10条数据,从10条开始
{
   exampleEntities(first: 10, skip: 10) {
         hash
         count
   }   
}

TIPS:

  • 默认排序规则是按照ID 的字母数字升序,而不是创建时间
  • skip参数要避免过大的值,因为查询性能不好
  • 如果客户端需要查询大数据量的实体,先使用一个基础属性值进行查询,然后对这个基础属性值做过滤,会更加的高效(第一次,它会发送带有 lastID = "" 的查询,并且对于后续请求,会将 lastID 设置为前一个请求中最后一个实体的 id 属性。这种方法的性能明显优于使用增加的跳过值)
  • 默认查询列表会返回100条数据,最大单次查询指定上限为1000,可以使用skip进行分页!!!
  1. 过滤(Filtering
// 使用where来设置过滤条件
// 等于指定的值
{
   exampleEntities(first: 10, where: {count: 10}) {
         hash
         count
   }   
}
// 一些查询后缀
_not_gt_lt_gte_lte_in_not_in_contains_not_contains_starts_with_ends_with_not_starts_with_not_ends_with
// count 大于10
{
   exampleEntities(first: 10, where: {count_gt: 10}) {
         hash
         count
   }   
}

TIPS:

  • 可以设置多个过滤条件
  1. 查询历史数据(不仅仅是当前块)
{
  exampleEntities(first: 10, block: {number: 890000}){
    id
  }
}
  1. 全文检索(fulltxt query search) TIPS:

Schema定义

  1. The Graph使用标准的Grapshql interface defination language
  2. The Graph只支持queries定义,并且自动生成对应的代码
  3. 目前,The Graph要求每一个被@entity指令标记的Entity必须包含一个ID

参考

  1. thegraph.com/docs/develo…