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