Trustfall 开源项目安装与使用指南

Trustfall 开源项目安装与使用指南

【免费下载链接】trustfall A query engine for any combination of data sources. Query your files and APIs as if they were databases! 【免费下载链接】trustfall 项目地址: https://gitcode.com/gh_mirrors/tr/trustfall

概述

Trustfall 是一个革命性的查询引擎,能够查询任何类型的数据源——从 API 和数据库到磁盘上的各种文件,甚至 AI 模型。它让你能够像查询数据库一样查询文件和 API,为数据查询提供了全新的范式。

核心特性

  • 多数据源支持:统一查询接口,支持 REST API、文件系统、数据库等
  • GraphQL 兼容语法:使用熟悉的 GraphQL 语法进行复杂查询
  • 高性能执行:基于 Rust 构建,提供卓越的性能表现
  • 跨平台支持:支持 Rust、Python、WASM 等多种运行环境
  • 类型安全:强类型系统确保查询的正确性

安装指南

前置要求

  • Rust 1.77+ 工具链
  • Python 3.9+(可选,用于 Python 绑定)
  • Node.js(可选,用于 WASM 构建)

Rust 环境安装

# 安装 Rust(Linux/macOS)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 或者使用包管理器安装
# Ubuntu/Debian
sudo apt install rustc cargo

# macOS
brew install rust

项目克隆与构建

# 克隆项目
git clone https://gitcode.com/gh_mirrors/tr/trustfall.git
cd trustfall

# 构建核心库
cargo build --release

# 运行测试确保安装正确
cargo test

Python 绑定安装

# 安装 Python 绑定
pip install trustfall

# 或者从源码安装
cd pytrustfall
pip install .

快速开始

基本使用示例

use trustfall::provider::BasicAdapter;
use trustfall_core::interpreter::execution::execute_query;

// 1. 定义 schema
let schema_str = r#"
    type User {
        name: String!
        age: Int!
        friends: [User!]!
    }
    
    type Query {
        allUsers: [User!]!
        userByName(name: String!): User
    }
"#;

// 2. 实现适配器
struct MyAdapter;
impl BasicAdapter for MyAdapter {
    // 实现必要的方法
}

// 3. 执行查询
let query = r#"
    {
        allUsers {
            name @output
            age @output
            friends {
                friendName: name @output
            }
        }
    }
"#;

let results = execute_query(adapter, schema, query, args);

HackerNews 查询示例

{
    FrontPage {
        ... on Story {
            title @output
            url @filter(op: "is_not_null") @output
            score @output
            
            byUser {
                submitter: id @output
                submitter_karma: karma @output
            }
        }
    }
}

核心概念

Schema 定义

Trustfall 使用 GraphQL Schema Definition Language (SDL) 定义数据模型:

type Article {
    title: String!
    content: String!
    author: User!
    comments: [Comment!]!
    tags: [String!]!
}

type User {
    name: String!
    email: String!
    articles: [Article!]!
}

type Query {
    allArticles: [Article!]!
    articleById(id: ID!): Article
    usersWithMinArticles(count: Int!): [User!]!
}

查询语法

Trustfall 扩展了 GraphQL 语法,添加了强大的指令系统:

指令功能示例
@output标记输出字段name @output
@filter添加过滤条件score @filter(op: ">=", value: ["10"])
@optional可选边遍历author @optional { name @output }
@recurse递归遍历comments @recurse(depth: 5)
@fold折叠结果tags @fold { tag: name @output }

适配器实现

实现 BasicAdapter trait 来连接数据源:

impl BasicAdapter for MyAdapter {
    fn resolve_starting_vertices(
        &self,
        edge_name: &str,
        parameters: &EdgeParameters,
    ) -> VertexIterator {
        // 实现起始顶点解析
    }
    
    fn resolve_property(
        &self,
        contexts: ContextIterator,
        type_name: &str,
        property_name: &str,
    ) -> PropertyIterator {
        // 实现属性解析
    }
    
    fn resolve_neighbors(
        &self,
        contexts: ContextIterator,
        type_name: &str,
        edge_name: &str,
        parameters: &EdgeParameters,
    ) -> VertexIterator {
        // 实现邻居解析
    }
}

实战案例

案例 1:查询 HackerNews 数据

# 运行 HackerNews 示例
cd trustfall
cargo run --example hackernews query examples/hackernews/example_queries/front_page_stories_with_links.ron

案例 2:Python 集成

from trustfall import Schema, Adapter, execute_query
from typing import Any, Dict, Iterator

class PythonAdapter(Adapter):
    def resolve_starting_vertices(self, edge_name: str, parameters: Dict[str, Any]) -> Iterator[Dict[str, Any]]:
        if edge_name == "allUsers":
            return iter([{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}])
        return iter([])
    
    # 实现其他必要方法

