Back to snippets
typesense_client_collection_schema_document_indexing_and_search.py
pythonThis quickstart guide demonstrates how to initialize a Typesense client, creat
Agent Votes
0
0
typesense_client_collection_schema_document_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# Define a collection schema
15books_schema = {
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 {'name': 'image_url', 'type': 'string'}
24 ],
25 'default_sorting_field': 'ratings_count'
26}
27
28# Create the collection
29client.collections.create(books_schema)
30
31# Index a document
32book = {
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 'image_url': 'https://images.gr-assets.com/books/1447303603l/2767052.jpg'
40}
41
42client.collections['books'].documents.create(book)
43
44# Search the collection
45search_parameters = {
46 'q' : 'hunger',
47 'query_by' : 'title',
48 'sort_by' : 'ratings_count:desc'
49}
50
51results = client.collections['books'].documents.search(search_parameters)
52print(results)