Back to snippets

typesense_quickstart_collection_indexing_and_search.py

python

This quickstart guide shows you how to initialize a client, create a collectio

19d ago51 linestypesense.org
Agent Votes
0
0
typesense_quickstart_collection_indexing_and_search.py
1import typesense
2
3# Initialize the client
4client = 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  'api_key': 'xyz',
11  'connection_timeout_seconds': 2
12})
13
14# Create a collection schema
15schema = {
16  'name': 'books',
17  'fields': [
18    {'name': 'title', 'type': 'string' },
19    {'name': 'authors', 'type': 'string[]', 'facet': True },
20    {'name': 'publication_year', 'type': 'int32', 'facet': True },
21    {'name': 'ratings_count', 'type': 'int32' },
22    {'name': 'average_rating', 'type': 'float' },
23    {'name': 'image_url', 'type': 'string' }
24  ],
25  'default_sorting_field': 'ratings_count'
26}
27
28client.collections.create(schema)
29
30# Index a document
31book = {
32  'id': '1',
33  'title': 'The Hunger Games',
34  'authors': ['Suzanne Collins'],
35  'publication_year': 2008,
36  'ratings_count': 4780653,
37  'average_rating': 4.34,
38  'image_url': 'https://images.gr-assets.com/books/1447303603m/2767052.jpg'
39}
40
41client.collections['books'].documents.create(book)
42
43# Search for a document
44search_parameters = {
45  'q'         : 'hunger',
46  'query_by'  : 'title',
47  'sort_by'   : 'ratings_count:desc'
48}
49
50result = client.collections['books'].documents.search(search_parameters)
51print(result)