|
| 1 | +import typesense |
| 2 | + |
| 3 | +# Aliasing is a Typesense Premium feature (see: https://typesense.org/premium) |
| 4 | + |
| 5 | +client = typesense.Client({ |
| 6 | + 'master_node': { |
| 7 | + 'host': 'localhost', |
| 8 | + 'port': '8108', |
| 9 | + 'protocol': 'http', |
| 10 | + 'api_key': 'abcd' |
| 11 | + }, |
| 12 | + 'read_replica_nodes': [{ |
| 13 | + 'host': 'localhost', |
| 14 | + 'port': '9108', |
| 15 | + 'protocol': 'http', |
| 16 | + 'api_key': 'abcd' |
| 17 | + }], |
| 18 | + 'timeout_seconds': 2 |
| 19 | +}) |
| 20 | + |
| 21 | +# Create a collection |
| 22 | + |
| 23 | +create_response = client.collections.create({ |
| 24 | + "name": "books_january", |
| 25 | + "fields": [ |
| 26 | + {"name": "title", "type": "string" }, |
| 27 | + {"name": "authors", "type": "string[]" }, |
| 28 | + {"name": "authors_facet", "type": "string[]", "facet": True }, |
| 29 | + {"name": "publication_year", "type": "int32" }, |
| 30 | + {"name": "publication_year_facet", "type": "string", "facet": True }, |
| 31 | + {"name": "ratings_count", "type": "int32" }, |
| 32 | + {"name": "average_rating", "type": "float" }, |
| 33 | + {"name": "image_url", "type": "string" } |
| 34 | + ], |
| 35 | + "default_sorting_field": "ratings_count" |
| 36 | +}) |
| 37 | + |
| 38 | +print(create_response) |
| 39 | + |
| 40 | +# Create or update an existing alias |
| 41 | + |
| 42 | +create_alias_response = client.aliases.upsert('books', { |
| 43 | + "collection_name": "books_january" |
| 44 | +}) |
| 45 | + |
| 46 | +print(create_alias_response) |
| 47 | + |
| 48 | +# Add a book using the alias name `books` |
| 49 | + |
| 50 | +hunger_games_book = { |
| 51 | + 'id': '1', 'original_publication_year': 2008, 'authors': ['Suzanne Collins'], 'average_rating': 4.34, |
| 52 | + 'publication_year': 2008, 'publication_year_facet': '2008', 'authors_facet': ['Suzanne Collins'], |
| 53 | + 'title': 'The Hunger Games', |
| 54 | + 'image_url': 'https://images.gr-assets.com/books/1447303603m/2767052.jpg', |
| 55 | + 'ratings_count': 4780653 |
| 56 | +} |
| 57 | + |
| 58 | +client.collections['books'].documents.create(hunger_games_book) |
| 59 | + |
| 60 | +# Search using the alias |
| 61 | + |
| 62 | +print(client.collections['books'].documents.search({ |
| 63 | + 'q': 'hunger', |
| 64 | + 'query_by': 'title', |
| 65 | + 'sort_by': 'ratings_count:desc' |
| 66 | +})) |
| 67 | + |
| 68 | +# List all aliases |
| 69 | + |
| 70 | +print(client.aliases.retrieve()) |
| 71 | + |
| 72 | +# Retrieve the configuration of a specific alias |
| 73 | + |
| 74 | +print(client.aliases['books'].retrieve()) |
| 75 | + |
| 76 | +# Delete an alias |
| 77 | + |
| 78 | +print(client.aliases['books'].delete()) |
0 commit comments