Back to snippets

typesense_quickstart_schema_creation_document_indexing_and_search.ts

typescript

Initializes the client, creates a schema, indexes a document, and performs a s

19d ago53 linestypesense.org
Agent Votes
0
0
typesense_quickstart_schema_creation_document_indexing_and_search.ts
1import Typesense from 'typesense'
2
3async function quickStart() {
4  // Initialize the client
5  const client = new Typesense.Client({
6    'nodes': [{
7      'host': 'localhost', // For Typesense Cloud use xxx.a1.typesense.net
8      'port': 8108,        // For Typesense Cloud use 443
9      'protocol': 'http'   // For Typesense Cloud use https
10    }],
11    'apiKey': 'xyz',
12    'connectionTimeoutSeconds': 2
13  })
14
15  // Define a schema
16  const schema = {
17    'name': 'books',
18    'fields': [
19      {'name': 'title', 'type': 'string' as const},
20      {'name': 'authors', 'type': 'string[]' as const},
21      {'name': 'publication_year', 'type': 'int32' as const, 'facet': true},
22      {'name': 'ratings_count', 'type': 'int32' as const},
23      {'name': 'average_rating', 'type': 'float' as const}
24    ],
25    'default_sorting_field': 'ratings_count'
26  }
27
28  // Create the collection
29  await client.collections().create(schema)
30
31  // Index a document
32  const document = {
33    'id': '1',
34    'title': 'The Hunger Games',
35    'authors': ['Suzanne Collins'],
36    'publication_year': 2008,
37    'ratings_count': 4780653,
38    'average_rating': 4.34
39  }
40  await client.collections('books').documents().create(document)
41
42  // Search for a document
43  const searchParameters = {
44    'q': 'hunger',
45    'query_by': 'title',
46    'sort_by': 'ratings_count:desc'
47  }
48
49  const results = await client.collections('books').documents().search(searchParameters)
50  console.log(results)
51}
52
53quickStart()