Skip to main content

Quickstart: TypeScript

The following guide will get you up and running with Tigris. It covers data modeling, creating database and collection, writing queries to read and write data, and performing search all without touching any infrastructure.

Prerequisitesโ€‹

You'll need any computer running macOS or Linux, with NodeJS v12 or later installed.

Install Tigris CLIโ€‹

Use the command below to install the CLI on macOS

brew install tigrisdata/tigris/tigris-cli

Alternative ways of installation can be found here.

Sign up for Tigris Cloudโ€‹

You will need to have a Tigris Cloud account to complete this quickstart. If you don't already have an account, you can sign up here.

Login and set up the application credentialsโ€‹

Login to your Tigris Cloud account

tigris login

The next step is to generate credentials to be used by the application we will be building in this quickstart

tigris create application quickstart "quickstart application"

Once the command is executed, it would create the application credentials (clientID and clientSecret) and print it on the screen. Make a note of id and secret from the output.

Output
{
"id": "your_client_id_here",
"name": "quickstart",
"description": "quickstart application",
"secret": "your_client_secret_here",
"created_at": 1666248043000,
"created_by": "google-oauth2|xxx"
}

Quickstartโ€‹

1. Scaffold a new TypeScript project pre-configured with Tigrisโ€‹

Let's create a directory and navigate to it

mkdir hello-tigris && cd hello-tigris

Now run the following command to scaffold a TypeScript project

npx @tigrisdata/create-tigris-app@latest

When prompted use api.preview.tigrisdata.cloud as the url of the Tigris instance. And use the clientID and clientSecret from the output of the tigris create application command above.

Output
โœ” What is the package-name (default: hello-tigris) ? ยท
โœ” Where do you want the project to be generated (default: /Users/ovaistariq/projects/hello-tigris) ? ยท
โœ” What is the url for your Tigris instance (default: api.preview.tigrisdata.cloud) ? ยท
โœ” What is the clientId ? ยท your_client_id_here
โœ” What is the client secret ? ยท ****************************************************************
Initializing Tigris quickstart application
๐ŸŽ‰ Initialized the Tigris quickstart application successfully
Run following command to install dependencies
npm install
Learn more at https://docs.tigrisdata.com/quickstart

This command initializes following file structure in hello-tigris directory:

.
โ”œโ”€โ”€ scripts
โ”‚ โ””โ”€โ”€ setup.ts
โ”œโ”€โ”€ src
โ”‚ โ””โ”€โ”€ lib
โ”‚ โ””โ”€โ”€ tigris.ts
โ”‚ โ””โ”€โ”€ models
โ”‚ โ””โ”€โ”€ hello_tigris
โ”‚ โ””โ”€โ”€ user.ts
โ”‚ โ””โ”€โ”€ repository
โ”‚ โ””โ”€โ”€ users.ts
โ”‚ โ””โ”€โ”€ index.ts
โ”œโ”€โ”€ .env
โ””โ”€โ”€ tsconfig.json
โ”œโ”€โ”€ package.json

Now install the project dependencies

npm install

2. Modeling data in a Tigris collectionโ€‹

Tigris stores documents in collections. Each collection needs to have a schema defined and all documents stored in the collection conform to the schema.

For your convenience, a sample schema of the user collection has been pre-populated in the project. It is shown below:

src/models/hello_tigris/user.ts
import {  TigrisCollectionType,  TigrisDataTypes,  TigrisSchema,} from "@tigrisdata/core/dist/types";export interface User extends TigrisCollectionType {  userId?: string;  name: string;  balance: number;}export const userSchema: TigrisSchema<User> = {  userId: {    type: TigrisDataTypes.INT64,    primary_key: {      order: 1,      autoGenerate: true,    },  },  name: {    type: TigrisDataTypes.STRING,  },  balance: {    type: TigrisDataTypes.NUMBER,  },};

3. Connecting to Tigris and creating the database and collectionโ€‹

The project has been pre-configured with the Tigris connection configuration. The connection URL, clientID and clientSecret are stored in the .env file.

