Algolia Python API Client

4.38.0 · active · verified Fri Apr 10

The `algoliasearch` library is a fully-featured and blazing-fast Python API client designed to interact with the Algolia Search API. It provides a Pythonic interface to index data, configure search settings, perform queries, and access advanced features like analytics and recommendations. The library is actively maintained with frequent minor releases, currently at version 4.38.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Algolia client, initialize an index, add a new object, search for objects, and update an object. Remember to replace placeholder API keys and application IDs with your actual credentials, ideally fetched from environment variables. For indexing operations, always use your Admin API Key.

import os
from algoliasearch.search.client import SearchClient

# Initialize the client with your Application ID and API Key
# Ensure you use your Admin API Key for indexing operations, and Search-Only API Key for search.
APP_ID = os.environ.get('ALGOLIA_APP_ID', 'YOUR_ALGOLIA_APP_ID')
API_KEY = os.environ.get('ALGOLIA_API_KEY', 'YOUR_ALGOLIA_ADMIN_API_KEY') # Use Admin API Key for writes
INDEX_NAME = os.environ.get('ALGOLIA_INDEX_NAME', 'your_index_name')

if not APP_ID or not API_KEY:
    print("Please set ALGOLIA_APP_ID and ALGOLIA_API_KEY environment variables or replace placeholders.")
else:
    try:
        client = SearchClient.create(APP_ID, API_KEY)
        index = client.init_index(INDEX_NAME)

        # Add a new record
        record = {"objectID": "1", "name": "Algolia Search", "category": "Search Engines"}
        save_response = index.save_object(record).wait()
        print(f"Object saved: {save_response.object_ids[0]}")

        # Search for records
        search_results = index.search('Algolia', {
            'attributesToRetrieve': ['name', 'category'],
            'hitsPerPage': 1
        })
        
        print("\nSearch Results:")
        for hit in search_results['hits']:
            print(f"- Name: {hit['name']}, Category: {hit['category']}")

        # Update an existing record
        index.partial_update_object({"objectID": "1", "description": "Fast and relevant search."}).wait()
        print("\nObject updated.")

        # Delete a record (optional, uncomment to run)
        # index.delete_object("1").wait()
        # print("\nObject deleted.")

    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →