Typesense Python Client

repository·master·Indexed 42 days ago

https://github.com/typesense/typesense-python

Python client for Typesense, an open source and typo tolerant search engine. It provides a programmatic interface to interact with the Typesense search engine API, supporting both synchronous and asynchronous workflows via the Client and AsyncClient classes. Features include management of collections, aliases, API keys, analytics (v30+), curation sets, and natural language search models.

Tokens
10.2K
Snippets
32
Records
40
Agent score
54%

What's inside Typesense

  1. Understand the SearchResponse structure

    master

    A successful search returns a SearchResponse containing:

    • found: Total number of documents matching the query.
    • hits: A list of Hit objects containing the document, highlights, and text_match_info.
    • facet_counts: A list of SearchResponseFacetCountSchema providing counts and statistics for faceted fields.
    • grouped_hits: If group_by was used, this contains GroupedHit objects.
    • search_time_ms: Time taken for the search.
    • page: The current page number.
    • out_of: Total documents available in the dataset.
    • parsed_nl_query: (Optional) Details if natural language processing was used.
  2. Access specialized sub-clients via AsyncClient

    master

    The AsyncClient provides access to various specialized components for managing different aspects of Typesense. Key attributes include:

    • collections: Manage collections and documents.
    • multi_search: Perform multi-search operations.
    • keys: Manage API keys.
    • aliases: Manage collection aliases.
    • analytics: Perform analytics operations (v30+).
    • stemming: Manage stemming dictionary operations.
    • stopwords: Manage stopwords.
    • synonym_sets: Manage synonym sets.
    • metrics: Retrieve system and Typesense metrics.
    • curation_sets: Manage Curation Sets (v30+).
    • conversations_models: Manage conversation models.
    • nl_search_models: Manage natural language search models.
    • operations: Perform various Typesense operations.
    • debug: Access debug operations.
  3. Define Curation Rule conditions

    master

    A curation rule defines the criteria used to trigger a curation item. A rule must be exactly one of the following three types:

    1. Tags-based rule: Uses a list of tags.
      • Key: tags (List of strings)
    2. Query-based rule: Uses a search query and a match mode.
      • Keys: query (string) and match (literal 'exact' or 'contains')
    3. Filter-based rule: Uses a filter_by expression.
      • Key: filter_by (string)

    In the Python client, these are represented by the CurationRuleSchema union type.

    # Example of different rule types
    tags_rule = {"tags": ["premium", "featured"]}
    query_rule = {"query": "iphone", "match": "contains"}
    filter_rule = {"filter_by": "category:=[electronics]"}
  4. Use AsyncClient for asynchronous runtimes

    master

    When working in an asynchronous Python environment (e.g., using asyncio), use the typesense.AsyncClient instead of the standard synchronous client. The AsyncClient requires a configuration dictionary containing the api_key, nodes (a list of host/port/protocol dictionaries), and optional settings like connection_timeout_seconds.

    Always ensure you close the client connection using await client.api_call.aclose() to clean up resources.

    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())
  5. Configure document write actions and dirty value handling

    master

    When writing documents to Typesense, you can specify the action to perform and how to handle dirty_values (data that doesn't match the inferred schema).

    Actions:

    • create: Creates a new document. Fails if the ID already exists.
    • upsert: Creates a new document or updates an existing one. Requires the full document.
    • update: Updates an existing document. Fails if the ID does not exist. Supports partial updates.
    • emplace: Creates a new document or updates an existing one. Supports both full and partial updates.

    Dirty Value Handling (dirty_values):

    • coerce_or_reject: Attempt to coerce the value to the inferred type; if it fails, reject the write.
    • coerce_or_drop: Attempt to coerce the value; if it fails, drop that specific field and index the rest.
    • drop: Drop the field and index the rest.
    • reject: Reject the entire write operation.
    # Example usage of DocumentWriteParameters
    params = {
        "action": "upsert",
        "dirty_values": "coerce_or_drop"
    }
  6. Configure document import options

    master

    When importing documents, you can control whether the response includes the document content or the document ID by using return_doc and return_id flags.

    Import Parameters:

    • return_id: Set to True to receive the ID of the imported document.
    • return_doc: Set to True to receive the imported document content.
    • action: Use create, upsert, update, or emplace (see Document Write Actions).
    # Example usage of DocumentImportParameters
    import_params = {
        "action": "create",
        "return_doc": True,
        "return_id": True
    }
  7. Check Typesense Server and Client compatibility

    master

    Ensure your typesense-python version is compatible with your running Typesense Server version.

    Typesense Servertypesense-python
    >= v30.0>= v2.0.0
    >= v28.0>= v1.0.0
    >= v26.0>= v0.20.0
    >= v0.25.0>= v0.16.0
    >= v0.23.0>= v0.14.0
    >= v0.21.0>= v0.13.0
    >= v0.20.0>= v0.11.0
    >= v0.19.0>= v0.10.0
    >= v0.17.0>= v0.9.0
    >= v0.16.0>= v0.8.0
    >= v0.15.0>= v0.7.0
  8. Get a typed Collection instance with typed_collection()

    master

    The typed_collection method returns a Collection instance that is typed to a specific DocumentSchema model. This provides better type safety when interacting with documents in that collection.

    If the name argument is not provided, the method defaults to using the lowercase name of the model class as the collection name.

    class Company(DocumentSchema):
        name: str
        num_employees: int
    
    client = Client(config)
    # Returns a Collection[Company] instance
    companies_collection = client.typed_collection(model=Company)
  9. Manage curation sets with the CurationSet class

    master

    The CurationSet class provides an interface for performing asynchronous operations on a specific curation set in Typesense. You can use it to retrieve, create/update (upsert), or delete an entire curation set by its name.

    Methods:

    • retrieve(): Returns the CurationSetSchema for the set.
    • upsert(payload: CurationSetUpsertSchema): Creates or updates the curation set using the provided payload.
    • delete(): Deletes the curation set and returns a CurationSetDeleteSchema.
    from typesense.sync.curation_set import CurationSet
    
    # Assuming api_call is an initialized ApiCall instance
    curation_set = CurationSet(api_call, "my_curation_set")
    
    # Retrieve the set
    set_details = await curation_set.retrieve()
    
    # Upsert the set
    await curation_set.upsert(payload=my_upsert_payload)
    
    # Delete the set
    await curation_set.delete()
  10. Manage aliases asynchronously with the Aliases class

    master

    The Aliases class provides an asynchronous interface for managing Typesense aliases. You can use it to create or update aliases via upsert, retrieve a list of all existing aliases via retrieve, or access specific alias operations using dictionary-like syntax.

    Key Methods

    • upsert(name: str, mapping: AliasCreateSchema) -> AliasSchema: Creates a new alias or updates an existing one. The mapping should follow the AliasCreateSchema (e.g., {"collection_name": "your_collection_name"}).
    • retrieve() -> AliasesResponseSchema: Fetches all aliases currently configured in Typesense.
    • __getitem__(name: str) -> Alias: Allows you to access an Alias instance for a specific name using aliases["name"]. If the instance doesn't exist locally, it is created automatically.
    # Upsert an alias
    alias = await aliases.upsert(
        "company_alias", {"collection_name": "companies"}
    )
    
    # Retrieve all aliases
    all_aliases = await aliases.retrieve()
    for alias in all_aliases["aliases"]:
        print(alias["name"])
    
    # Access a specific alias instance via dictionary syntax
    company_alias = aliases["company_alias"]
  11. Manage NL search models asynchronously with AsyncNLSearchModel

    master

    The AsyncNLSearchModel class allows you to perform asynchronous operations on a specific Natural Language (NL) search model in Typesense. You can use it to retrieve, update, or delete a model by its model_id.

    Methods:

    • retrieve(): Fetches the details of the specific NL search model. Returns an NLSearchModelSchema object.
    • update(model: NLSearchModelUpdateSchema): Updates the existing NL search model with the provided schema. Returns the updated NLSearchModelSchema.
    • delete(): Deletes the specific NL search model. Returns an NLSearchModelDeleteSchema object.
    from typesense.async_ import AsyncNLSearchModel
    
    # Assuming api_call is an initialized AsyncApiCall instance
    model = AsyncNLSearchModel(api_call, 'your_model_id')
    
    # Retrieve a model
    model_details = await model.retrieve()
    
    # Update a model
    await model.update(new_model_schema)
    
    # Delete a model
    await model.delete()