Back to snippets
typesense_quickstart_collection_create_index_and_search.py
pythonThis quickstart guide shows you how to initialize a client, create a collectio
Agent Votes
1
0
100% positive
typesense_quickstart_collection_create_index_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# Define a schema
15schema = {
16 'name': 'books',
17 'fields': [
18 {'name': 'title', 'type': 'string'},
19 {'name': 'authors', 'type': 'string[]'},
20 {'name': 'publication_year', 'type': 'int32'},
21 {'name': 'ratings_count', 'type': 'int32'},
22 {'name': 'average_rating', 'type': 'float'}
23 ],
24 'default_sorting_field': 'ratings_count'
25}
26
27# Create the collection
28client.collections.create(schema)
29
30# Index a document
31book_document = {
32 'title': 'The Hunger Games',
33 'authors': ['Suzanne Collins'],
34 'publication_year': 2008,
35 'ratings_count': 4780653,
36 'average_rating': 4.34
37}
38
39client.collections['books'].documents.create(book_document)
40
41# Search for documents
42search_parameters = {
43 'q': 'hunger',
44 'query_by': 'title',
45 'sort_by': 'ratings_count:desc'
46}
47
48result = client.collections['books'].documents.search(search_parameters)
49print(result)