Let's run the project setup which will look for model definitions in the src/models directory and create the necessary database and collections.

The model file hello_tigris/user.ts results in

  1. The database created with the name hello_tigris
  2. The collection user created using the model defined in user.ts
npm run setup
Output
event - Scanning /Users/ovaistariq/projects/hello-tigris/src/models for Tigris schema definitions
info - Found DB definition hello_tigris
info - Found Schema file user.ts in hello_tigris
info - Found schema definition: userSchema
debug - Generated Tigris Manifest: [{"dbName":"hello_tigris","collections":[{"collectionName":"user","schema":{"userId":{"type":"int64","primary_key":{"order":1,"autoGenerate":true}},"name":{"type":"string"},"balance":{"type":"number"}},"schemaName":"userSchema"}]}]
event - Created database: hello_tigris
debug - {"title":"user","additionalProperties":false,"type":"object","properties":{"userId":{"type":"integer","format":"int64","autoGenerate":true},"name":{"type":"string"},"balance":{"type":"number"}},"collection_type":"documents","primary_key":["userId"]}
event - Created collection: user from schema: userSchema in db: hello_tigris
Setup complete ...

4. Exploring how to send queries to Tigrisโ€‹

In this section we will be modifying the UsersRepository in src/repository/users.ts and will perform some queries to interact with the user collection.

4.1 Create a new User documentโ€‹

Let's start with a query to create a new User document and log it to the console. Add the highlighted code below to the file src/repository/users.ts

