API Documentation - v0.9.1

Version:

Introduction

Welcome to the Typesense API documentation. This documentation itself is open source. Please leave your feedback as issues on the GitHub repo or send us a pull-request to contribute edits.

To learn how to install and run Typesense, see our getting started guide instead.

API clients

At the moment, we have API clients for Javascript, Python, and Ruby.

We recommend that you use our API client library if it is available for your language.

gem install typesense
pip install typesense
// Node.js
npm install typesense

// Browser
<script src="dist/typesense.min.js"></script>

If you're using our Javascript client to access Typesense directly from the browser, be sure to start the Typesense server with the --enable-cors flag.

Authentication

require 'typesense'

client = Typesense::Client.new(
  master_node: {
    host:     'localhost',
    port:     8108,
    protocol: 'http',
    api_key:  '<API_KEY>'
  },

  read_replica_nodes: [
    {
      host:     'read_replica_1',
      port:     8108,
      protocol: 'http',
      api_key:  '<API_KEY>'
    }
  ],

  timeout_seconds: 2
)
import typesense

client = typesense.Client({
  'master_node': {
    'host': 'localhost',
    'port': '8108',
    'protocol': 'http',
    'api_key': '<API_KEY>'
  },
  'read_replica_nodes': [{
    'host': 'read_replica_1',
    'port': '8108',
    'protocol': 'http',
    'api_key': '<API_KEY>'
  }],
  'timeout_seconds': 2
})
/*
 *  Our Javascript client library works on both the client and the browser.
 *  When using the library on the browser, please be sure to use the
 *  search-only API Key rather than the master API key since the latter
 *  has write access to Typesense and you don't want to expose that.
 */
let client = new Typesense.Client({
  'masterNode': {
    'host': 'master',
    'port': '8108',
    'protocol': 'http',
    'apiKey': '<API_KEY>'
  },
  'readReplicaNodes': [{
    'host': 'read_replica_1',
    'port': '8108',
    'protocol': 'http',
    'apiKey': '<API_KEY>'
  }],
  'timeoutSeconds': 2
})
# API authentication is done via the `X-TYPESENSE-API-KEY` HTTP header.
curl -H "X-TYPESENSE-API-KEY: <API_KEY>" "http://localhost:8108/collections"

Usage

In Typesense, a group of related documents is called a collection. A collection is roughly equivalent to a table in a relational database.

Create a collection

When a collection is created, we give it a name and describe the fields that will be indexed from the documents that are added to the collection.

Your documents can contain other fields not mentioned in the collection's schema - they will be stored but not indexed.

schema = {
  'name'      => 'companies',
  'fields'    => [
    {
      'name'  => 'company_name',
      'type'  => 'string'
    },
    {
      'name'  => 'num_employees',
      'type'  => 'int32'
    },
    {
      'name'  => 'country',
      'type'  => 'string',
      'facet' => true
    }
  ],
  'default_sorting_field' => 'num_employees'
}

client.collections.create(schema)
schema = {
  'name': 'companies',
  'fields': [
    {
      'name'  :  'company_name',
      'type'  :  'string'
    },
    {
      'name'  :  'num_employees',
      'type'  :  'int32'
    },
    {
      'name'  :  'country',
      'type'  :  'string',
      'facet' :  True
    }
  ],
  'default_sorting_field': 'num_employees'
}

client.collections.create(schema)
let schema = {
  'name': 'companies',
  'num_documents': 0,
  'fields': [
    {
      'name': 'company_name',
      'type': 'string',
      'facet': false
    },
    {
      'name': 'num_employees',
      'type': 'int32',
      'facet': false
    },
    {
      'name': 'country',
      'type': 'string',
      'facet': true
    }
  ],
  'default_sorting_field': 'num_employees'
}

client.collections().create(schema)
curl "http://localhost:8108/collections" -X POST -H "Content-Type: application/json" \
       -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -d '{
         "name": "companies",
         "fields": [
           {"name": "company_name", "type": "string" },
           {"name": "num_employees", "type": "int32" },
           {"name": "country", "type": "string", "facet": true }
         ],
         "default_sorting_field": "num_employees"
       }'
