| 1 |
from collections import defaultdict |
| 2 |
import json |
| 3 |
import logging |
| 4 |
|
| 5 |
from lunr.exceptions import BaseLunrException |
| 6 |
from lunr.field_ref import FieldRef |
| 7 |
from lunr.match_data import MatchData |
| 8 |
from lunr.token_set import TokenSet |
| 9 |
from lunr.token_set_builder import TokenSetBuilder |
| 10 |
from lunr.pipeline import Pipeline |
| 11 |
from lunr.query import Query, QueryPresence |
| 12 |
from lunr.query_parser import QueryParser |
| 13 |
from lunr.utils import CompleteSet |
| 14 |
from lunr.vector import Vector |
| 15 |
|
| 16 |
logger = logging.getLogger(__name__) |
| 17 |
|
| 18 |
|
| 19 |
class Index: |
| 20 |
"""An index contains the built index of all documents and provides a query |
| 21 |
interface to the index. |
| 22 |
|
| 23 |
Usually instances of lunr.Index will not be created using this |
| 24 |
constructor, instead lunr.Builder should be used to construct new |
| 25 |
indexes, or lunr.Index.load should be used to load previously built and |
| 26 |
serialized indexes. |
| 27 |
""" |
| 28 |
|
| 29 |
def __init__(self, inverted_index, field_vectors, token_set, fields, pipeline): |
| 30 |
self.inverted_index = inverted_index |
| 31 |
self.field_vectors = field_vectors |
| 32 |
self.token_set = token_set |
| 33 |
self.fields = fields |
| 34 |
self.pipeline = pipeline |
| 35 |
|
| 36 |
def __eq__(self, other): |
| 37 |
# TODO: extend equality to other attributes |
| 38 |
return ( |
| 39 |
self.inverted_index == other.inverted_index and self.fields == other.fields |
| 40 |
) |
| 41 |
|
| 42 |
def search(self, query_string): |
| 43 |
"""Performs a search against the index using lunr query syntax. |
| 44 |
|
| 45 |
Results will be returned sorted by their score, the most relevant |
| 46 |
results will be returned first. |
| 47 |
|
| 48 |
For more programmatic querying use `lunr.Index.query`. |
| 49 |
|
| 50 |
Args: |
| 51 |
query_string (str): A string to parse into a Query. |
| 52 |
|
| 53 |
Returns: |
| 54 |
dict: Results of executing the query. |
| 55 |
""" |
| 56 |
query = self.create_query() |
| 57 |
# TODO: should QueryParser be a method of query? should it return one? |
| 58 |
parser = QueryParser(query_string, query) |
| 59 |
parser.parse() |
| 60 |
return self.query(query) |
| 61 |
|
| 62 |
def create_query(self, fields=None): |
| 63 |
"""Convenience method to create a Query with the Index's fields. |
| 64 |
|
| 65 |
Args: |
| 66 |
fields (iterable, optional): The fields to include in the Query, |
| 67 |
defaults to the Index's `all_fields`. |
| 68 |
|
| 69 |
Returns: |
| 70 |
Query: With the specified fields or all the fields in the Index. |
| 71 |
""" |
| 72 |
if fields is None: |
| 73 |
return Query(self.fields) |
| 74 |
|
| 75 |
non_contained_fields = set(fields) - set(self.fields) |
| 76 |
if non_contained_fields: |
| 77 |
raise BaseLunrException( |
| 78 |
"Fields {} are not part of the index", non_contained_fields |
| 79 |
) |
| 80 |
|
| 81 |
return Query(fields) |
| 82 |
|
| 83 |
def query(self, query=None, callback=None): |
| 84 |
"""Performs a query against the index using the passed lunr.Query |
| 85 |
object. |
| 86 |
|
| 87 |
If performing programmatic queries against the index, this method is |
| 88 |
preferred over `lunr.Index.search` so as to avoid the additional query |
| 89 |
parsing overhead. |
| 90 |
|
| 91 |
Args: |
| 92 |
query (lunr.Query): A configured Query to perform the search |
| 93 |
against, use `create_query` to get a preconfigured object |
| 94 |
or use `callback` for convenience. |
| 95 |
callback (callable): An optional function taking a single Query |
| 96 |
object result of `create_query` for further configuration. |
| 97 |
""" |
| 98 |
if query is None: |
| 99 |
query = self.create_query() |
| 100 |
|
| 101 |
if callback is not None: |
| 102 |
callback(query) |
| 103 |
|
| 104 |
if len(query.clauses) == 0: |
| 105 |
logger.warning( |
| 106 |
"Attempting a query with no clauses. Please add clauses by " |
| 107 |
"either using the `callback` argument or using `create_query` " |
| 108 |
"to create a preconfigured Query, manually adding clauses and " |
| 109 |
"passing it as the `query` argument." |
| 110 |
) |
| 111 |
return [] |
| 112 |
|
| 113 |
# for each query clause |
| 114 |
# * process terms |
| 115 |
# * expand terms from token set |
| 116 |
# * find matching documents and metadata |
| 117 |
# * get document vectors |
| 118 |
# * score documents |
| 119 |
|
| 120 |
matching_fields = {} |
| 121 |
query_vectors = {field: Vector() for field in self.fields} |
| 122 |
term_field_cache = {} |
| 123 |
required_matches = {} |
| 124 |
prohibited_matches = defaultdict(set) |
| 125 |
|
| 126 |
for clause in query.clauses: |
| 127 |
# Unless the pipeline has been disabled for this term, which is |
| 128 |
# the case for terms with wildcards, we need to pass the clause |
| 129 |
# term through the search pipeline. A pipeline returns an array |
| 130 |
# of processed terms. Pipeline functions may expand the passed |
| 131 |
# term, which means we may end up performing multiple index lookups |
| 132 |
# for a single query term. |
| 133 |
if clause.use_pipeline: |
| 134 |
terms = self.pipeline.run_string(clause.term, {"fields": clause.fields}) |
| 135 |
else: |
| 136 |
terms = [clause.term] |
| 137 |
|
| 138 |
clause_matches = set() |
| 139 |
|
| 140 |
for term in terms: |
| 141 |
# Each term returned from the pipeline needs to use the same |
| 142 |
# query clause object, e.g. the same boost and or edit distance |
| 143 |
# The simplest way to do this is to re-use the clause object |
| 144 |
# but mutate its term property. |
| 145 |
clause.term = term |
| 146 |
|
| 147 |
# From the term in the clause we create a token set which will |
| 148 |
# then be used to intersect the indexes token set to get a list |
| 149 |
# of terms to lookup in the inverted index |
| 150 |
term_token_set = TokenSet.from_clause(clause) |
| 151 |
expanded_terms = self.token_set.intersect(term_token_set).to_list() |
| 152 |
|
| 153 |
# If a term marked as required does not exist in the TokenSet |
| 154 |
# it is impossible for the search to return any matches. |
| 155 |
# We set all the field-scoped required matches set to empty |
| 156 |
# and stop examining further clauses |
| 157 |
if ( |
| 158 |
len(expanded_terms) == 0 |
| 159 |
and clause.presence == QueryPresence.REQUIRED |
| 160 |
): |
| 161 |
for field in clause.fields: |
| 162 |
required_matches[field] = CompleteSet() |
| 163 |
break |
| 164 |
|
| 165 |
for expanded_term in expanded_terms: |
| 166 |
posting = self.inverted_index[expanded_term] |
| 167 |
term_index = posting["_index"] |
| 168 |
|
| 169 |
for field in clause.fields: |
| 170 |
# For each field that this query term is scoped by |
| 171 |
# (by default all fields are in scope) we need to get |
| 172 |
# all the document refs that have this term in that |
| 173 |
# field. |
| 174 |
# |
| 175 |
# The posting is the entry in the invertedIndex for the |
| 176 |
# matching term from above. |
| 177 |
field_posting = posting[field] |
| 178 |
matching_document_refs = field_posting.keys() |
| 179 |
term_field = expanded_term + "/" + field |
| 180 |
matching_documents_set = set(matching_document_refs) |
| 181 |
|
| 182 |
# If the presence of this term is required, ensure that |
| 183 |
# the matching documents are added to the set of |
| 184 |
# required matches for this clause. |
| 185 |
if clause.presence == QueryPresence.REQUIRED: |
| 186 |
clause_matches = clause_matches.union( |
| 187 |
matching_documents_set |
| 188 |
) |
| 189 |
|
| 190 |
if field not in required_matches: |
| 191 |
required_matches[field] = CompleteSet() |
| 192 |
|
| 193 |
# If the presence of this term is prohibited, |
| 194 |
# ensure that the matching documents are added to the |
| 195 |
# set of prohibited matches for this field, creating |
| 196 |
# that set if it does not exist yet. |
| 197 |
elif clause.presence == QueryPresence.PROHIBITED: |
| 198 |
prohibited_matches[field] = prohibited_matches[field].union( |
| 199 |
matching_documents_set |
| 200 |
) |
| 201 |
|
| 202 |
# prohibited matches should not be part of the |
| 203 |
# query vector used for similarity scoring and no |
| 204 |
# metadata should be extracted so we continue |
| 205 |
# to the next field |
| 206 |
continue |
| 207 |
|
| 208 |
# The query field vector is populated using the |
| 209 |
# term_index found for the term an a unit value with |
| 210 |
# the appropriate boost |
| 211 |
# Using upsert because there could already be an entry |
| 212 |
# in the vector for the term we are working with. |
| 213 |
# In that case we just add the scores together. |
| 214 |
query_vectors[field].upsert( |
| 215 |
term_index, clause.boost, lambda a, b: a + b |
| 216 |
) |
| 217 |
|
| 218 |
# If we've already seen this term, field combo then |
| 219 |
# we've already collected the matching documents and |
| 220 |
# metadata, no need to go through all that again |
| 221 |
if term_field in term_field_cache: |
| 222 |
continue |
| 223 |
|
| 224 |
for matching_document_ref in matching_document_refs: |
| 225 |
# All metadata for this term/field/document triple |
| 226 |
# are then extracted and collected into an instance |
| 227 |
# of lunr.MatchData ready to be returned in the |
| 228 |
# query results |
| 229 |
matching_field_ref = FieldRef(matching_document_ref, field) |
| 230 |
metadata = field_posting[str(matching_document_ref)] |
| 231 |
|
| 232 |
if str(matching_field_ref) not in matching_fields: |
| 233 |
matching_fields[str(matching_field_ref)] = MatchData( |
| 234 |
expanded_term, field, metadata |
| 235 |
) |
| 236 |
else: |
| 237 |
matching_fields[str(matching_field_ref)].add( |
| 238 |
expanded_term, field, metadata |
| 239 |
) |
| 240 |
|
| 241 |
term_field_cache[term_field] = True |
| 242 |
|
| 243 |
# if the presence was required we need to update the required |
| 244 |
# matches field sets, we do this after all fields for the term |
| 245 |
# have collected their matches because the clause terms presence |
| 246 |
# is required in _any_ of the fields, not _all_ of the fields |
| 247 |
if clause.presence == QueryPresence.REQUIRED: |
| 248 |
for field in clause.fields: |
| 249 |
required_matches[field] = required_matches[field].intersection( |
| 250 |
clause_matches |
| 251 |
) |
| 252 |
|
| 253 |
# We need to combine the field scoped required and prohibited |
| 254 |
# matching documents inot a global set of required and prohibited |
| 255 |
# matches |
| 256 |
all_required_matches = CompleteSet() |
| 257 |
all_prohibited_matches = set() |
| 258 |
for field in self.fields: |
| 259 |
if field in required_matches: |
| 260 |
all_required_matches = all_required_matches.intersection( |
| 261 |
required_matches[field] |
| 262 |
) |
| 263 |
if field in prohibited_matches: |
| 264 |
all_prohibited_matches = all_prohibited_matches.union( |
| 265 |
prohibited_matches[field] |
| 266 |
) |
| 267 |
|
| 268 |
matching_field_refs = matching_fields.keys() |
| 269 |
results = [] |
| 270 |
matches = {} |
| 271 |
|
| 272 |
# If the query is negated (only contains prohibited terms) |
| 273 |
# we need to get _all_ field_refs currently existing in the index. |
| 274 |
# This to avoid any costs of getting all field regs unnecessarily |
| 275 |
# Additionally, blank match data must be created to correctly populate |
| 276 |
# the results |
| 277 |
if query.is_negated(): |
| 278 |
matching_field_refs = list(self.field_vectors.keys()) |
| 279 |
|
| 280 |
for matching_field_ref in matching_field_refs: |
| 281 |
field_ref = FieldRef.from_string(matching_field_ref) |
| 282 |
matching_fields[matching_field_ref] = MatchData() |
| 283 |
|
| 284 |
for matching_field_ref in matching_field_refs: |
| 285 |
# Currently we have document fields that match the query, but we |
| 286 |
# need to return documents. The matchData and scores are combined |
| 287 |
# from multiple fields belonging to the same document. |
| 288 |
# |
| 289 |
# Scores are calculated by field, using the query vectors created |
| 290 |
# above, and combined into a final document score using addition. |
| 291 |
field_ref = FieldRef.from_string(matching_field_ref) |
| 292 |
doc_ref = field_ref.doc_ref |
| 293 |
|
| 294 |
if doc_ref not in all_required_matches or doc_ref in all_prohibited_matches: |
| 295 |
continue |
| 296 |
|
| 297 |
field_vector = self.field_vectors[matching_field_ref] |
| 298 |
score = query_vectors[field_ref.field_name].similarity(field_vector) |
| 299 |
|
| 300 |
try: |
| 301 |
doc_match = matches[doc_ref] |
| 302 |
doc_match["score"] += score |
| 303 |
doc_match["match_data"].combine(matching_fields[matching_field_ref]) |
| 304 |
except KeyError: |
| 305 |
match = { |
| 306 |
"ref": doc_ref, |
| 307 |
"score": score, |
| 308 |
"match_data": matching_fields[matching_field_ref], |
| 309 |
} |
| 310 |
matches[doc_ref] = match |
| 311 |
results.append(match) |
| 312 |
|
| 313 |
return sorted(results, key=lambda a: a["score"], reverse=True) |
| 314 |
|
| 315 |
def serialize(self): |
| 316 |
"""Returns a serialized index as a dict following lunr-schema.""" |
| 317 |
from lunr import __TARGET_JS_VERSION__ |
| 318 |
|
| 319 |
inverted_index = [ |
| 320 |
[term, self.inverted_index[term]] for term in sorted(self.inverted_index) |
| 321 |
] |
| 322 |
field_vectors = [ |
| 323 |
[ref, vector.serialize()] for ref, vector in self.field_vectors.items() |
| 324 |
] |
| 325 |
|
| 326 |
# CamelCased keys for compatibility with JS version |
| 327 |
return { |
| 328 |
"version": __TARGET_JS_VERSION__, |
| 329 |
"fields": self.fields, |
| 330 |
"fieldVectors": field_vectors, |
| 331 |
"invertedIndex": inverted_index, |
| 332 |
"pipeline": self.pipeline.serialize(), |
| 333 |
} |
| 334 |
|
| 335 |
@classmethod |
| 336 |
def load(cls, serialized_index): |
| 337 |
"""Load a serialized index""" |
| 338 |
from lunr import __TARGET_JS_VERSION__ |
| 339 |
|
| 340 |
if isinstance(serialized_index, str): |
| 341 |
serialized_index = json.loads(serialized_index) |
| 342 |
|
| 343 |
if serialized_index["version"] != __TARGET_JS_VERSION__: |
| 344 |
logger.warning( |
| 345 |
"Version mismatch when loading serialized index. " |
| 346 |
"Current version of lunr {} does not match that of serialized " |
| 347 |
"index {}".format(__TARGET_JS_VERSION__, serialized_index["version"]) |
| 348 |
) |
| 349 |
|
| 350 |
field_vectors = { |
| 351 |
ref: Vector(elements) for ref, elements in serialized_index["fieldVectors"] |
| 352 |
} |
| 353 |
|
| 354 |
tokenset_builder = TokenSetBuilder() |
| 355 |
inverted_index = {} |
| 356 |
for term, posting in serialized_index["invertedIndex"]: |
| 357 |
tokenset_builder.insert(term) |
| 358 |
inverted_index[term] = posting |
| 359 |
|
| 360 |
tokenset_builder.finish() |
| 361 |
|
| 362 |
return Index( |
| 363 |
fields=serialized_index["fields"], |
| 364 |
field_vectors=field_vectors, |
| 365 |
inverted_index=inverted_index, |
| 366 |
token_set=tokenset_builder.root, |
| 367 |
pipeline=Pipeline.load(serialized_index["pipeline"]), |
| 368 |
) |