src/repository/users.ts
import {User} from "../models/hello_tigris/user";import {Collection, DB} from "@tigrisdata/core";import {SelectorFilterOperator} from "@tigrisdata/core/dist/types";import {SearchRequest, SearchResult} from "@tigrisdata/core/dist/search/types";export class UsersRepository {  private readonly users: Collection<User>;  constructor(db: DB) {    this.users = db.getCollection<User>("user");  }  // TODO: Add implementation  // Create a user record  public create = async (user: User) => {    const createdUser = await this.users.insertOne(user);    console.log(createdUser);  };  // > Rest of the code is collapsed}

Next update the file src/index.ts with the code highlighted below.

src/index.ts
import dotenv from "dotenv";dotenv.config();import tigrisDB from "./lib/tigris";import { UsersRepository } from "./repository/users";async function main() {  // initialize the repository  const repository = new UsersRepository(tigrisDB);  // TODO: perform queries  await repository.create({    name: "Jane Garcia",    balance: 100,  });  await repository.create({    name: "Jane Jerome",    balance: 300,  });  await repository.create({    name: "Alice Bloom",    balance: 200,  });}main()  .then(async () => {    console.log("All done ...");  })  .catch(async (e) => {    console.error(e);    process.exit(1);  });

And execute the src/index.ts file again

npx ts-node src/index.ts
Output
{ name: 'Jane Garcia', balance: 100, userId: '1667280097048625549' }
{ name: 'Jane Jerome', balance: 300, userId: '1667280097106284124' }
{ name: 'Alice Bloom', balance: 200, userId: '1667280097158833650' }
All done ...

Great job, you just created your first user records.

4.2 Retrieve all documents from the collectionโ€‹

Tigris provides rich querying functionality to read data. In this section we will be using the findMany operation to retrieve all the documents in the user collection.

Add the highlighted code below to the file src/repository/users.ts

src/repository/users.ts
import {User} from "../models/hello_tigris/user";import {Collection, DB} from "@tigrisdata/core";import {SelectorFilterOperator} from "@tigrisdata/core/dist/types";import {SearchRequest, SearchResult} from "@tigrisdata/core/dist/search/types";export class UsersRepository {  private readonly users: Collection<User>;  constructor(db: DB) {    this.users = db.getCollection<User>("user");  }  // TODO: Add implementation  // Create a user record  public create = async (user: User) => {    const createdUser = await this.users.insertOne(user);    console.log(createdUser);  };  // TODO: Add implementation  // Read all users from the collection  public findAll = async () => {    const usersCursor = this.users.findMany();    try {      for await (const user of usersCursor) {        console.log(`UserId: ${user.userId}, Name: ${user.name}, Balance: ${user.balance}`);      }    } catch (e) {      console.error(e);    }  };  // > Rest of the code is collapsed}

Now delete the create calls, and add the call to findAll instead in the file src/index.ts.

src/index.ts
import dotenv from "dotenv";dotenv.config();import tigrisDB from "./lib/tigris";import { UsersRepository } from "./repository/users";async function main() {  // initialize the repository  const repository = new UsersRepository(tigrisDB);  // TODO: perform queries  await repository.findAll();}main()  .then(async () => {    console.log("All done ...");  })  .catch(async (e) => {    console.error(e);    process.exit(1);  });

Let's execute the src/index.ts file again

npx ts-node src/index.ts
Output
UserId: 1667280097048625549, Name: Jane Garcia, Balance: 100
UserId: 1667280097106284124, Name: Jane Jerome, Balance: 300
UserId: 1667280097158833650, Name: Alice Bloom, Balance: 200
All done ...

You have now successfully performed a query on the user collection.

4.3 Explore search queries with Tigrisโ€‹

Tigris automatically indexes the data in your collections and provides real-time search functionality out of the box. This eliminates the need for Elasticsearch.

Add the highlighted code below to the file src/repository/users.ts

src/repository/users.ts
import {User} from "../models/hello_tigris/user";import {Collection, DB} from "@tigrisdata/core";import {SelectorFilterOperator} from "@tigrisdata/core/dist/types";import {SearchRequest, SearchResult} from "@tigrisdata/core/dist/search/types";export class UsersRepository {  private readonly users: Collection<User>;  constructor(db: DB) {    this.users = db.getCollection<User>("user");  }  // TODO: Add implementation  // Create a user record  public create = async (user: User) => {    const createdUser = await this.users.insertOne(user);    console.log(createdUser);  };  // TODO: Add implementation  // Read all users from the collection  public findAll = async () => {    const usersCursor = this.users.findMany();    try {      for await (const user of usersCursor) {        console.log(`UserId: ${user.userId}, Name: ${user.name}, Balance: ${user.balance}`);      }    } catch (e) {      console.error(e);    }  };  // TODO: Add implementation  // Search user records by name  public search = async (name: string) => {    const request: SearchRequest<User> = {      q: name,      searchFields: ["name"],    };    const results = this.users.searchStream(request);    try {      for await (const res of results) {        console.log(`Search results found: ${res.meta.found}`)        for (let hit of res.hits) {          const user = hit.document;          console.log(`UserId: ${user.userId}, Name: ${user.name}, Balance: ${user.balance}`);        }      }    } catch (e) {      console.error(e);    }  };  // > Rest of the code is collapsed}

Now delete the findAll call, and add the call to search instead in the file src/index.ts.

src/index.ts
import dotenv from "dotenv";dotenv.config();import tigrisDB from "./lib/tigris";import { UsersRepository } from "./repository/users";async function main() {  // initialize the repository  const repository = new UsersRepository(tigrisDB);  // TODO: perform queries  await repository.search("jane");}main()  .then(async () => {    console.log("All done ...");  })  .catch(async (e) => {    console.error(e);    process.exit(1);  });

Let's execute the src/index.ts file again

npx ts-node src/index.ts
Output
Search results found: 2
UserId: 1667280097106284124, Name: Jane Jerome, Balance: 300
UserId: 1667280097048625549, Name: Jane Garcia, Balance: 100
All done ...

You successfully performed the search query on the user collection without needing any additional database like Elasticsearch.

5. Next stepsโ€‹

In this Quickstart guide, you have learned how to get started with Tigris in a TypeScript project. Feel free to dive deeper with the dedicated reference guide for TypeScript.

Where to go from here?โ€‹

๐Ÿš€ Signup for the beta of Tigris Cloud - a fully managed version of Tigris, and try out the open source developer data platform in the cloud.

Browse through the docs in your own areas of interest, or join our Slack or Discord community to ask any questions you might have.