Sample response
{
  "name": "companies",
  "num_documents": 0,
  "fields": [
    {"name": "company_name", "type": "string" },
    {"name": "num_employees", "type": "int32" },
    {"name": "country", "type": "string", "facet": true }
  ],
  "default_sorting_field": "num_employees"
}
Definition

POST ${TYPESENSE_HOST}/collections

Arguments
Parameter Required Description
name yes Name of the collection you wish to create.
fields yes

A list of fields that you wish to index for querying, filtering and faceting.

Apart from specifying the name and type for each field, a field of type string or string[] can be declared as a faceted field by setting its facet property to true.

Faceted fields are indexed verbatim without any tokenization or preprocessing. For example, if you are building a product search, color and brand could be defined as facet fields.

default_sorting_field yes

The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. For example, in a product search application, you could define num_reviews field as the default_sorting_field.

Additionally, when a word in a search query matches multiple possible words (either because of a typo or during a prefix search), this parameter is used to rank such equally matching tokens. For e.g. both "john" and "joan" are 1-typo away from "jofn". Similarly, in a prefix search, both "apple" and "apply" would match the prefix "app".

Supported search field types

Typesense allows you to index the following types of fields:

string
int32
int64
float
bool

You can define an array or multi-valued field by suffixing a [] at the end:

string[]
int32[]
int64[]
float[]
bool[]

Index a document

A document to be indexed in a given collection must conform to the schema of the collection.

If the document contains an `id` field of type `string`, Typesense would use that field as the identifier for the document. Otherwise, Typesense would assign an identifier of its choice to the document.

document = {
  'id'            => '124',
  'company_name'  => 'Stark Industries',
  'num_employees' => 5215,
  'country'       => 'USA'
}

client.collections['companies'].documents.create(document)
document = {
  'id': '124',
  'company_name': 'Stark Industries',
  'num_employees': 5215,
  'country': 'USA'
}

client.collections['companies'].documents.create(document)
let document = {
  'id': '124',
  'company_name': 'Stark Industries',
  'num_employees': 5215,
  'country': 'USA'
}

client.collections('companies').documents().create(document)
curl "http://localhost:8108/collections/companies/documents" -X POST \
        -H "Content-Type: application/json" \
        -H "X-TYPESENSE-API-KEY: abcd" \
        -d '{
          "id": "124",
          "company_name": "Stark Industries",
          "num_employees": 5215,
          "country": "USA"
        }'
Sample Response
{
  "id": "124",
  "company_name": "Stark Industries",
  "num_employees": 5215,
  "country": "USA"
}
Definition

POST ${TYPESENSE_HOST}/collections/:collection/documents

Search a collection

In Typesense, a search consists of a query against one or more text fields and a list of filters against numerical or facet fields. You can also sort and facet your results.

Due to performance reasons, Typesense limits searches to a maximum of 500 results.

search_parameters = {
  'q'         => 'stark',
  'query_by'  => 'company_name',
  'filter_by' => 'num_employees:>100',
  'sort_by'   => 'num_employees:desc'
}

client.collections['companies'].documents.search(search_parameters)
search_parameters = {
  'q'         : 'stark',
  'query_by'  : 'company_name',
  'filter_by' : 'num_employees:>100',
  'sort_by'   : 'num_employees:desc'
}

client.collections['companies'].documents.search(search_parameters)
let searchParameters = {
  'q'         : 'stark',
  'query_by'  : 'company_name',
  'filter_by' : 'num_employees:>100',
  'sort_by'   : 'num_employees:desc'
}

client.collections('companies').documents().search(searchParameters)
curl -H "X-TYPESENSE-API-KEY: abcd" \
    "http://localhost:8108/collections/companies/documents/search\
    ?q=stark&query_by=company_name&filter_by=num_employees:>100\
    &sort_by=num_employees:desc"
