Debian Codegraph @

lunr/builder.py

raw
1 from collections import defaultdict
2
3
4 from lunr.pipeline import Pipeline
5 from lunr.tokenizer import Tokenizer
6 from lunr.token_set import TokenSet
7 from lunr.field_ref import FieldRef
8 from lunr.index import Index
9 from lunr.vector import Vector
10 from lunr.idf import idf as Idf
11
12
13 class Field:
14 """Represents a field with boost and extractor functions."""
15
16 def __init__(self, field_name, boost=1, extractor=None):
17 self.name = field_name
18 self.boost = boost
19 self.extractor = extractor
20
21 def __repr__(self):
22 return '<Field "{0.name}" boost="{0.boost}">'.format(self)
23
24 def __hash__(self):
25 return hash(self.name)
26
27
28 class Builder:
29 """Performs indexing on a set of documents and returns instances of
30 lunr.Index ready for querying.
31
32 All configuration of the index is done via the builder, the fields to
33 index, the document reference, the text processing pipeline and document
34 scoring parameters are all set on the builder before indexing.
35 """
36
37 def __init__(self):
38 self._ref = "id"
39 self._fields = {}
40 self.inverted_index = {}
41 self.field_term_frequencies = {}
42 self.field_lengths = {}
43 self.pipeline = Pipeline()
44 self.search_pipeline = Pipeline()
45 self._documents = {}
46 self.document_count = 0
47 self._b = 0.75
48 self._k1 = 1.2
49 self.term_index = 0
50 self.metadata_whitelist = []
51
52 def ref(self, ref):
53 """Sets the document field used as the document reference.
54
55 Every document must have this field. The type of this field in the
56 document should be a string, if it is not a string it will be coerced
57 into a string by calling `str`.
58
59 The default ref is 'id'. The ref should _not_ be changed during
60 indexing, it should be set before any documents are added to the index.
61 Changing it during indexing can lead to inconsistent results.
62
63 """
64 self._ref = ref
65
66 def field(self, field_name, boost=1, extractor=None):
67 """Adds a field to the list of document fields that will be indexed.
68
69 Every document being indexed should have this field. None values for
70 this field in indexed documents will not cause errors but will limit
71 the chance of that document being retrieved by searches.
72
73 All fields should be added before adding documents to the index. Adding
74 fields after a document has been indexed will have no effect on already
75 indexed documents.
76
77 Fields can be boosted at build time. This allows terms within that
78 field to have more importance on search results. Use a field boost to
79 specify that matches within one field are more important that other
80 fields.
81
82 Args:
83 field_name (str): Name of the field to be added, must not include
84 a forward slash '/'.
85 boost (int): Optional boost factor to apply to field.
86 extractor (callable): Optional function to extract a field from
87 the document.
88
89 Raises:
90 ValueError: If the field name contains a `/`.
91 """
92 if "/" in field_name:
93 raise ValueError("Field {} contains illegal character `/`")
94
95 self._fields[field_name] = Field(field_name, boost, extractor)
96
97 def b(self, number):
98 """A parameter to tune the amount of field length normalisation that is
99 applied when calculating relevance scores.
100
101 A value of 0 will completely disable any normalisation and a value of 1
102 will fully normalise field lengths. The default is 0.75. Values of b
103 will be clamped to the range 0 - 1.
104 """
105 if number < 0:
106 self._b = 0
107 elif number > 1:
108 self._b = 1
109 else:
110 self._b = number
111
112 def k1(self, number):
113 """A parameter that controls the speed at which a rise in term
114 frequency results in term frequency saturation.
115
116 The default value is 1.2. Setting this to a higher value will give
117 slower saturation levels, a lower value will result in quicker
118 saturation.
119 """
120 self._k1 = number
121
122 def add(self, doc, attributes=None):
123 """Adds a document to the index.
124
125 Before adding documents to the index it should have been fully
126 setup, with the document ref and all fields to index already having
127 been specified.
128
129 The document must have a field name as specified by the ref (by default
130 this is 'id') and it should have all fields defined for indexing,
131 though None values will not cause errors.
132
133 Args:
134 - doc (dict): The document to be added to the index.
135 - attributes (dict, optional): A set of attributes corresponding
136 to the document, currently a single `boost` -> int will be
137 taken into account.
138 """
139 doc_ref = str(doc[self._ref])
140 self._documents[doc_ref] = attributes or {}
141 self.document_count += 1
142
143 for field_name, field in self._fields.items():
144 extractor = field.extractor
145 field_value = doc[field_name] if extractor is None else extractor(doc)
146 tokens = Tokenizer(field_value)
147 terms = self.pipeline.run(tokens, field_name)
148 field_ref = FieldRef(doc_ref, field_name)
149 field_terms = defaultdict(int)
150
151 # TODO: field_refs are casted to strings in JS, should we allow
152 # FieldRef as keys?
153 self.field_term_frequencies[str(field_ref)] = field_terms
154 self.field_lengths[str(field_ref)] = len(terms)
155
156 for term in terms:
157 # TODO: term is a Token, should we allow Tokens as keys?
158 term_key = str(term)
159
160 field_terms[term_key] += 1
161 if term_key not in self.inverted_index:
162 posting = {_field_name: {} for _field_name in self._fields}
163 posting["_index"] = self.term_index
164 self.term_index += 1
165 self.inverted_index[term_key] = posting
166
167 if doc_ref not in self.inverted_index[term_key][field_name]:
168 self.inverted_index[term_key][field_name][doc_ref] = defaultdict(
169 list
170 )
171
172 for metadata_key in self.metadata_whitelist:
173 metadata = term.metadata[metadata_key]
174 self.inverted_index[term_key][field_name][doc_ref][
175 metadata_key
176 ].append(metadata)
177
178 def build(self):
179 """Builds the index, creating an instance of `lunr.Index`.
180
181 This completes the indexing process and should only be called once all
182 documents have been added to the index.
183 """
184 self._calculate_average_field_lengths()
185 self._create_field_vectors()
186 self._create_token_set()
187
188 return Index(
189 inverted_index=self.inverted_index,
190 field_vectors=self.field_vectors,
191 token_set=self.token_set,
192 fields=list(self._fields.keys()),
193 pipeline=self.search_pipeline,
194 )
195
196 def _create_token_set(self):
197 """Creates a token set of all tokens in the index using `lunr.TokenSet`"""
198 self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys())))
199
200 def _calculate_average_field_lengths(self):
201 """Calculates the average document length for this index"""
202 accumulator = defaultdict(int)
203 documents_with_field = defaultdict(int)
204
205 for field_ref, length in self.field_lengths.items():
206 _field_ref = FieldRef.from_string(field_ref)
207 field = _field_ref.field_name
208
209 documents_with_field[field] += 1
210 accumulator[field] += length
211
212 for field_name in self._fields:
213 accumulator[field_name] /= documents_with_field[field_name]
214
215 self.average_field_length = accumulator
216
217 def _create_field_vectors(self):
218 """Builds a vector space model of every document using lunr.Vector."""
219 field_vectors = {}
220 term_idf_cache = {}
221
222 for field_ref, term_frequencies in self.field_term_frequencies.items():
223 _field_ref = FieldRef.from_string(field_ref)
224 field_name = _field_ref.field_name
225 field_length = self.field_lengths[field_ref]
226 field_vector = Vector()
227 field_boost = self._fields[field_name].boost
228 doc_boost = self._documents[_field_ref.doc_ref].get("boost", 1)
229
230 for term, tf in term_frequencies.items():
231 term_index = self.inverted_index[term]["_index"]
232
233 if term not in term_idf_cache:
234 idf = Idf(self.inverted_index[term], self.document_count)
235 term_idf_cache[term] = idf
236 else:
237 idf = term_idf_cache[term]
238
239 score = (
240 idf
241 * ((self._k1 + 1) * tf)
242 / (
243 self._k1
244 * (
245 1
246 - self._b
247 + self._b
248 * (field_length / self.average_field_length[field_name])
249 )
250 + tf
251 )
252 )
253 score *= field_boost
254 score *= doc_boost
255 score_with_precision = round(score, 3)
256
257 field_vector.insert(term_index, score_with_precision)
258
259 field_vectors[field_ref] = field_vector
260
261 self.field_vectors = field_vectors
262
263 def use(self, fn, *args, **kwargs):
264 """Applies a plugin to the index builder.
265
266 A plugin is a function that is called with the index builder as its
267 context. Plugins can be used to customise or extend the behaviour of
268 the index in some way.
269
270 A plugin is just a function, that encapsulated the custom behaviour
271 that should be applied when building the index. The plugin function
272 will be called with the index builder as its argument, additional
273 arguments can also be passed when calling use.
274 """
275 fn(self, *args, **kwargs)