https://docs.tigrisdata.com/quickstart Skip to main content Signup for the Tigris beta and [?] give us a star on GitHub Tigris LogoTigris Logo TigrisDocsAPIBlog Slack Community * Overview * Quickstart * HTTP Reference * TypeScript Reference * Go Reference * Java Reference * Tutorials * Command Line Interface + Configuration + Working Locally + Reference * * Quickstart On this page Quickstart Tigris is the first truly open source developer data platform available with a simple yet powerful, unified API that spans search, event streaming, and transactional document store. It enables you to focus on building your applications and stop worrying about the data infrastructure. The following guide will get you up and running with Tigris. It covers data modeling, querying and searching. tip Quickly add data and easily retrieve or edit that data through simple and intuitive APIs. Easily evolve the data model as your application evolves without worrying about breaking a rigid schema. Startup Tigris on your local machine docker run -d -p 8081:8081 tigrisdata/tigris-local:latest Once this command has completed, Tigris will be available on port 8081. 5-minute quickstart * HTTP * TypeScript * Go * Java Prerequisites All you'll need is any computer running macOS or Linux. Creating database and collection For this quickstart we will create a database named sampledb and then create a collection users inside it. Creating a database is as easy as calling an API, and it is ready in an instant. curl -X POST http://localhost:8081/v1/databases/sampledb/create Similarly, a collection is instantaneously created through the API. In Tigris, a collection is an ordered set of records called documents that all follow a specific schema and whose fields are strongly typed. curl http://localhost:8081/v1/databases/sampledb/collections/users/createOrUpdate \ -X POST \ -H "Content-Type: application/json" \ -d '{ "schema": { "title": "users", "properties": { "balance": { "type": "number" }, "id": { "type": "integer", "format": "int32", "autoGenerate": true }, "name": { "type": "string" } }, "primary_key": [ "id" ] } }' The schema of the collections created above can be fetched as follows curl -X POST http://localhost:8081/v1/databases/sampledb/collections/users/describe Insert some documents The following example will replace documents with the same id if they already exist, or create new documents if they don't exist with the same id. curl http://localhost:8081/v1/databases/sampledb/collections/users/documents/insert \ -X POST \ -H "Content-Type: application/json" \ -d '{ "documents": [ {"name": "Jania McGrory", "balance": 6045.7}, {"name": "Bunny Instone", "balance": 2948.87} ] }' Read a document using the primary key field Read the document from the collection by using its id. curl http://localhost:8081/v1/databases/sampledb/collections/users/documents/read \ -X POST \ -H "Content-Type: application/json" \ -d '{ "filter": {"id": 1} }' Read a document using any field in the schema Read the document from the collection by using the field name. curl http://localhost:8081/v1/databases/sampledb/collections/users/documents/read \ -X POST \ -H "Content-Type: application/json" \ -d '{ "filter": {"name": "Jania McGrory"} }' Update a document Update one of the fields in a document by using its id. curl http://localhost:8081/v1/databases/sampledb/collections/users/documents/update \ -X PUT \ -H "Content-Type: application/json" \ -d '{ "fields": { "$set": {"balance": 2448.87} }, "filter": {"id": 2} }' Search Search for users with name like "bunny" and balance greater than 500 curl http://localhost:8081/v1/databases/sampledb/collections/users/documents/search \ -X POST \ -H "Content-Type: application/json" \ -d '{ "q": "bunny", "search_fields": ["name"], "filter": {"balance": {"$gt": 500}} }' Delete documents Use the delete API to remove the documents from the collection based on the filter. curl http://localhost:8081/v1/databases/sampledb/collections/users/documents/delete \ -X DELETE \ -H "Content-Type: application/json" \ -d '{ "filter": { "$or": [ {"id": 1}, {"id": 2} ] } }' Drop database Finally, drop the database sampledb we have created for this quickstart with all its collections. curl -X DELETE http://localhost:8081/v1/databases/sampledb/drop Prerequisites All you'll need is any computer running macOS or Linux, with NodeJS v12 or later installed. 1. Scaffold the tigris quickstart app Let's create a directory and run following commands to scaffold a TypeScript project $ mkdir hello-tigris $ cd hello-tigris $ npx create-tigris-app This command initializes following file structure in hello-tigris directory: . +-- package.json +-- src | +-- testScript.ts | +-- tigrisClient.ts | +-- repository | | +-- users.ts | +-- models | +-- user.ts +-- tsconfig.json * package.json is the node project metadata, and lists @tigrisdata/ core as one of the dependencies * src/testScript.ts is an empty file we will use to execute queries against Tigris database * src/tigrisClient.ts is an already created TypeScript client we will use to connect to Tigris DB * src/repository/users.ts is a boilerplate class where we will write some queries to perform CRUD operations on a collection * src/models/user.ts is a Tigris data model class used for this exercise * tsconfig.json is the TypeScript project config and won't be relevant for this tutorial Then, install the project dependencies $ npm install 2. Model data in a Tigris collection schema Tigris uses a declarative approach to database infrastructure and enforces that all documents stored in collection conform to the collection's schema. For our convenience, User schema definition is pre-populated in our project: src/models/user.ts import { TigrisCollectionType, TigrisDataTypes, TigrisSchema,} from "@tigrisdata/core/dist/types";export interface User extends TigrisCollectionType { userId?: number; name: string; balance: number;}export const userSchema: TigrisSchema = { userId: { type: TigrisDataTypes.INT32, primary_key: { order: 1, autoGenerate: true, }, }, name: { type: TigrisDataTypes.STRING, }, balance: { type: TigrisDataTypes.NUMBER, },}; In Tigris, models represent the collections in the underlying database. In the next section, we will map this User model to a collection. 3. Initialize Tigris client and setup database The already included TigrisClient in src/tigrisClient.ts uses Tigris's client library to establish a connection to database: src/tigrisClient.ts import { DB, Tigris } from "@tigrisdata/core";import { User, userSchema } from "./models/user";export class TigrisClient { private readonly dbName: string; private readonly tigris: Tigris; private _db: DB; constructor() { this.dbName = "hello_tigris"; this.tigris = new Tigris({ serverUrl: "localhost:8081", insecureChannel: true, }); } public get db(): DB { return this._db; } public async setup() { await this.initializeTigris(); } public async initializeTigris() { // create database (if not exists) this._db = await this.tigris.createDatabaseIfNotExists(this.dbName); console.log("db: " + this.dbName + " created successfully"); // register collections schema and wait for it to finish await Promise.all([ this._db.createOrUpdateCollection("users", userSchema), ]); } // drop the users collection public dropCollection = async () => { const resp = await this._db.dropCollection("users"); console.log(resp); };} This client also initializes a database named hello_tigris and creates a users collection conforming to schema defined in src/models /user.ts. info The example points to Tigris DB instance running in localhost:8081 and can be modified as per your environment. 4. Explore how to send queries to database This section is hands-on, we will use the Users class in src/ repository/users.ts to write some queries to interact with newly created collection. The class presents following boilerplate template for us to use: src/repository/users.ts import { User } from "../models/user";import { Collection, DB } from "@tigrisdata/core";export class Users { private readonly users: Collection; constructor(db: DB) { this.users = db.getCollection("users"); } // TODO: Add CRUD operations here} We will add create, read, update, delete and search operations to this collection class in next few sections. 4.1 Create a new User document Let's add following method in Users class in src/repository/users.ts to insert a document in collection: // .... boilerplate .... // Insert a user in collection public createUser = async (user: User) => { const createdUser = await this.users.insert(user); console.log(createdUser); } 4.2 Read a single document from collection Finding a user is relatively simple using findOne() construct // .... boilerplate .... // Get a single user from collection public getUser = async (userId: number) => { const user = await this.users.findOne({ userId: userId }); if (user !== undefined) { console.log(user); } else { console.log(`No user found matching userId = ${userId}`) } } 4.3 Read all User documents Tigris client also provides an easy to use streaming api to read multiple documents from collection. // .... boilerplate .... // Get all users from collection public getAllUsers = async () => { return new Promise((resolve, reject) => this.users.findAllStream({ onNext(user: User) { console.log(JSON.parse(JSON.stringify(user))); }, onEnd() { resolve(); }, onError(error: Error) { console.log(`Error fetching users ${error}`); reject(); } }) ); } 4.4 Update a User All collection APIs, including update(), use the same filter operations to target the query to selected documents. For example, to update a user balance: import {SelectorFilterOperator, UpdateFieldsOperator} from "@tigrisdata/core/dist/types"; // .... boilerplate .... // Update a user's "balance" public updateUserBalance = async (userName: string, newBalance: number) => { await this.users.update({ op: SelectorFilterOperator.EQ, fields: { name: userName } }, { op: UpdateFieldsOperator.SET, fields: { balance: newBalance } }); } 4.5 Search for Users Tigris offers a realtime search for documents in collection. Searching is by default enabled for a collection, no explicit setup required. Let's say, we want find users with name matching Amy: import {SearchRequest, SearchResult} from "@tigrisdata/core/dist/search/types"; // .... boilerplate .... // Search for users where name matches "nameLike" public searchUsers = async (nameLike: string) => { const query: SearchRequest = { q: nameLike }; return new Promise((resolve, reject) => this.users.search(query, { onNext(result: SearchResult) { for (let i = 0; i < result.hits.length; i++) { console.log(JSON.parse(JSON.stringify(result.hits[i].document))); } }, onEnd() { resolve(); }, onError(error: Error) { console.log(`Error searching for users ${error}`); reject(); } }) ); } 4.6 Delete a User The delete() operation follows same semantics as create/read/update APIs. // .... boilerplate .... // Delete a user by "userId" public deleteUser = async (userIdToDelete: number) => { await this.users.delete({ userId: userIdToDelete, }); } Before moving to next section, let's review what we did here. We used simple constructs offered by Tigris's client library and added create, read, update, delete and search capabilities in Users class to use users collection. 5. Use the database and perform some operations We now have a TigrisClient object that instantiates hello_tigris database and users collection for us, and a Users class that can perform CRUD operations on the collection. Let's add following code to the driver script in src/testScript.ts file: src/testScript.ts import { TigrisClient } from "./tigrisClient";import { Users } from "./repository/users";async function main() { const tigris = new TigrisClient(); await tigris.setup(); const usersCollection = new Users(tigris.db); console.log("\nInserting 3 users"); await usersCollection.createUser({ userId: 1, name: "Jania McGrory", balance: 100, }); await usersCollection.createUser({ userId: 2, name: "Amy Jackson", balance: 200, }); await usersCollection.createUser({ userId: 3, name: "Amylia Jones", balance: 80, }); console.log("\nRead user with userId = 2"); await usersCollection.getUser(2); console.log("\nReading all users"); await usersCollection.getAllUsers(); console.log("\nUpdate balance to 45 for userName = Jania McGrory"); await usersCollection.updateUserBalance("Jania McGrory", 45); console.log("Verify that update has processed"); await usersCollection.getUser(1); console.log("\nFind users with name like 'amy'"); await usersCollection.searchUsers("amy"); console.lo g("\nDelete userId = 3"); await usersCollection.deleteUser(3); console.log("Read all users to verify userId = 3 is deleted"); await usersCollection.getAllUsers(); console.log("\nDrop collection"); await tigris.dropCollection();}main().then((r) => console.log("\nQuickstart tutorial completed")); Now execute the above script using npm on CLI. $> npm run test db: hello_tigris created successfully {"title":"users","additionalProperties":false,"type":"object","properties":{"userId":{"type":"integer","format":"int32","autoGenerate":true},"name":{"type":"string"},"balance":{"type":"number"}},"collection_type":"documents","primary_key":["userId"]} Inserting 3 users { userId: 1, name: 'Jania McGrory', balance: 100 } { userId: 2, name: 'Amy Jackson', balance: 200 } { userId: 3, name: 'Amylia Jones', balance: 80 } Read user with userId = 2 { userId: 2, name: 'Amy Jackson', balance: 200 } Reading all users { userId: 1, name: 'Jania McGrory', balance: 100 } { userId: 2, name: 'Amy Jackson', balance: 200 } { userId: 3, name: 'Amylia Jones', balance: 80 } Update balance to 45 for name = Jania McGrory Verify that update has processed { userId: 1, name: 'Jania McGrory', balance: 45 } Find users with name like 'amy' { name: 'Amy Jackson', userId: 2, balance: 200 } { name: 'Amylia Jones', userId: 3, balance: 80 } Delete userId = 3 Read all users to verify userId = 3 is deleted { userId: 1, name: 'Jania McGrory', balance: 45 } { userId: 2, name: 'Amy Jackson', balance: 200 } Drop collection DropCollectionResponse { _status: 'dropped', _message: 'collection dropped successfully' } Quickstart tutorial completed Yay! we successfully executed our first few queries against Tigris database using TypeScript. 6. Next steps In this Quickstart guide, you have learnt how to get started with Tigris in a plain TypeScript project. Feel free to dive deeper into the dedicated reference guide for TypeScript or continue building a RESTful web app using Tigris Prerequisites All you'll need is any computer running macOS or Linux, with Golang 1.18 or newer installed. Install the client library go get -u github.com/tigrisdata/tigris-client-go@latest Quickstart main.go package main import ( "context" "fmt" "time" "github.com/tigrisdata/tigris-client-go/config" "github.com/tigrisdata/tigris-client-go/fields" "github.com/tigrisdata/tigris-client-go/filter" "github.com/tigrisdata/tigris-client-go/tigris" ) // User is a declaration of the model for the collection type User struct { tigris.Model Name string Balance float64 } func main() { ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() // Connect to the Tigris backend, create the database and collection if they don't exist, // otherwise update the schema of the collection if it already exists db, err := tigris.OpenDatabase(ctx, &config.Database{Driver: config.Driver{URL: "localhost:8081"}}, "hello_db", &User{}) if err != nil { panic(err) } // Get the collection object, all the CRUD operations on the collection will be performed // through this collection object users := tigris.GetCollection[User](db) // Insert userJ := User{Name: "Jania McGrory", Balance: 6045.7} userB := User{Name: "Bunny Instone", Balance: 2948.87} users.Insert(ctx, &userJ, &userB) // Read var user *User user, err = users.ReadOne(ctx, filter.Eq("ID", userJ.ID)) // find user with primary key field if err != nil { panic(err) } fmt.Println(user) user, err = users.ReadOne(ctx, filter.Eq("Name", "Jania McGrory")) // find user with Name Jania McGrory if err != nil { panic(err) } fmt.Println(user) // Update - update user's name users.Update(ctx, filter.Eq("ID", userJ.ID), fields.Set("Name", "Jania McGrover")) // Transaction - transfer balance between users db.Tx(ctx, func(txCtx context.Context) error { // update their balance if _, err = users.Update(txCtx, filter.Eq("ID", userJ.ID), fields.Set("Balance", userJ.Balance-100)); err != nil { return err } if _, err = users.Update(txCtx, filter.Eq("ID", userB.ID), fields.Set("Balance", userB.Balance+100)); err != nil { return err } return nil }) // Search for users with `Name` like "bunny" and `Balance` greater than 500 searchRequest := search.NewRequestBuilder(). WithQuery("bunny"). WithSearchFields("Name"). WithFilter(filter.Gt("Balance", 500)). Build() iterator, err := users.Search(ctx, searchRequest) if err != nil { panic(err) } var result search.Result[User] for iterator.Next(&result) { fmt.Printf("%#v", result) } // Delete - delete users with IDs 1 or 2 users.Delete(ctx, filter.Or(filter.Eq("ID", userJ.ID), filter.Eq("ID", userB.ID))) // Drop the database and its collections db.Drop(ctx) } Prerequisites All you'll need is any computer running macOS or Linux, with JDK 1.8 or newer installed. Add the client library dependency to your project com.tigrisdata tigris-client ${tigris.client.java.version} For latest version and for other dependency management or build tool you can refer to dependency snippet from here Quickstart TigrisApp.java import com.tigrisdata.db.annotation.TigrisPrimaryKey; import com.tigrisdata.db.client.Filters; import com.tigrisdata.db.client.InsertResponse; import com.tigrisdata.db.client.StandardTigrisClient; import com.tigrisdata.db.client.TigrisClient; import com.tigrisdata.db.client.TigrisCollection; import com.tigrisdata.db.client.TigrisDatabase; import com.tigrisdata.db.client.UpdateFields; import com.tigrisdata.db.client.config.TigrisConfiguration; import com.tigrisdata.db.client.error.TigrisException; import com.tigrisdata.db.type.TigrisCollectionType; import java.util.Objects; public class TigrisApp { public static void main(String[] args) throws TigrisException { // configure the client TigrisConfiguration config = TigrisConfiguration.newBuilder("localhost:8081") .withNetwork( TigrisConfiguration.NetworkConfig.newBuilder() .usePlainText() // for dev env - plaintext communication .build()) .build(); // initialize the client TigrisClient client = StandardTigrisClient.getInstance(config); // create the database if it does not exist, // and fetch the database object TigrisDatabase helloDB = client.createDatabaseIfNotExists("hello-db"); // create the collections if they don't exist, or // update the collection schema helloDB.createOrUpdateCollections(User.class); // fetch the collection object, all the CRUD operations on the // collection will be performed through this collection object TigrisCollection users = helloDB.getCollection(User.class); // insert User jania = new User("Jania McGrory", 6045.7); User bunny = new User("Bunny Instone", 2948.87); users.insert(jania); users.insert(bunny); // read the auto-generated ids int janiaId = jania.getUserId(); int bunnyId = bunny.getUserId(); // find the user by primary key field User user = users.readOne(Filters.eq("userId", janiaId)).get(); // find user with Name Jania McGrory User user = users.readOne(Filters.eq("name", "Jania McGrory")).get(); // update users.update( Filters.eq("userId", janiaId), UpdateFields.newBuilder() .set("name", "Jania McGrover") .build() ); // transaction - transfer balance between users helloDB.transact( (tx) -> { try { users.update( tx, Filters.eq("userId", janiaId), UpdateFields .newBuilder() .set("balance", jania.getBalance() - 100) .build()); users.update( tx, Filters.eq("userId", bunnyId), UpdateFields .newBuilder() .set("balance", bunny.getBalance() + 100) .build()); } catch (TigrisException tigrisException) { // auto-rollback after throwing exception. throw new IllegalStateException("Transaction failed", tigrisException); } }); // Search for users with `name` like "bunny" and `balance` greater than 500 SearchRequest request = SearchRequest.newBuilder() .withQuery("bunny") .withSearchFields("name") .withFilter(Filters.gt("balance", 500)) .build(); Iterator> results = users.search(request); while (results.hasNext()) { SearchResult result = results.next(); } // delete users users.delete(Filters.eq("userId", janiaId)); users.delete(Filters.eq("userId", bunnyId)); // drop the database and its collections client.dropDatabase("hello-db"); } public static class User implements TigrisCollectionType { @TigrisPrimaryKey(order = 1, autoGenerate = true) private int userId; private String name; private double balance; public User() { } public User(String name, double balance) { this.name = name; this.balance = balance; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return userId == user.userId && Double.compare(user.balance, balance) == 0 && Objects.equals(name, user.name); } @Override public int hashCode() { return Objects.hash(userId, name, balance); } } } Where to go from here? Browse through the docs in your own areas of interest, or join our Slack Community to ask any questions you might have. Signup for the private beta of Tigris Cloud - a fully managed version of Tigris, and try out the open source developer data platform in the cloud. Edit this page Last updated on Sep 20, 2022 by Ovais Tariq Previous Features Next HTTP Reference * Startup Tigris on your local machine * 5-minute quickstart + Prerequisites + 1. Scaffold the tigris quickstart app + 2. Model data in a Tigris collection schema + 3. Initialize Tigris client and setup database + 4. Explore how to send queries to database + 5. Use the database and perform some operations + 6. Next steps * Where to go from here? Copyright (c) 2022 Tigris Data, Inc.