Sample response
{
  "facet_counts": [],
  "found": 1,
  "took_ms": 1,
  "hits": [
    {
      "highlights": [
        {
          "field": "company_name",
          "snippet": "<mark>Stark</mark> Industries"
        }
      ],
      "document": {
        "id": "124",
        "company_name": "Stark Industries",
        "num_employees": 5215,
        "country": "USA"
      }
    }
  ]
}

When a string[] field is queried, the highlights structure would include the corresponding matching array indices of the snippets. For e.g:

{
      ...
      "highlights": [
        {
          "field": "addresses",
          "indices": [0,2],
          "snippets": [
            "10880 <mark>Malibu</mark> Point, <mark>Malibu,</mark> CA 90265",
            "10000 <mark>Malibu</mark> Point, <mark>Malibu,</mark> CA 90265"
          ]
        }
      ],
      ...
}
Definition

GET ${TYPESENSE_HOST}/collections/:collection/documents/search

Arguments
Parameter Required Description
q yes

The query text to search for in the collection.

Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by.

For example, to return all documents that match a filter, use:
q=*&filter_by=num_employees:10

query_by yes

One or more string / string[] fields that should be queried against. Separate multiple fields with a comma: company_name, country

The order of the fields is important: a record that matches on a field earlier in the list is considered more relevant than a record matched on a field later in the list. So, in the example above, documents that match on the company_name field are ranked above documents matched on the country field.

prefix no

Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is necessary for building autocomplete and instant search interfaces.

Default: true

filter_by no

Filter conditions for refining your search results. Separate multiple conditions with && operator. Examples:

num_employees:10

num_employees:<=100 && country:[USA, UK]

country: USA

sort_by no

A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Separate multiple fields with a comma. Currently, upto 2 sort fields can be specified.

E.g. num_employees:desc,year_started:asc

If no sort_by parameter is specified, results are sorted by the default_sorting_field defined during the collection's creation.

facet_by no

A list of fields that will be used for faceting your results on. Separate multiple fields with a comma.

num_typos no

Number of typographical errors (1 or 2) that would be tolerated.

Damerau–Levenshtein distance is used to calculate the number of errors.

Default: 2

page no

Results from this specific page number would be fetched.

per_page no

Number of results to fetch per page.

include_fields no

Comma-separated list of fields from the document to include in the search result.

exclude_fields no

Comma-separated list of fields from the document to exclude in the search result.

drop_tokens_threshold no

If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set drop_tokens_threshold to 0 to disable dropping of tokens.

Default: 10

Retrieve a document

Fetch an individual document from a collection by using its id.
client.collections['companies'].documents['124'].retrieve
client.collections['companies'].documents['124'].retrieve()
client.collections('companies').documents('124').retrieve()
$ curl -H "X-TYPESENSE-API-KEY: abcd" -X GET \
      "http://localhost:8108/collections/companies/documents/124"
Sample response
{
  "id": "124",
  "company_name": "Stark Industries",
  "num_employees": 5215,
  "country": "USA"
}
Definition

GET ${TYPESENSE_HOST}/collections/:collection/documents/:id

Delete a document

Delete an individual document from a collection by using its id.

client.collections['companies'].documents['124'].delete
client.collections['companies'].documents('124').delete()
client.collections('companies').documents('124').delete()
curl -H "X-TYPESENSE-API-KEY: abcd" -X DELETE \
    "http://localhost:8108/collections/companies/documents/124"
Sample response
{
  "id": "124",
  "company_name": "Stark Industries",
  "num_employees": 5215,
  "country": "USA"
}
Definition

DELETE ${TYPESENSE_HOST}/collections/:collection/documents/:id

Retrieve a collection

Retrieve the details of a collection, given its name.

client.collections['companies'].retrieve
client.collections['companies'].retrieve()
client.collections('companies').retrieve()
curl -H "X-TYPESENSE-API-KEY: abcd" -X GET
    "http://localhost:8108/collections/companies"
Sample response
{
  "name": "companies",
  "num_documents": 1250,
  "fields": [
    {"name": "company_name", "type": "string"},
    {"name": "num_employees", "type": "int32"},
    {"name": "country", "type": "string", "facet": true}
  ],
  "default_sorting_field": "num_employees"
}
Definition

