Lunr.py

0.8.0 · active · verified Thu Apr 16

Lunr.py is a Python implementation of Lunr.js, a lightweight full-text search library designed for client-side search. It enables developers to create search indexes from Python data structures, often for serialization and consumption by a JavaScript frontend. The library is actively maintained, with its current version being 0.8.0, and targets close compatibility with the original Lunr.js implementation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a Lunr index from a list of dictionaries. It defines a unique reference field (`id`), fields to be searched (`title`, `body`), and the documents themselves. It then performs a basic search and a more precise search using term presence modifiers (`+` for required, `-` for prohibited).

from lunr import lunr

documents = [
    {
        "id": "1",
        "title": "Alice's Adventures in Wonderland",
        "body": "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'"
    },
    {
        "id": "2",
        "title": "Through the Looking-Glass",
        "body": "One thing was certain, that the white kitten had had nothing to do with it: it was the black kitten's fault entirely."
    },
    {
        "id": "3",
        "title": "The Hunting of the Snark",
        "body": "'Just the place for a Snark!' the Bellman cried, As he landed his crew with a thump and a shake. 'Just the place for a Snark! I have sought it for years!'"
    }
]

idx = lunr(ref='id', fields=('title', 'body'), documents=documents)

results = idx.search("Alice sister")
for result in results:
    print(f"Document Ref: {result['ref']}, Score: {result['score']}")

results_exact = idx.search("+snark -alice")
print(f"\nExact search results for '+snark -alice':")
for result in results_exact:
    print(f"Document Ref: {result['ref']}, Score: {result['score']}")

view raw JSON →