schema = Schema("""
    type User {
        name: String!
        age: Int!
    }
    type Query {
        allUsers: [User!]!
    }
""")

adapter = PythonAdapter()
query = """
    {
        allUsers {
            name @output
            age @output
        }
    }
"""

for result in execute_query(adapter, schema, query, {}):
    print(result)

案例 3:文件系统查询

{
    Directory(path: "/home/user/documents") {
        name @output
        size @output
        
        files {
            fileName: name @output
            fileSize: size @output
            extension @output
        }
        
        subdirectories {
            dirName: name @output
            fileCount: files @fold {
                count: _ @transform(op: "count") @output
            }
        }
    }
}

性能优化

查询优化技巧

  1. 尽早过滤:在查询开始时应用过滤器
  2. 限制结果集:使用 max 参数限制返回数量
  3. 批量处理:实现批处理逻辑减少 API 调用
  4. 缓存策略:对频繁访问的数据实现缓存
{
    # 好的实践:尽早过滤
    Users(filter: {age: {gt: 18}}) {
        name @output
        posts @filter(op: ">=", value: ["$min_posts"]) {
            title @output
        }
    }
}

内存管理

// 使用流式处理避免内存溢出
impl BasicAdapter for MyAdapter {
    fn resolve_starting_vertices(
        &self,
        edge_name: &str,
        parameters: &EdgeParameters,
    ) -> VertexIterator {
        // 返回迭代器而非Vec,支持流式处理
        Box::new(vertices.into_iter())
    }
}

常见问题解答

Q: Trustfall 与传统 GraphQL 有何不同?

A: Trustfall 扩展了 GraphQL 语法,添加了 @output@filter 等指令,支持更复杂的查询模式和数据转换。

Q: 支持哪些数据源?

A: 任何可以通过 Rust 或 Python 访问的数据源,包括:REST API、数据库、文件系统、内存数据结构等。

Q: 性能如何?

A: 基于 Rust 构建,性能接近原生代码水平。查询引擎经过高度优化,支持并行执行。

Q: 学习曲线如何?

A: 如果你熟悉 GraphQL,上手会很快。主要需要学习额外的指令系统和适配器实现。

进阶功能

自定义标量类型

scalar DateTime
scalar JSON
scalar Email

type User {
    name: String!
    email: Email!
    createdAt: DateTime!
    metadata: JSON!
}

参数化查询

query($min_score: Int!, $max_items: Int!) {
    TopStories(max: $max_items) {
        ... on Story {
            title @output
            score @filter(op: ">=", value: ["$min_score"]) @output
            url @output
        }
    }
}

复杂过滤条件

{
    Products {
        name @output
        price @output
        category @output
        
        # 多条件过滤
        @filter(op: "and", value: [
            {op: ">=", value: ["$min_price"]},
            {op: "<=", value: ["$max_price"]},
            {op: "in", value: ["$categories"]}
        ])
    }
}

生态系统集成

Web 前端集成

// 使用 WASM 版本在浏览器中运行
import { Trustfall } from 'trustfall-wasm';

const trustfall = await Trustfall.load();
const results = trustfall.executeQuery(adapter, schema, query, args);

后端服务集成

// Actix Web 集成示例
use actix_web::{web, App, HttpResponse, HttpServer};
use trustfall::provider::BasicAdapter;

async fn query_handler(
    adapter: web::Data<MyAdapter>,
    query: web::Json<QueryRequest>,
) -> HttpResponse {
    let results = execute_query(
        adapter.get_ref(),
        &schema,
        &query.query,
        &query.args,
    );
    
    HttpResponse::Ok().json(results.collect::<Vec<_>>())
}

总结

Trustfall 为数据查询带来了革命性的变化,它打破了传统数据源之间的壁垒,提供了一个统一的查询接口。无论你是要查询 REST API、数据库还是文件系统,Trustfall 都能让你用相同的语法和模式进行高效查询。

通过本指南,你应该已经掌握了 Trustfall 的安装、基本使用和高级功能。现在就开始使用 Trustfall,体验查询一切数据的强大能力吧!

下一步行动

  1. 安装 Rust 和 Trustfall
  2. 尝试运行示例查询
  3. 实现自己的数据源适配器
  4. 集成到现有项目中

记得在使用过程中参考官方文档和示例代码,遇到问题时可以查看项目的 issue 页面或参与社区讨论。

【免费下载链接】trustfall A query engine for any combination of data sources. Query your files and APIs as if they were databases! 【免费下载链接】trustfall 项目地址: https://gitcode.com/gh_mirrors/tr/trustfall

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值