### Install Typesense Python Client Source: https://github.com/typesense/typesense-python/blob/master/README.md Install the Typesense Python client using pip. Add it to your requirements.txt for project dependency management. ```bash pip install typesense ``` -------------------------------- ### Async API Usage Example Source: https://context7.com/typesense/typesense-python/llms.txt Demonstrates the asynchronous API for creating collections, upserting documents, searching, multi-searching, and performing health checks. Remember to call `await client.api_call.aclose()` when finished. ```python import asyncio import typesense async def main() -> None: client = typesense.AsyncClient({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) try: # Create collection await client.collections.create({ "name": "books", "fields": [ {"name": "title", "type": "string"}, {"name": "ratings_count", "type": "int32"}, {"name": "average_rating","type": "float"}, ], "default_sorting_field": "ratings_count", }) # Create and upsert documents book = {"id": "1", "title": "The Hunger Games", "ratings_count": 4780653, "average_rating": 4.34} await client.collections["books"].documents.create(book) await client.collections["books"].documents.upsert(book) # Search results = await client.collections["books"].documents.search({ "q": "hunger", "query_by": "title", "sort_by": "ratings_count:desc" }) print(results["found"]) # Multi-search multi = await client.multi_search.perform( {"searches": [{"q": "hunger", "query_by": "title"}, {"q": "4.34", "query_by": "average_rating"}]}, {"collection": "books"}, ) for r in multi["results"]: print(r["found"]) # Health check print(await client.operations.is_healthy()) # Cleanup await client.collections["books"].delete() finally: await client.api_call.aclose() asyncio.run(main()) ``` -------------------------------- ### Retrieve and Access Synonym Sets Source: https://context7.com/typesense/typesense-python/llms.txt Use `client.synonym_sets.retrieve()` to get all synonym sets. Access a specific synonym set using dictionary-like syntax, e.g., `client.synonym_sets["en_synonyms"]`. ```python # Retrieve all synonym sets all_synonyms = client.synonym_sets.retrieve() # Access a specific synonym set synonym_set = client.synonym_sets["en_synonyms"] ``` -------------------------------- ### List All Typesense Collections Source: https://context7.com/typesense/typesense-python/llms.txt Retrieve metadata for every collection in the Typesense instance. This is useful for getting an overview of your indexed data. ```python all_collections = client.collections.retrieve() for col in all_collections: print(col["name"], col["num_documents"]) # books 0 ``` -------------------------------- ### Initialize Client with URL String Nodes Source: https://context7.com/typesense/typesense-python/llms.txt Nodes can also be provided as URL strings for client initialization. This offers a more concise way to specify server endpoints. ```python client = typesense.Client({ "api_key": "abcd", "nodes": ["http://localhost:8108"], "nearest_node": "http://node0.example.com:8108", }) ``` -------------------------------- ### Client Initialization Source: https://context7.com/typesense/typesense-python/llms.txt Initialize a synchronous or asynchronous client by providing configuration details for Typesense server nodes and API key. ```APIDOC ## Client Initialization Initialize a synchronous or asynchronous client by passing a `ConfigDict` with the server nodes and API key. ```python import typesense # Synchronous client client = typesense.Client({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, "num_retries": 3, "retry_interval_seconds": 1.0, "healthcheck_interval_seconds": 60, }) # Asynchronous client import asyncio async def main() -> None: async_client = typesense.AsyncClient({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) print(await async_client.collections.retrieve()) await async_client.api_call.aclose() # always close the async client when done asyncio.run(main()) ``` Nodes can also be provided as URL strings: ```python client = typesense.Client({ "api_key": "abcd", "nodes": ["http://localhost:8108"], "nearest_node": "http://node0.example.com:8108", }) ``` ``` -------------------------------- ### Initialize Synchronous and Asynchronous Typesense Clients Source: https://context7.com/typesense/typesense-python/llms.txt Initialize a synchronous or asynchronous client by providing a configuration dictionary with server node details and an API key. The asynchronous client requires explicit closing. ```python import typesense # Synchronous client client = typesense.Client({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, "num_retries": 3, "retry_interval_seconds": 1.0, "healthcheck_interval_seconds": 60, }) ``` ```python import typesense import asyncio async def main() -> None: async_client = typesense.AsyncClient({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) print(await async_client.collections.retrieve()) await async_client.api_call.aclose() # always close the async client when done asyncio.run(main()) ``` -------------------------------- ### Initialize Async Typesense Client Source: https://github.com/typesense/typesense-python/blob/master/README.md Initialize the asynchronous Typesense client for use in async runtimes. Ensure to close the client connection when done. ```python import asyncio import typesense async def main() -> None: client = typesense.AsyncClient({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) print(await client.collections.retrieve()) await client.api_call.aclose() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create an API Key Source: https://context7.com/typesense/typesense-python/llms.txt Use this to create a scoped API key with specific action and collection permissions. The key's ID and value are returned upon creation. ```python key = client.keys.create({ "description": "Search-only key for books", "actions": ["documents:search"], "collections": ["books"], }) print(key["id"]) print(key["value"]) ``` -------------------------------- ### Async Client Operations Source: https://context7.com/typesense/typesense-python/llms.txt Demonstrates asynchronous operations using `AsyncClient`, including collection management, document operations, searching, and health checks. ```APIDOC ## Async API — `AsyncClient` Every method on `Client` has an `await`able equivalent on `AsyncClient`. Always call `await client.api_call.aclose()` when done (or use a `finally` block). ```python import asyncio import typesense async def main() -> None: client = typesense.AsyncClient({ "api_key": "abcd", "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) try: # Create collection await client.collections.create({ "name": "books", "fields": [ {"name": "title", "type": "string"}, {"name": "ratings_count", "type": "int32"}, {"name": "average_rating","type": "float"}, ], "default_sorting_field": "ratings_count", }) # Create and upsert documents book = {"id": "1", "title": "The Hunger Games", "ratings_count": 4780653, "average_rating": 4.34} await client.collections["books"].documents.create(book) await client.collections["books"].documents.upsert(book) # Search results = await client.collections["books"].documents.search({ "q": "hunger", "query_by": "title", "sort_by": "ratings_count:desc" }) print(results["found"]) # Multi-search multi = await client.multi_search.perform( {"searches": [{"q": "hunger", "query_by": "title"}, {"q": "4.34", "query_by": "average_rating"}]}, {"collection": "books"}, ) for r in multi["results"]: print(r["found"]) # Health check print(await client.operations.is_healthy()) # Cleanup await client.collections["books"].delete() finally: await client.api_call.aclose() asyncio.run(main()) ``` ``` -------------------------------- ### client.keys.create Source: https://context7.com/typesense/typesense-python/llms.txt Creates a new scoped API key with specified actions and collection permissions. This key can be used to grant granular access to Typesense resources. ```APIDOC ## `client.keys.create` — Create an API Key Create a scoped API key with specific action and collection permissions. ```python key = client.keys.create({ "description": "Search-only key for books", "actions": ["documents:search"], "collections": ["books"], }) print(key["id"]) print(key["value"]) ``` ``` -------------------------------- ### client.collections[name].documents.import_ Source: https://context7.com/typesense/typesense-python/llms.txt Imports a list of documents. Supports `action` (create, upsert, update), `batch_size`, and optional `return_id`/`return_doc` parameters. ```APIDOC ## `client.collections[name].documents.import_` — Bulk Import Documents Import a list of documents (or raw JSONL bytes/string). Supports `action` (`create`, `upsert`, `update`), `batch_size`, and optional `return_id`/`return_doc` parameters. ```python from typesense.exceptions import TypesenseClientError docs = [ {"id": "1", "title": "The Hunger Games", "authors": ["Suzanne Collins"], "publication_year": 2008, "ratings_count": 4780653, "average_rating": 4.34, "image_url": "https://example.com/1.jpg"}, {"id": "2", "title": "Catching Fire", "authors": ["Suzanne Collins"], "publication_year": 2009, "ratings_count": 2000000, "average_rating": 4.30, "image_url": "https://example.com/2.jpg"}, ] # Basic import results = client.collections["books"].documents.import_(docs) for r in results: print(r) # {'success': True} or {'success': False, 'error': '...', 'document': {...}} # Upsert with return_id results = client.collections["books"].documents.import_( docs, {"action": "upsert", "return_id": True}, ) # Batch import (100 docs per batch) results = client.collections["books"].documents.import_(docs, batch_size=100) # Guard against empty list try: client.collections["books"].documents.import_([], {"action": "upsert"}) except TypesenseClientError as e: print(e) # Cannot import an empty list of documents. ``` ``` -------------------------------- ### Create a Document in Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Index a single document into a collection. The 'id' field is optional; Typesense can auto-generate one if omitted. ```python book = { "id": "1", "title": "The Hunger Games", "authors": ["Suzanne Collins"], "publication_year": 2008, "ratings_count": 4780653, "average_rating": 4.34, "image_url": "https://images.gr-assets.com/books/1447303603m/2767052.jpg", } created_doc = client.collections["books"].documents.create(book) print(created_doc["id"]) ``` -------------------------------- ### client.collections.create Source: https://context7.com/typesense/typesense-python/llms.txt Create a new collection in Typesense by defining its schema, including fields and an optional default sorting field. ```APIDOC ## `client.collections.create` — Create a Collection Define a collection schema with fields and an optional default sorting field. Supports all Typesense field types: `string`, `string[]`, `int32`, `int64`, `float`, `bool`, `geopoint`, and more. ```python schema = { "name": "books", "fields": [ {"name": "title", "type": "string"}, {"name": "authors", "type": "string[]", "facet": True}, {"name": "publication_year", "type": "int32", "facet": True}, {"name": "ratings_count", "type": "int32"}, {"name": "average_rating", "type": "float"}, {"name": "image_url", "type": "string"}, ], "default_sorting_field": "ratings_count", } created = client.collections.create(schema) # {'name': 'books', 'fields': [...], 'num_documents': 0, ...} print(created) ``` ``` -------------------------------- ### Create and Manage Analytics Rules Source: https://context7.com/typesense/typesense-python/llms.txt Create rules to track popular queries and click-through events. Rules can be created, listed, updated (upserted), and deleted. ```python # Create a popular queries rule rule = client.analytics.rules.create({ "name": "top_searches", "type": "popular_queries", "params": { "source": {"collections": ["books"]}, "destination": {"collection": "top_searches"}, "limit": 1000, }, }) print(rule["name"]) # List rules (optionally filter by tag) rules = client.analytics.rules.retrieve() # Upsert (update) a rule client.analytics.rules.upsert("top_searches", { "name": "top_searches", "type": "popular_queries", "params": { "source": {"collections": ["books"]}, "destination": {"collection": "top_searches"}, "limit": 500, }, }) # Delete a rule client.analytics.rules["top_searches"].delete() ``` -------------------------------- ### Generate a Scoped Search Key Client-Side Source: https://context7.com/typesense/typesense-python/llms.txt Generate a signed search key client-side that embeds query parameters like `filter_by`. This requires a base key with the `documents:search` action. The scoped key can then be used in a new client instance to enforce these filters. ```python # Generate a key that restricts results to ratings_count < 100 scoped_key = client.keys.generate_scoped_search_key( key["value"], {"filter_by": "ratings_count:<100"}, ) # Use the scoped key in a new client scoped_client = typesense.Client({ "api_key": scoped_key, "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) results = scoped_client.collections["books"].documents.search({ "q": "hunger", "query_by": "title", }) print(results["found"]) ``` -------------------------------- ### Import Documents to Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Imports a list of documents into a collection. Supports various actions like 'create', 'upsert', and 'update', along with batching and options to return IDs or documents. ```python from typesense.exceptions import TypesenseClientError docs = [ {"id": "1", "title": "The Hunger Games", "authors": ["Suzanne Collins"], "publication_year": 2008, "ratings_count": 4780653, "average_rating": 4.34, "image_url": "https://example.com/1.jpg"}, {"id": "2", "title": "Catching Fire", "authors": ["Suzanne Collins"], "publication_year": 2009, "ratings_count": 2000000, "average_rating": 4.30, "image_url": "https://example.com/2.jpg"}, ] # Basic import results = client.collections["books"].documents.import_(docs) for r in results: print(r) # {'success': True} or {'success': False, 'error': '...', 'document': {...}} # Upsert with return_id results = client.collections["books"].documents.import_( docs, {"action": "upsert", "return_id": True}, ) # Batch import (100 docs per batch) results = client.collections["books"].documents.import_(docs, batch_size=100) # Guard against empty list try: client.collections["books"].documents.import_([], {"action": "upsert"}) except TypesenseClientError as e: print(e) # Cannot import an empty list of documents. ``` -------------------------------- ### Configure Slow Request Logging Source: https://context7.com/typesense/typesense-python/llms.txt Configure the logging of slow requests by setting a time threshold in milliseconds. ```APIDOC ## `client.operations.toggle_slow_request_log` — Configure Slow Request Logging ```python client.operations.toggle_slow_request_log({"log_slow_requests_time_ms": 200}) ``` ``` -------------------------------- ### client.collections[name].documents.create Source: https://context7.com/typesense/typesense-python/llms.txt Create and index a single document within a specified collection. The document ID is optional, as Typesense can auto-generate it. ```APIDOC ## `client.collections[name].documents.create` — Create a Document Index a single document. The `id` field is optional; Typesense auto-generates one if omitted. ```python book = { "id": "1", "title": "The Hunger Games", "authors": ["Suzanne Collins"], "publication_year": 2008, "ratings_count": 4780653, "average_rating": 4.34, "image_url": "https://images.gr-assets.com/books/1447303603m/2767052.jpg", } created_doc = client.collections["books"].documents.create(book) print(created_doc["id"]) ``` ``` -------------------------------- ### Perform Server Operations Source: https://context7.com/typesense/typesense-python/llms.txt Execute server-level operations like creating snapshots, compacting the database, clearing the cache, or triggering leader election votes using `client.operations.perform()`. ```python # Create a snapshot client.operations.perform("snapshot", {"snapshot_path": "/tmp/typesense-data-snapshot"}) # Compact the database client.operations.perform("db/compact") # Clear the cache client.operations.perform("cache/clear") # Vote in a cluster leader election client.operations.perform("vote") # Retrieve pending schema changes changes = client.operations.perform("schema_changes") print(changes) ``` -------------------------------- ### Create a Typesense Collection Source: https://context7.com/typesense/typesense-python/llms.txt Define a collection schema with fields and an optional default sorting field. Supports various Typesense field types. ```python schema = { "name": "books", "fields": [ {"name": "title", "type": "string"}, {"name": "authors", "type": "string[]", "facet": True}, {"name": "publication_year", "type": "int32", "facet": True}, {"name": "ratings_count", "type": "int32"}, {"name": "average_rating", "type": "float"}, {"name": "image_url", "type": "string"}, ], "default_sorting_field": "ratings_count", } created = client.collections.create(schema) # {'name': 'books', 'fields': [...], 'num_documents': 0, ...} print(created) ``` -------------------------------- ### Manage Stemming Dictionaries Source: https://context7.com/typesense/typesense-python/llms.txt Provide custom word-root mappings to control how words are stemmed. Dictionaries can be upserted from a list of pairs or raw JSONL bytes, and they can be listed. ```python # Upsert a stemming dictionary from a list of word-root pairs result = client.stemming.dictionaries.upsert( "english_custom", [ {"word": "running", "root": "run"}, {"word": "cries", "root": "cry"}, {"word": "leaves", "root": "leaf"}, ], ) print(result) # Or supply raw JSONL bytes raw_jsonl = b'{"word":"running","root":"run"}\n{"word":"cries","root":"cry"}' client.stemming.dictionaries.upsert("english_custom", raw_jsonl) # List all dictionaries print(client.stemming.dictionaries.retrieve()) ``` -------------------------------- ### Toggle Slow Request Logging Source: https://context7.com/typesense/typesense-python/llms.txt Configure the logging of slow requests by calling `client.operations.toggle_slow_request_log()` with the desired time threshold in milliseconds. ```python client.operations.toggle_slow_request_log({"log_slow_requests_time_ms": 200}) ``` -------------------------------- ### client.multi_search.perform Source: https://context7.com/typesense/typesense-python/llms.txt Executes multiple independent search queries in a single API round-trip. Common parameters can be shared via `common_params`. ```APIDOC ## `client.multi_search.perform` — Multi-Search Execute multiple independent search queries in a single API round-trip. Common parameters can be shared via `common_params`. ```python response = client.multi_search.perform( { "searches": [ {"q": "hunger", "query_by": "title"}, {"q": "suzanne", "query_by": "authors"}, ] }, {"collection": "books", "sort_by": "ratings_count:desc"}, ) for i, result in enumerate(response["results"]): print(f"Query {i}: {result['found']} hit(s)") ``` ``` -------------------------------- ### Manage Collection Aliases Source: https://context7.com/typesense/typesense-python/llms.txt Use aliases to point a virtual name to a physical collection, enabling zero-downtime re-indexing. You can upsert (create or update), retrieve, and delete aliases. ```python # Point alias "books" to collection "books_january" client.aliases.upsert("books", {"collection_name": "books_january"}) # Search through the alias results = client.collections["books"].documents.search({ "q": "hunger", "query_by": "title" }) # Swap to a new collection atomically client.aliases.upsert("books", {"collection_name": "books_february"}) # List all aliases print(client.aliases.retrieve()) # Retrieve a specific alias print(client.aliases["books"].retrieve()) # Delete an alias client.aliases["books"].delete() ``` -------------------------------- ### client.stemming.dictionaries.upsert Source: https://context7.com/typesense/typesense-python/llms.txt Manages custom stemming dictionaries, allowing you to define word-root mappings. This provides fine-grained control over how words are stemmed during indexing and search, improving query accuracy. ```APIDOC ## `client.stemming.dictionaries.upsert` — Stemming Dictionaries Provide custom word-root mappings to control how words are stemmed during indexing and search. ```python # Upsert a stemming dictionary from a list of word-root pairs result = client.stemming.dictionaries.upsert( "english_custom", [ {"word": "running", "root": "run"}, {"word": "cries", "root": "cry"}, {"word": "leaves", "root": "leaf"}, ], ) print(result) # Or supply raw JSONL bytes raw_jsonl = b'{"word":"running","root":"run"}\n{"word":"cries","root":"cry"}' client.stemming.dictionaries.upsert("english_custom", raw_jsonl) # List all dictionaries print(client.stemming.dictionaries.retrieve()) ``` ``` -------------------------------- ### Synonym Sets Management Source: https://context7.com/typesense/typesense-python/llms.txt Manage synonym sets at the server level. This replaces the deprecated `collection.synonyms` functionality. ```APIDOC ## `client.synonym_sets` — Synonym Sets (v30+) Manage synonym sets at the server level (replaces the deprecated `collection.synonyms`). ```python # Retrieve all synonym sets all_synonyms = client.synonym_sets.retrieve() # Access a specific synonym set synonym_set = client.synonym_sets["en_synonyms"] ``` ``` -------------------------------- ### client.collections.retrieve Source: https://context7.com/typesense/typesense-python/llms.txt Retrieve metadata for all collections currently present in the Typesense instance. ```APIDOC ## `client.collections.retrieve` — List All Collections Retrieve metadata for every collection currently in the Typesense instance. ```python all_collections = client.collections.retrieve() for col in all_collections: print(col["name"], col["num_documents"]) # books 0 ``` ``` -------------------------------- ### Retrieve and Delete an API Key Source: https://context7.com/typesense/typesense-python/llms.txt Manage individual API keys by retrieving their data (value is masked) or deleting them. You can also list all existing keys. ```python # Retrieve a key (value is masked) key_data = client.keys[key["id"]].retrieve() print(key_data["description"]) # List all keys all_keys = client.keys.retrieve() for k in all_keys["keys"]: print(k["id"], k["description"]) # Delete a key deleted = client.keys[key["id"]].delete() print(deleted["id"]) ``` -------------------------------- ### client.collections[name].retrieve Source: https://context7.com/typesense/typesense-python/llms.txt Retrieve the schema and metadata for a specific collection by its name. ```APIDOC ## `client.collections[name].retrieve` — Retrieve a Single Collection ```python books_schema = client.collections["books"].retrieve() print(books_schema["name"]) print(books_schema["num_documents"]) ``` ``` -------------------------------- ### Export Documents from Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Exports all documents from a collection in JSONL format. This is useful for backups or migrating data. ```python jsonl_str = client.collections["books"].documents.export() for line in jsonl_str.split("\n"): import json doc = json.loads(line) print(doc["title"]) # The Hunger Games ``` -------------------------------- ### Server Operations Source: https://context7.com/typesense/typesense-python/llms.txt Trigger built-in Typesense server operations such as snapshot creation, database compaction, cache clearing, and more. ```APIDOC ## `client.operations.perform` — Server Operations Trigger built-in Typesense server operations: `snapshot`, `vote`, `db/compact`, `cache/clear`, `schema_changes`. ```python # Create a snapshot client.operations.perform("snapshot", {"snapshot_path": "/tmp/typesense-data-snapshot"}) # Compact the database client.operations.perform("db/compact") # Clear the cache client.operations.perform("cache/clear") # Vote in a cluster leader election client.operations.perform("vote") # Retrieve pending schema changes changes = client.operations.perform("schema_changes") print(changes) ``` ``` -------------------------------- ### client.aliases.upsert / client.aliases.retrieve Source: https://context7.com/typesense/typesense-python/llms.txt Manages collection aliases, which provide a virtual name for a physical collection. This enables zero-downtime re-indexing by allowing atomic swaps between collections. ```APIDOC ## `client.aliases.upsert` / `client.aliases.retrieve` — Collection Aliases Aliases allow pointing a virtual name to a physical collection, enabling zero-downtime re-indexing. ```python # Point alias "books" to collection "books_january" client.aliases.upsert("books", {"collection_name": "books_january"}) # Search through the alias results = client.collections["books"].documents.search({ "q": "hunger", "query_by": "title" }) # Swap to a new collection atomically client.aliases.upsert("books", {"collection_name": "books_february"}) # List all aliases print(client.aliases.retrieve()) # Retrieve a specific alias print(client.aliases["books"].retrieve()) # Delete an alias client.aliases["books"].delete() ``` ``` -------------------------------- ### client.keys[id].retrieve / client.keys[id].delete Source: https://context7.com/typesense/typesense-python/llms.txt Manages individual API keys by allowing retrieval of key details (with masked value) and deletion of specific keys using their ID. ```APIDOC ## `client.keys[id].retrieve` / `client.keys[id].delete` — Manage Individual Keys ```python # Retrieve a key (value is masked) key_data = client.keys[key["id"]].retrieve() print(key_data["description"]) # List all keys all_keys = client.keys.retrieve() for k in all_keys["keys"]: print(k["id"], k["description"]) # Delete a key deleted = client.keys[key["id"]].delete() print(deleted["id"]) ``` ``` -------------------------------- ### client.keys.generate_scoped_search_key Source: https://context7.com/typesense/typesense-python/llms.txt Generates a client-side signed search key that embeds query parameters, such as a mandatory `filter_by`. This is useful for creating temporary, restricted search access. ```APIDOC ## `client.keys.generate_scoped_search_key` — Generate a Scoped Search Key Create a signed search key client-side that embeds query parameters (e.g., a mandatory `filter_by`). Only keys with the `documents:search` action can be used as the base. ```python # Generate a key that restricts results to ratings_count < 100 scoped_key = client.keys.generate_scoped_search_key( key["value"], {"filter_by": "ratings_count:<100"}, ) # Use the scoped key in a new client scoped_client = typesense.Client({ "api_key": scoped_key, "nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}], "connection_timeout_seconds": 2, }) results = scoped_client.collections["books"].documents.search({ "q": "hunger", "query_by": "title", }) print(results["found"]) ``` ``` -------------------------------- ### Perform Multi-Search in Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Executes multiple independent search queries in a single API request. This is efficient for performing several searches simultaneously and can share common parameters. ```python response = client.multi_search.perform( { "searches": [ {"q": "hunger", "query_by": "title"}, {"q": "suzanne", "query_by": "authors"}, ] }, {"collection": "books", "sort_by": "ratings_count:desc"}, ) for i, result in enumerate(response["results"]): print(f"Query {i}: {result['found']} hit(s)") ``` -------------------------------- ### Access Curation Sets Source: https://context7.com/typesense/typesense-python/llms.txt Manage curated search result overrides at the server level. You can retrieve all curation sets and access individual sets by name. ```python # Retrieve all curation sets sets = client.curation_sets.retrieve() for s in sets: print(s["name"]) # Access a specific curation set curation_set = client.curation_sets["featured_books"] ``` -------------------------------- ### client.collections[name].documents.export Source: https://context7.com/typesense/typesense-python/llms.txt Exports all documents from a collection in JSONL format. ```APIDOC ## `client.collections[name].documents.export` — Export Documents as JSONL ```python jsonl_str = client.collections["books"].documents.export() for line in jsonl_str.split("\n"): import json doc = json.loads(line) print(doc["title"]) # The Hunger Games ``` ``` -------------------------------- ### Health Check Source: https://context7.com/typesense/typesense-python/llms.txt Check the health status of the Typesense server. ```APIDOC ## `client.operations.is_healthy` — Health Check ```python is_ok = client.operations.is_healthy() print(is_ok) # True ``` ``` -------------------------------- ### Typed Collection Access and Document Retrieval Source: https://context7.com/typesense/typesense-python/llms.txt Use `client.typed_collection()` with a `DocumentSchema` subclass for static type checking. Access documents using `collection.documents["id"].retrieve()`. ```python from typesense.types.document import DocumentSchema class Book(DocumentSchema): id: str title: str authors: list[str] publication_year: int ratings_count: int average_rating: float image_url: str # Infers collection name "book" from class name books_col = client.typed_collection(model=Book) # Or specify an explicit name books_col = client.typed_collection(model=Book, name="books") book: Book = books_col.documents["1"].retrieve() print(book["title"]) # The Hunger Games ``` -------------------------------- ### client.collections[name].documents.search Source: https://context7.com/typesense/typesense-python/llms.txt Performs full-text and faceted search with filtering, sorting, highlighting, and pagination. ```APIDOC ## `client.collections[name].documents.search` — Search Documents Full-text and faceted search with filtering, sorting, highlighting, and pagination. ```python results = client.collections["books"].documents.search({ "q": "hunger", "query_by": "title", "filter_by": "publication_year:>2000", "sort_by": "ratings_count:desc", "facet_by": "authors", "per_page": 10, "page": 1, }) print(results["found"]) # total matches for hit in results["hits"]: print(hit["document"]["title"]) # The Hunger Games print(hit["highlights"][0]["snippet"]) # Hunger Games ``` ``` -------------------------------- ### Bulk Update Documents by Filter Source: https://context7.com/typesense/typesense-python/llms.txt Updates all documents within a collection that match a specified filter expression. This is efficient for modifying multiple documents based on criteria. ```python result = client.collections["books"].documents.update( {"publication_year": 2009}, {"filter_by": "publication_year: 2008"}, ) print(result) # {'num_updated': 1} ``` -------------------------------- ### client.collections[name].documents.upsert Source: https://context7.com/typesense/typesense-python/llms.txt Inserts a document if it does not exist; replaces it entirely if it does. ```APIDOC ## `client.collections[name].documents.upsert` — Create or Update a Document Insert a document if it does not exist; replace it entirely if it does. ```python upserted = client.collections["books"].documents.upsert({ "id": "1", "title": "The Hunger Games", "authors": ["Suzanne Collins"], "publication_year": 2008, "ratings_count": 4780653, "average_rating": 4.34, "image_url": "https://example.com/img.jpg", }) print(upserted["id"]) # 1 ``` ``` -------------------------------- ### client.stopwords.upsert / client.stopwords.retrieve Source: https://context7.com/typesense/typesense-python/llms.txt Manages stopwords sets, which are collections of words to be excluded from search queries. This helps in refining search relevance by ignoring common, non-informative words. ```APIDOC ## `client.stopwords.upsert` / `client.stopwords.retrieve` — Stopwords Sets Define sets of words to exclude from search queries. ```python # Create a stopwords set client.stopwords.upsert("common_words", { "stopwords": ["the", "a", "an", "is"], "locale": "en", }) # Retrieve all stopword sets sets = client.stopwords.retrieve() print(sets) # Retrieve a specific set print(client.stopwords["common_words"].retrieve()) # Delete a stopwords set client.stopwords["common_words"].delete() ``` ``` -------------------------------- ### Search Documents in Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Performs full-text and faceted search on documents within a collection. Supports filtering, sorting, highlighting, and pagination for precise results. ```python results = client.collections["books"].documents.search({ "q": "hunger", "query_by": "title", "filter_by": "publication_year:>2000", "sort_by": "ratings_count:desc", "facet_by": "authors", "per_page": 10, "page": 1, }) print(results["found"]) # total matches for hit in results["hits"]: print(hit["document"]["title"]) # The Hunger Games print(hit["highlights"][0]["snippet"]) # Hunger Games ``` -------------------------------- ### Retrieve a Single Typesense Collection Source: https://context7.com/typesense/typesense-python/llms.txt Retrieve the schema and metadata for a specific collection by its name. Useful for inspecting individual collection configurations. ```python books_schema = client.collections["books"].retrieve() print(books_schema["name"]) print(books_schema["num_documents"]) ``` -------------------------------- ### Retrieve Document from Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Fetches a single document by its ID from a collection. Use this when you need to access the complete data of a specific document. ```python doc = client.collections["books"].documents["1"].retrieve() print(doc["title"]) # The Hunger Games ``` -------------------------------- ### Manage Stopwords Sets Source: https://context7.com/typesense/typesense-python/llms.txt Define sets of words to exclude from search queries. You can create (upsert), retrieve all sets, retrieve a specific set, and delete sets. ```python # Create a stopwords set client.stopwords.upsert("common_words", { "stopwords": ["the", "a", "an", "is"], "locale": "en", }) # Retrieve all stopword sets sets = client.stopwords.retrieve() print(sets) # Retrieve a specific set print(client.stopwords["common_words"].retrieve()) # Delete a stopwords set client.stopwords["common_words"].delete() ``` -------------------------------- ### Perform Health Check Source: https://context7.com/typesense/typesense-python/llms.txt Call `client.operations.is_healthy()` to check if the Typesense server is operational. It returns `True` if the server is healthy. ```python is_ok = client.operations.is_healthy() print(is_ok) # True ``` -------------------------------- ### client.collections[name].documents[id].retrieve Source: https://context7.com/typesense/typesense-python/llms.txt Retrieves a single document by its ID. ```APIDOC ## `client.collections[name].documents[id].retrieve` — Retrieve a Document ```python doc = client.collections["books"].documents["1"].retrieve() print(doc["title"]) # The Hunger Games ``` ``` -------------------------------- ### client.analytics.rules Source: https://context7.com/typesense/typesense-python/llms.txt Manages analytics rules for tracking popular queries and click-through events. These rules help in understanding user search behavior and optimizing search results. ```APIDOC ## `client.analytics.rules` — Analytics Rules (v30+) Create rules to track popular queries and click-through events. ```python # Create a popular queries rule rule = client.analytics.rules.create({ "name": "top_searches", "type": "popular_queries", "params": { "source": {"collections": ["books"]}, "destination": {"collection": "top_searches"}, "limit": 1000, }, }) print(rule["name"]) # List rules (optionally filter by tag) rules = client.analytics.rules.retrieve() # Upsert (update) a rule client.analytics.rules.upsert("top_searches", { "name": "top_searches", "type": "popular_queries", "params": { "source": {"collections": ["books"]}, "destination": {"collection": "top_searches"}, "limit": 500, }, }) # Delete a rule client.analytics.rules["top_searches"].delete() ``` ``` -------------------------------- ### Upsert Document in Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Inserts a document if it doesn't exist or replaces it entirely if it does. This is useful for creating or updating individual documents. ```python upserted = client.collections["books"].documents.upsert({ "id": "1", "title": "The Hunger Games", "authors": ["Suzanne Collins"], "publication_year": 2008, "ratings_count": 4780653, "average_rating": 4.34, "image_url": "https://example.com/img.jpg", }) print(upserted["id"]) # 1 ``` -------------------------------- ### client.curation_sets Source: https://context7.com/typesense/typesense-python/llms.txt Manages curation sets, which allow for server-level overrides of search results. This feature replaces deprecated collection override functionality and is useful for promoting specific documents. ```APIDOC ## `client.curation_sets` — Curation Sets (v30+) Manage curated search result overrides at the server level (replaces the deprecated `collection.overrides`). ```python # Retrieve all curation sets sets = client.curation_sets.retrieve() for s in sets: print(s["name"]) # Access a specific curation set curation_set = client.curation_sets["featured_books"] ``` ``` -------------------------------- ### Typed Collection Access Source: https://context7.com/typesense/typesense-python/llms.txt Access a `Collection` instance bound to a specific `DocumentSchema` subclass for full static type checking. ```APIDOC ## `client.typed_collection` — Typed Collection Access Get a `Collection` instance bound to a specific `DocumentSchema` subclass for full static type checking. ```python from typesense.types.document import DocumentSchema class Book(DocumentSchema): id: str title: str authors: list[str] publication_year: int ratings_count: int average_rating: float image_url: str # Infers collection name "book" from class name books_col = client.typed_collection(model=Book) # Or specify an explicit name books_col = client.typed_collection(model=Book, name="books") book: Book = books_col.documents["1"].retrieve() print(book["title"]) # The Hunger Games ``` ``` -------------------------------- ### Delete a Typesense Collection Source: https://context7.com/typesense/typesense-python/llms.txt Delete a collection and all its associated documents from the Typesense instance. Use with caution as this action is irreversible. ```python dropped = client.collections["books"].delete() print(dropped["name"]) ``` -------------------------------- ### client.collections[name].update Source: https://context7.com/typesense/typesense-python/llms.txt Update the schema of an existing collection, allowing for the addition, modification, or dropping of fields without re-indexing. ```APIDOC ## `client.collections[name].update` — Update a Collection Schema Add, modify, or drop fields from an existing collection without re-indexing. ```python # Add an optional boolean field client.collections["books"].update({ "fields": [{"name": "in_stock", "type": "bool", "optional": True}] }) # Drop the field client.collections["books"].update({ "fields": [{"name": "in_stock", "drop": True}] }) ``` ``` -------------------------------- ### Update a Typesense Collection Schema Source: https://context7.com/typesense/typesense-python/llms.txt Add, modify, or drop fields from an existing collection schema without re-indexing. This allows for dynamic schema evolution. ```python # Add an optional boolean field client.collections["books"].update({ "fields": [{"name": "in_stock", "type": "bool", "optional": True}] }) # Drop the field client.collections["books"].update({ "fields": [{"name": "in_stock", "drop": True}] }) ``` -------------------------------- ### client.collections[name].documents[id].update Source: https://context7.com/typesense/typesense-python/llms.txt Performs a partial update on a document, changing only the provided fields. Supports `dirty_values` parameter for type coercion. ```APIDOC ## `client.collections[name].documents[id].update` — Update a Document Partial update: only the provided fields are changed. Supports `dirty_values` parameter for type coercion. ```python # Normal partial update updated = client.collections["books"].documents["1"].update({"average_rating": 4.45}) print(updated["average_rating"]) # 4.45 # Update with coercion (string → float) updated = client.collections["books"].documents["1"].update( {"average_rating": "4.55"}, {"dirty_values": "coerce_or_reject"}, ) print(updated["average_rating"]) # 4.55 ``` ``` -------------------------------- ### client.collections[name].delete Source: https://context7.com/typesense/typesense-python/llms.txt Delete a specific collection from the Typesense instance. ```APIDOC ## `client.collections[name].delete` — Delete a Collection ```python dropped = client.collections["books"].delete() print(dropped["name"]) ``` ``` -------------------------------- ### client.collections[name].documents.update Source: https://context7.com/typesense/typesense-python/llms.txt Updates all documents matching a specified filter expression. ```APIDOC ## `client.collections[name].documents.update` — Bulk Update by Filter Update all documents matching a filter expression. ```python result = client.collections["books"].documents.update( {"publication_year": 2009}, {"filter_by": "publication_year: 2008"}, ) print(result) # {'num_updated': 1} ``` ``` -------------------------------- ### client.collections[name].documents[id].delete Source: https://context7.com/typesense/typesense-python/llms.txt Deletes a single document by its ID. ```APIDOC ## `client.collections[name].documents[id].delete` — Delete a Single Document ```python deleted = client.collections["books"].documents["1"].delete() print(deleted["id"]) # 1 ``` ``` -------------------------------- ### Update Document in Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Partially updates a document by changing only the provided fields. Supports `dirty_values` parameter for type coercion, allowing for flexible data updates. ```python # Normal partial update updated = client.collections["books"].documents["1"].update({"average_rating": 4.45}) print(updated["average_rating"]) # 4.45 # Update with coercion (string → float) updated = client.collections["books"].documents["1"].update( {"average_rating": "4.55"}, {"dirty_values": "coerce_or_reject"}, ) print(updated["average_rating"]) # 4.55 ``` -------------------------------- ### Bulk Delete Documents by Filter Source: https://context7.com/typesense/typesense-python/llms.txt Deletes all documents within a collection that match a given filter expression. This is useful for removing multiple records based on specific criteria. ```python result = client.collections["books"].documents.delete( {"filter_by": "ratings_count: 4780653"} ) print(result) # {'num_deleted': 1} ``` -------------------------------- ### client.collections[name].documents.delete Source: https://context7.com/typesense/typesense-python/llms.txt Deletes all documents matching a specified filter expression. ```APIDOC ## `client.collections[name].documents.delete` — Bulk Delete by Filter ```python result = client.collections["books"].documents.delete( {"filter_by": "ratings_count: 4780653"} ) print(result) # {'num_deleted': 1} ``` ``` -------------------------------- ### Delete Document from Typesense Source: https://context7.com/typesense/typesense-python/llms.txt Removes a single document from a collection using its ID. Use this for deleting specific records. ```python deleted = client.collections["books"].documents["1"].delete() print(deleted["id"]) # 1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.