PySolr

3.11.0 · active · verified Wed Apr 15

PySolr is a lightweight Python client for Apache Solr, providing an interface for querying, indexing, and managing data in Solr. It is actively maintained with version 3.11.0 being the latest stable release, and typically sees 1-3 major releases per year, though the cadence can be irregular.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Solr instance, index documents, perform a search, and delete documents. It uses `os.environ.get` for the Solr URL to support flexible deployment, defaulting to a local Solr instance. Note the use of `always_commit=True` due to a significant change in default behavior in recent versions.

import os
import pysolr

solr_url = os.environ.get('SOLR_URL', 'http://localhost:8983/solr/')

try:
    # Connect to Solr with explicit commit behavior
    solr = pysolr.Solr(solr_url, always_commit=True, timeout=10)

    # Do a health check
    solr.ping()
    print(f"Successfully connected to Solr at {solr_url}")

    # Index some data
    docs_to_add = [
        {"id": "doc_1", "title": "The Quick Brown Fox"},
        {"id": "doc_2", "title": "Jumps Over The Lazy Dog"},
    ]
    solr.add(docs_to_add)
    print("Added documents.")

    # Search for data
    results = solr.search('fox')

    print(f"Found {len(results)} result(s) for 'fox':")
    for result in results:
        print(f"  - ID: {result['id']}, Title: {result['title']}")

    # Delete a document
    solr.delete(id='doc_1')
    print("Deleted doc_1.")

    # Search again to confirm deletion
    results_after_delete = solr.search('fox')
    print(f"Found {len(results_after_delete)} result(s) for 'fox' after deletion.")

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

view raw JSON →