GET ${TYPESENSE_HOST}/collections/:collection

Export a collection

client.collections['companies'].documents.export
client.collections['companies'].documents.export()
client.collections('companies').documents().export()
curl -H "X-TYPESENSE-API-KEY: abcd" -X GET
    "http://localhost:8108/collections/companies/documents/export"
Sample response
[
"{\"id\": \"124\", \"company_name\": \"Stark Industries\", \"num_employees\": 5215, \
\"country\": \"US\"}",
"{\"id\": \"125\", \"company_name\": \"Future Technology\", \"num_employees\": 1232, \
\"country\": \"UK\"}",
"{\"id\": \"126\", \"company_name\": \"Random Corp.\", \"num_employees\": 531, \
\"country\": \"AU\"}"
]
[u'{"company_name":"Stark Industries","country":"USA","id":"124","num_employees":5215}',\
u'{"company_name":"Future Technology","country":"UK","id":"125","num_employees":1232}',\
u'{"company_name":"Random Corp.","country":"AU","id":"126","num_employees":531}']
['{"company_name":"Stark Industries","country":"USA","id":"124","num_employees":5215}',\
'{"company_name":"Future Technology","country":"UK","id":"125","num_employees":1232}',\
'{"company_name":"Random Corp.","country":"AU","id":"126","num_employees":531}']
{"id": "124", "company_name": "Stark Industries", "num_employees": 5215,\
"country": "US"}
{"id": "125", "company_name": "Future Technology", "num_employees": 1232,\
"country": "UK"}
{"id": "126", "company_name": "Random Corp.", "num_employees": 531,\
"country": "AU"}
Definition

GET ${TYPESENSE_HOST}/collections/:collection/documents/export

List all collections

Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first.

client.collections.retrieve
client.collections.retrieve()
client.collections().retrieve()
curl -H "X-TYPESENSE-API-KEY: abcd" "http://localhost:8108/collections"
Sample response
{
  "collections": [
    {
      "num_documents": 1250,
      "name": "companies",
      "fields": [
        {"name": "company_name", "type": "string"},
        {"name": "num_employees", "type": "int32"},
        {"name": "country", "type": "string", "facet": true}
      ],
      "default_sorting_field": "num_employees"
    },
    {
      "num_documents": 1250,
      "name": "ceos",
      "fields": [
        {"name": "company_name", "type": "string"},
        {"name": "full_name", "type": "string"},
        {"name": "from_year", "type": "int32"}
      ],
      "default_sorting_field": "num_employees"
    }
  ]
}
Definition

GET ${TYPESENSE_HOST}/collections

Drop a collection

Permanently drops a collection. This action cannot be done. For large collections, this might have an impact on read latencies.

client.collections['companies'].delete
client.collections['companies'].delete()
client.collections('companies').delete()
curl -H "X-TYPESENSE-API-KEY: abcd" -X DELETE
    "http://localhost:8108/collections/companies"
Sample response
{
  "name": "companies",
  "num_documents": 1250,
  "fields": [
    {"name": "company_name", "type": "string"},
    {"name": "num_employees", "type": "int32"},
    {"name": "country", "type": "string", "facet": true}
  ],
  "default_sorting_field": "num_employees"
}
Definition

DELETE ${TYPESENSE_HOST}/collections/:collection

API errors

Typesense API uses standard HTTP response codes to indicate the success or failure of a request.

Codes in the 2xx range indicate success, codes in the 4xx range indicate an error given the information provided (e.g. a required parameter was omitted), and codes in the 5xx range indicate an error with the Typesense service itself.

Error Code Meaning
400 Bad Request - The request could not be understood due to malformed syntax.
401 Unauthorized - Your API key is wrong.
404 Not Found - The requested resource is not found.
409 Conflict - When a resource already exists.
422 Unprocessable Entity - Request is well-formed, but cannot be processed.
503 Service Unavailable - We’re temporarily offline. Please try again later.