| 1 |
from lunr import languages as lang |
| 2 |
from lunr.builder import Builder |
| 3 |
from lunr.stemmer import stemmer |
| 4 |
from lunr.trimmer import trimmer |
| 5 |
from lunr.stop_word_filter import stop_word_filter |
| 6 |
|
| 7 |
|
| 8 |
def lunr(ref, fields, documents, languages=None, builder=None): |
| 9 |
"""A convenience function to configure and construct a lunr.Index. |
| 10 |
|
| 11 |
Args: |
| 12 |
ref (str): The key in the documents to be used a the reference. |
| 13 |
fields (list): A list of strings defining fields in the documents to |
| 14 |
index. Optionally a list of dictionaries with three keys: |
| 15 |
`field_name` defining the document's field, `boost` an integer |
| 16 |
defining a boost to be applied to the field, and `extractor` |
| 17 |
a callable taking the document as a single argument and returning |
| 18 |
a string located in the document in a particular way. |
| 19 |
documents (list): The list of dictonaries representing the documents |
| 20 |
to index. Optionally a 2-tuple of dicts, the first one being |
| 21 |
the document and the second the associated attributes to it. |
| 22 |
languages (str or list, optional): The languages to use if using |
| 23 |
NLTK language support, ignored if NLTK is not available. |
| 24 |
|
| 25 |
Returns: |
| 26 |
Index: The populated Index ready to search against. |
| 27 |
""" |
| 28 |
builder = builder or get_default_builder(languages) |
| 29 |
builder.ref(ref) |
| 30 |
for field in fields: |
| 31 |
if isinstance(field, dict): |
| 32 |
builder.field(**field) |
| 33 |
else: |
| 34 |
builder.field(field) |
| 35 |
|
| 36 |
for document in documents: |
| 37 |
if isinstance(document, (tuple, list)): |
| 38 |
builder.add(document[0], attributes=document[1]) |
| 39 |
else: |
| 40 |
builder.add(document) |
| 41 |
|
| 42 |
return builder.build() |
| 43 |
|
| 44 |
|
| 45 |
def get_default_builder(languages=None): |
| 46 |
"""Creates a new pre-configured instance of Builder. |
| 47 |
|
| 48 |
Useful as a starting point to tweak the defaults. |
| 49 |
""" |
| 50 |
if languages is not None and lang.LANGUAGE_SUPPORT: |
| 51 |
if isinstance(languages, str): |
| 52 |
languages = [languages] |
| 53 |
|
| 54 |
unsupported_languages = set(languages) - set(lang.SUPPORTED_LANGUAGES) |
| 55 |
if unsupported_languages: |
| 56 |
raise RuntimeError( |
| 57 |
"The specified languages {} are not supported, " |
| 58 |
"please choose one of {}".format( |
| 59 |
", ".join(unsupported_languages), |
| 60 |
", ".join(lang.SUPPORTED_LANGUAGES.keys()), |
| 61 |
) |
| 62 |
) |
| 63 |
builder = lang.get_nltk_builder(languages) |
| 64 |
else: |
| 65 |
builder = Builder() |
| 66 |
builder.pipeline.add(trimmer, stop_word_filter, stemmer) |
| 67 |
builder.search_pipeline.add(stemmer) |
| 68 |
|
| 69 |
return builder |