Coverage for src/scixplorer/search.py: 98%

550 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-18 23:06 +0000

1"""Plan and run document searches on the ADS search API. 

2 

3:func:`plan` turns a :class:`~scixplorer.query.Query` over :class:`~scixplorer.models.document.Document` 

4into a :class:`SearchPlan`: the Solr ``q``, ``fl`` and ``sort`` parameters, and 

5which endpoint to use. It is pure (no I/O) and runs these passes in order: 

6 

71. Wrap predicates on a related model's fields (``Journal.title == ...``) in the 

8 one document relation that leads to that model. 

92. Resolve each relation predicate against the related model (held in memory) 

10 into a set of keys: ``Document.journal.title.contains("x")`` becomes 

11 ``bibstem:(...)`` and ``Document.affiliation.country == "Australia"`` becomes 

12 ``aff_id:(...)``. 

133. Library membership: left to ADS as ``docs(library/<id>)``, or (with 

14 ``config.library_membership = "bibcodes"``) replaced by the library's bibcodes. 

154. Simplify; a filter that can never match needs no request at all. 

16 Then per-record conditions (``Document.authors.any(...)``, see 

17 :func:`_per_record`): each is translated into a condition on the 

18 document's arrays. One that this expresses exactly is replaced by it, 

19 wherever it is; any other must be a top-level ``&`` condition (optionally 

20 negated), sends only its necessary condition, and is checked client-side 

21 on each returned document (a *refinement*). 

225. The default collection (``config.collection``): an open search is limited 

23 to it by a final top-level ``database:`` condition, unless the filter names 

24 the collection itself or names specific documents (see :func:`_collection_scope`). 

256. Move large bibcode sets out of the query string: a top-level positive set is 

26 sent to ``/search/bigquery`` and a top-level negated set is excluded while 

27 streaming (with offset and limit then applied locally, as for a refinement). 

28 A search that would filter locally while ADS is sent ``*:*`` (apart from the 

29 default collection) is refused: it would download the whole index. 

307. Compile, adding a final sort key so that pages are stable. 

31 

32:class:`SearchBackend` executes plans in the sans-IO protocol of :mod:`scixplorer.query`. 

33""" 

34 

35from __future__ import annotations 

36 

37import weakref 

38from collections.abc import Callable, Generator, Iterator, Mapping, Sequence 

39from dataclasses import dataclass, replace 

40from typing import Any 

41 

42from . import _config, evaluate, solr 

43from .client import Request, Response 

44from .exceptions import APIError, NotLocallyEvaluable, QueryError, UnsupportedQueryError 

45from .expr import ( 

46 EVERYTHING, 

47 NOTHING, 

48 And, 

49 Constant, 

50 Expr, 

51 Func, 

52 In, 

53 InLibrary, 

54 Like, 

55 Match, 

56 Not, 

57 Or, 

58 Order, 

59 Quantified, 

60 Range, 

61 Raw, 

62 Related, 

63 simplify, 

64 transform, 

65 walk, 

66) 

67from .fields import Field, VirtualField 

68from .model import Model, Relation 

69from .models.library import fetch_bibcodes 

70from .query import Explanation, Query 

71 

72__all__ = [ 

73 "BIGQUERY_PATH", 

74 "MAX_PAGE_SIZE", 

75 "MAX_RELATED_VALUES", 

76 "POSITIONAL_FIELDS", 

77 "QUERY_PATH", 

78 "ResultPage", 

79 "SearchBackend", 

80 "SearchPlan", 

81 "plan", 

82 "to_solr", 

83] 

84 

85#: Most keys a relation predicate may resolve to: one GET request cannot carry more clauses. 

86MAX_RELATED_VALUES = 1000 

87 

88#: Most rows ADS returns per search request. 

89MAX_PAGE_SIZE = 2000 

90 

91#: Document fields that ADS searches by position with ``pos()``, so that a 

92#: per-author condition on one of them at given positions 

93#: (``Document.authors[0].aff == ...``) is sent as ``pos(aff:..., 1)``. A 

94#: positional condition on any other field is sent without ``pos()`` and checked 

95#: client-side. Read at planning time. The live tests confirm that ADS accepts 

96#: ``pos()`` on these three. 

97POSITIONAL_FIELDS = frozenset({"author", "aff", "aff_id"}) 

98 

99QUERY_PATH = "/search/query" 

100BIGQUERY_PATH = "/search/bigquery" 

101 

102_STRATEGIES = ("docs", "bibcodes") 

103 

104#: Fields besides the identifiers (``Document._identifiers``) whose values name 

105#: specific documents: a top-level condition on one exempts a search from the 

106#: default collection. 

107_ALSO_NAMING = ("identifier", "doi", "alternate_bibcode") 

108 

109#: Fields through which a filter names the collection itself, and how raw Solr text does. 

110_COLLECTION_FIELDS = ("database", "collection") 

111_COLLECTION_TEXT = ("database:", "collection:") 

112 

113#: Fields whose values are unique, so that sorting by one needs no tiebreaker. 

114#: (``scix_id`` is left out until it is known to be sortable on the server.) 

115_UNIQUE = frozenset({"id", "bibcode"}) 

116 

117 

118@dataclass(frozen=True) 

119class SearchPlan: 

120 """How a document query is sent to ADS. 

121 

122 ``q``, ``fl`` (Solr field names) and ``sort`` are the search parameters. 

123 ``bigquery_bibcodes`` is set when the search goes to ``/search/bigquery`` 

124 with those bibcodes. Results are filtered locally while streaming (and 

125 offset and limit then applied locally) when ``exclude_bibcodes`` are to be 

126 dropped or a ``refinement`` (a condition ``q`` only approximates) must 

127 hold for each document; ``refinement_fl`` are the fields it reads. An 

128 ``empty`` plan sends no request: nothing can match. ``notes`` explain the 

129 planner's decisions. 

130 """ 

131 

132 q: str 

133 fl: tuple[str, ...] 

134 sort: str 

135 bigquery_bibcodes: tuple[str, ...] | None = None 

136 exclude_bibcodes: frozenset[str] | None = None 

137 empty: bool = False 

138 notes: tuple[str, ...] = () 

139 refinement: Expr | None = None 

140 refinement_fl: tuple[str, ...] = () 

141 

142 @property 

143 def filters_locally(self) -> bool: 

144 """Whether results are filtered while streaming, so offset and limit are applied locally.""" 

145 return self.exclude_bibcodes is not None or self.refinement is not None 

146 

147 @property 

148 def path(self) -> str: 

149 """The endpoint: ``/search/bigquery`` or ``/search/query``.""" 

150 return QUERY_PATH if self.bigquery_bibcodes is None else BIGQUERY_PATH 

151 

152 def request(self, start: int, rows: int, *, fl: Sequence[str] | None = None) -> Request: 

153 """The request for ``rows`` results from position ``start`` (``fl`` overrides the fields).""" 

154 params: dict[str, Any] = { 

155 "q": self.q, 

156 "fl": ",".join(self.fl if fl is None else fl), 

157 "sort": self.sort, 

158 "start": start, 

159 "rows": rows, 

160 } 

161 if self.bigquery_bibcodes is None: 

162 return Request("GET", QUERY_PATH, params=params) 

163 params["fq"] = "{!bitset}" 

164 return Request( 

165 "POST", 

166 BIGQUERY_PATH, 

167 params=params, 

168 content="bibcode\n" + "\n".join(self.bigquery_bibcodes), 

169 headers={"Content-Type": "big-query/csv"}, 

170 idempotent=True, 

171 ) 

172 

173 

174class ResultPage: 

175 """The documents of one page of results and the client that fetched them. 

176 

177 Documents keep a reference to their page so that a field read on one of 

178 them can be loaded for all of them with one request. The page holds the 

179 documents weakly, so it never keeps them alive. 

180 """ 

181 

182 __slots__ = ("client", "_members") 

183 

184 def __init__(self, client: Any) -> None: 

185 self.client = client 

186 self._members: list[weakref.ref[Model]] = [] 

187 

188 def attach(self, document: Model) -> None: 

189 """Add ``document`` to this page.""" 

190 self._members.append(weakref.ref(document)) 

191 setattr(document, "_page", self) 

192 

193 def members(self) -> list[Model]: 

194 """The documents of this page that still exist, in result order.""" 

195 alive = (ref() for ref in self._members) 

196 return [document for document in alive if document is not None] 

197 

198 

199# Planning. 

200 

201 

202@dataclass(frozen=True) 

203class _Resolved: 

204 """The filter after relations are resolved (passes 1 and 2), with notes so far.""" 

205 

206 expr: Expr 

207 notes: tuple[str, ...] 

208 

209 

210def plan(query: Query[Any], *, library_bibcodes: Mapping[str, Sequence[str]] | None = None) -> SearchPlan: 

211 """Plan ``query``: decide the request parameters without performing any I/O. 

212 

213 With ``config.library_membership == "bibcodes"``, ``library_bibcodes`` must 

214 map the id of every library in the filter to its bibcodes (the backend 

215 fetches them). Raises :class:`~scixplorer.exceptions.QueryError` (or its subclass 

216 :class:`~scixplorer.exceptions.UnsupportedQueryError`) for a query that cannot be 

217 sent, and ``ValueError`` for an invalid configuration. 

218 """ 

219 return _finish(query, _resolve(query), library_bibcodes or {}) 

220 

221 

222def to_solr(query_or_expr: Query[Any] | Expr) -> str: 

223 """The Solr ``q`` string that a document query (or a filter expression) sends. 

224 

225 For a search sent to ``/search/bigquery`` this is the query applied to the 

226 uploaded bibcodes, without them; for one with a per-record condition 

227 checked client-side, it holds only that condition's necessary part. A filter that can never match gives the 

228 query matching nothing. Raises :class:`~scixplorer.exceptions.UnsupportedQueryError` 

229 if the query needs the bibcodes of a library (``library_membership="bibcodes"``). 

230 """ 

231 if isinstance(query_or_expr, Expr): 

232 from .models.document import Document 

233 

234 query: Query[Any] = Document.select().where(query_or_expr) 

235 else: 

236 query = query_or_expr 

237 resolved = _resolve(query) 

238 ids = _library_ids(resolved) 

239 if ids: 

240 raise UnsupportedQueryError( 

241 f"With scixplorer.config.library_membership = 'bibcodes' this query needs the bibcodes " 

242 f"of library {ids[0]!r}, which to_solr() does not fetch. Use query.explain(), or " 

243 f"set library_membership = 'docs' to see the query with docs(library/<id>)." 

244 ) 

245 return _finish(query, resolved, {}).q 

246 

247 

248def _strategy() -> str: 

249 strategy = _config.config.library_membership 

250 if strategy not in _STRATEGIES: 

251 raise ValueError( 

252 f"scixplorer.config.library_membership must be 'docs' or 'bibcodes', not {strategy!r}" 

253 ) 

254 return strategy 

255 

256 

257def _page_size() -> int: 

258 size = _config.config.page_size 

259 if isinstance(size, bool) or not isinstance(size, int) or size < 1: 

260 raise ValueError(f"scixplorer.config.page_size must be a positive int, not {size!r}") 

261 return min(size, MAX_PAGE_SIZE) 

262 

263 

264def _resolve(query: Query[Any]) -> _Resolved: 

265 """Passes 1 and 2: wrap implicit relation predicates, then resolve every relation.""" 

266 model = query.model 

267 expr = query.expr if query.expr is not None else EVERYTHING 

268 notes: list[str] = [] 

269 expr = _wrap_implicit(expr, model) 

270 expr = transform(expr, lambda node: _resolve_related(node, model, notes)) 

271 return _Resolved(expr, tuple(notes)) 

272 

273 

274def _wrap_implicit(expr: Expr, model: type[Model]) -> Expr: 

275 """Wrap each leaf on another model's field in the relation leading to that model. 

276 

277 Existing :class:`Related` predicates are left alone: their leaves are 

278 meant to be on the related model. (``transform`` cannot skip a subtree, 

279 so this recursion is written out.) 

280 """ 

281 if isinstance(expr, Related): 

282 return expr 

283 if isinstance(expr, (And, Or)): 

284 return type(expr)(tuple(_wrap_implicit(operand, model) for operand in expr.operands)) 

285 if isinstance(expr, Not): 

286 return Not(_wrap_implicit(expr.operand, model)) 

287 if isinstance(expr, Func): 

288 args = tuple(_wrap_implicit(arg, model) if isinstance(arg, Expr) else arg for arg in expr.args) 

289 return Func(expr.name, args) 

290 if isinstance(expr, (Match, In, Like, Range)): 

291 owner = expr.field.model 

292 if issubclass(model, owner): 

293 return expr 

294 relations = [rel for rel in model._relations.values() if rel.related_model is owner] 

295 if len(relations) == 1: 

296 return Related(relations[0], expr) 

297 if not relations: 

298 message = ( 

299 f"{owner.__name__}.{expr.field.name} is not a field of {model.__name__}, and " 

300 f"{model.__name__} has no relation to {owner.__name__}" 

301 ) 

302 for collection in model._collections.values(): 

303 if collection.record_model is owner: 

304 message += ( 

305 f"; {owner.__name__} fields are used inside {collection.label()}.any(...) or " 

306 f".all(...), e.g. {collection.label()}.any({owner.__name__}.{expr.field.name} == ...)" 

307 ) 

308 raise QueryError(message) 

309 names = ", ".join(f"{model.__name__}.{rel.name}" for rel in relations) 

310 raise QueryError( 

311 f"{owner.__name__}.{expr.field.name} is ambiguous: say which relation it is " 

312 f"reached through ({names}), e.g. {model.__name__}.{relations[0].name}.{expr.field.name}" 

313 ) 

314 return expr 

315 

316 

317def _resolve_related(node: Expr, model: type[Model], notes: list[str]) -> Expr: 

318 """Pass 2 for one node: a relation predicate becomes ``In(<owner key field>, keys)``.""" 

319 if not isinstance(node, Related) or model._relations.get(node.relation.name) is not node.relation: 

320 return node 

321 relation = node.relation 

322 return _keys_condition(relation, node.predicate, model._fields[relation.key], f"{model.__name__}.{relation.name}", notes) 

323 

324 

325def _keys_condition( 

326 relation: Relation[Any], predicate: Expr, key_field: Field[Any, Any], label: str, notes: list[str] 

327) -> Expr: 

328 """``In(key_field, keys)`` for the related rows matching ``predicate`` (``NOTHING`` if none), with a note. 

329 

330 Shared by document relations and relations of a collection's records 

331 (``Author.affiliation``), so both resolve and are limited alike. 

332 """ 

333 keys, how = _related_keys(relation, predicate, label) 

334 if not keys: 

335 notes.append(f"{label}: {how}; no {relation.related_model.__name__} matched, so this condition matches nothing") 

336 return NOTHING 

337 if len(keys) > MAX_RELATED_VALUES: 

338 raise UnsupportedQueryError( 

339 f"{label}: {len(keys)} {relation.related_model.__name__} rows matched " 

340 f"{_describe(predicate)}, but at most {MAX_RELATED_VALUES} {relation.key} values fit in " 

341 f"one search request. Narrow the {relation.related_model.__name__} condition." 

342 ) 

343 notes.append(f"{label}: {how}; matched as {relation.key} in {len(keys)} value(s)") 

344 return In(key_field, tuple(keys)) 

345 

346 

347def _related_keys(relation: Relation[Any], predicate: Expr, label: str) -> tuple[list[Any], str]: 

348 """The ``related_key`` values of the related rows matching ``predicate``, and how they were found. 

349 

350 A predicate that only compares the related key itself (``Document.journal == 

351 "ApJ"``) gives its values directly, so a key missing from the local data 

352 still matches on ADS. 

353 """ 

354 key_field = relation.related_field 

355 if isinstance(predicate, Match) and predicate.field is key_field: 

356 return [predicate.value], f"{relation.related_key} given directly" 

357 if isinstance(predicate, In) and predicate.field is key_field: 

358 return list(dict.fromkeys(predicate.values)), f"{relation.related_key} given directly" 

359 related = relation.related_model 

360 try: 

361 rows = _local_rows(related, related.select().where(predicate)) 

362 except NotLocallyEvaluable as exc: 

363 raise NotLocallyEvaluable( 

364 f"{label}: the {related.__name__} condition must be evaluable locally, " 

365 f"because {related.__name__} rows are matched in Python before searching: {exc}" 

366 ) from exc 

367 keys = (getattr(row, relation.related_key) for row in rows) 

368 found = list(dict.fromkeys(key for key in keys if key is not None)) 

369 return found, f"{len(rows)} {related.__name__} row(s) matched {_describe(predicate)}" 

370 

371 

372def _describe(predicate: Expr) -> str: 

373 """A predicate over a related model, written in Solr syntax for notes (its repr if that fails).""" 

374 try: 

375 return solr.compile(predicate) 

376 except (QueryError, TypeError): 

377 return repr(predicate) 

378 

379 

380def _local_rows(model: type[Model], query: Query[Any]) -> list[Any]: 

381 """Run ``query`` with its model's backend, refusing any request (planning is pure).""" 

382 rows: list[Any] = [] 

383 run = model._backend.run(query) 

384 try: 

385 for item in run: 

386 if not isinstance(item, list): 

387 raise UnsupportedQueryError( 

388 f"{model.__name__} conditions inside a document query must be answerable " 

389 f"without requests to ADS" 

390 ) 

391 rows.extend(item) 

392 finally: 

393 run.close() 

394 return rows 

395 

396 

397def _library_ids(resolved: _Resolved) -> list[str]: 

398 """Ids of the libraries whose bibcodes must be fetched before planning (in order, distinct).""" 

399 if _strategy() != "bibcodes": 

400 return [] 

401 nodes = walk(simplify(resolved.expr)) 

402 return list(dict.fromkeys(node.library_id for node in nodes if isinstance(node, InLibrary))) 

403 

404 

405def _finish(query: Query[Any], resolved: _Resolved, library_bibcodes: Mapping[str, Sequence[str]]) -> SearchPlan: 

406 """Passes 3 to 7: libraries, simplification, collection, large bibcode sets, compilation, fields.""" 

407 model = query.model 

408 bibcode_field = model._fields["bibcode"] 

409 notes = list(resolved.notes) 

410 # Simplified first, so that libraries in branches that cannot match are 

411 # neither needed nor fetched (the backend collects ids the same way). 

412 expr = simplify(resolved.expr) 

413 from_libraries: set[Expr] = set() 

414 

415 if _strategy() == "bibcodes": 

416 for library_id in _library_ids(resolved): 

417 if library_id not in library_bibcodes: 

418 raise ValueError( 

419 f"plan() needs the bibcodes of library {library_id!r} " 

420 f"(library_membership='bibcodes'): pass library_bibcodes={{id: bibcodes}}" 

421 ) 

422 count = len(library_bibcodes[library_id]) 

423 notes.append(f"library {library_id}: {count} bibcode(s), fetched from ADS") 

424 

425 def replace(node: Expr) -> Expr: 

426 if not isinstance(node, InLibrary): 

427 return node 

428 members = In(bibcode_field, tuple(library_bibcodes[node.library_id])) 

429 from_libraries.add(members) 

430 return members 

431 

432 expr = simplify(transform(expr, replace)) 

433 elif any(isinstance(node, InLibrary) for node in walk(expr)): 

434 notes.append("library membership is tested by ADS with docs(library/<id>)") 

435 expr, refinements, read = _per_record(expr, model, notes) 

436 fl, fl_note = _field_list(query) 

437 sort, sort_note = _sort(query) 

438 notes.append(fl_note) 

439 added = [name for name in read if model._fields[name].solr_name not in fl] 

440 if added: 

441 fl = tuple(f.solr_name for name, f in model._fields.items() if f.solr_name in fl or name in added) 

442 notes.append(f"also fetching {', '.join(added)} for the client-side check") 

443 notes.append(sort_note) 

444 if expr == NOTHING: 

445 notes.append("the filter can never match, so no request is made") 

446 return SearchPlan(solr.compile(NOTHING), fl, sort, empty=True, notes=tuple(notes)) 

447 scope, scope_note = _collection_scope(expr, model) 

448 if scope_note is not None: 

449 notes.append(scope_note) 

450 

451 limit = _config.config.max_inline_bibcodes 

452 conjuncts = expr.operands if isinstance(expr, And) else (expr,) 

453 positive: list[tuple[Any, ...]] = [] 

454 negative: list[tuple[Any, ...]] = [] 

455 rest: list[Expr] = [] 

456 for conjunct in conjuncts: 

457 large = _large_set(conjunct, bibcode_field, limit) 

458 negated = _large_set(conjunct.operand, bibcode_field, limit) if isinstance(conjunct, Not) else None 

459 if large is not None: 

460 positive.append(large.values) 

461 elif negated is not None: 

462 negative.append(negated.values) 

463 else: 

464 rest.append(conjunct) 

465 for conjunct in rest: 

466 for node in walk(conjunct): 

467 large = _large_set(node, bibcode_field, limit) 

468 if large is not None: 

469 raise UnsupportedQueryError(_large_set_message(large, limit, large in from_libraries)) 

470 

471 bigquery: tuple[str, ...] | None = None 

472 exclude: frozenset[str] | None = None 

473 if positive: 

474 kept = dict.fromkeys(positive[0]) 

475 for other in positive[1:]: 

476 members = set(other) 

477 kept = {bibcode: None for bibcode in kept if bibcode in members} 

478 dropped = set().union(*negative) 

479 bigquery = tuple(bibcode for bibcode in kept if bibcode not in dropped) 

480 sets = f"the intersection of {len(positive)} bibcode sets" if len(positive) > 1 else "a bibcode set" 

481 notes.append( 

482 f"{sets} larger than max_inline_bibcodes={limit}: searching /search/bigquery " 

483 f"with {len(bigquery)} bibcode(s)" 

484 + (" (excluded bibcodes removed from the upload)" if negative else "") 

485 ) 

486 if not bigquery: 

487 notes.append("no bibcode is left to search, so no request is made") 

488 return SearchPlan(solr.compile(NOTHING), fl, sort, empty=True, notes=tuple(notes)) 

489 elif negative: 

490 exclude = frozenset().union(*negative) 

491 notes.append( 

492 f"excluding {len(exclude)} bibcode(s) (a negated set larger than max_inline_bibcodes={limit}) " 

493 f"while streaming; offset and limit are then applied locally" 

494 ) 

495 

496 remaining = rest[0] if len(rest) == 1 else And(tuple(rest)) if rest else EVERYTHING 

497 if remaining == EVERYTHING and bigquery is None and (exclude is not None or refinements): 

498 raise UnsupportedQueryError(_whole_index_message(exclude, refinements)) 

499 if scope is not None: 

500 remaining = simplify(And((remaining, scope))) 

501 refinement = refinements[0] if len(refinements) == 1 else And(refinements) if refinements else None 

502 return SearchPlan( 

503 q=solr.compile(remaining), 

504 fl=fl, 

505 sort=sort, 

506 bigquery_bibcodes=bigquery, 

507 exclude_bibcodes=exclude, 

508 notes=tuple(notes), 

509 refinement=refinement, 

510 refinement_fl=tuple(f.solr_name for name, f in model._fields.items() if name in read), 

511 ) 

512 

513 

514def _whole_index_message(exclude: frozenset[str] | None, refinements: tuple[Expr, ...]) -> str: 

515 """Why a plan that filters every document of the index locally is refused, and what to add.""" 

516 checks = [f"excluding {len(exclude)} bibcode(s)"] if exclude is not None else [] 

517 for refinement in refinements: 

518 negated = isinstance(refinement, Not) 

519 node = refinement.operand if isinstance(refinement, Not) else refinement 

520 if isinstance(node, Quantified): 520 ↛ 517line 520 didn't jump to line 517 because the condition on line 520 was always true

521 checks.append(("~" if negated else "") + _label(node)) 

522 return ( 

523 f"This query would download every document in SciX: {' and '.join(checks)} is done " 

524 f"client-side on each returned document, and nothing else narrows the search ADS runs " 

525 f"(its query would be *:*, apart from the default collection). Add a condition ADS can " 

526 f"search, AND-ed with the rest, for example a year range (Document.year.between(2015, 2020)), " 

527 f"an author (Document.author == \"Last, F\") or a journal (Document.journal == \"ApJ\")." 

528 ) 

529 

530 

531# Per-record conditions. 

532 

533 

534@dataclass(frozen=True) 

535class _Server: 

536 """What ADS is sent for (part of) a per-record condition. 

537 

538 ``expr`` is a condition on the owner's fields; it decides the condition 

539 exactly if ``exact``, else it is only necessary and ``reason`` says why. 

540 """ 

541 

542 expr: Expr 

543 exact: bool 

544 reason: str = "" 

545 

546 

547def _per_record(expr: Expr, model: type[Model], notes: list[str]) -> tuple[Expr, tuple[Expr, ...], tuple[str, ...]]: 

548 """Pass 4b: translate per-record conditions (:class:`~scixplorer.expr.Quantified`) for ADS. 

549 

550 Returns the filter to send, the refinements (top-level conditions to check 

551 client-side on each returned document) and the owner fields they read. 

552 

553 Each condition is translated with :func:`_translate`. One translated 

554 exactly is replaced in place, anywhere in the filter. Any other must be a 

555 top-level ``&`` condition, optionally negated: its necessary condition (or 

556 nothing, when negated) stays in the filter and the condition itself 

557 becomes a refinement; elsewhere it raises ``UnsupportedQueryError``. 

558 ``expr`` is simplified (so ``~~c`` and nested groups are already flat); 

559 the result is simplified again. 

560 """ 

561 if not any(isinstance(node, Quantified) for node in walk(expr)): 

562 return expr, (), () 

563 kept: list[Expr] = [] 

564 refinements: list[Expr] = [] 

565 read: dict[str, None] = {} 

566 for conjunct in expr.operands if isinstance(expr, And) else (expr,): 

567 negated = isinstance(conjunct, Not) and isinstance(conjunct.operand, Quantified) 

568 node = conjunct.operand if isinstance(conjunct, Not) else conjunct 

569 if not isinstance(node, Quantified): 

570 kept.append(transform(conjunct, lambda n: _replace_exact(n, model, notes))) 

571 continue 

572 server = _translate(node, model, notes) 

573 label = _label(node) 

574 if server.exact: 

575 kept.append(~server.expr if negated else server.expr) 

576 notes.append(f"{label}: expressed exactly in the query as {solr.compile(server.expr)}") 

577 continue 

578 try: 

579 evaluate.predicate(conjunct) 

580 except NotLocallyEvaluable as exc: 

581 raise NotLocallyEvaluable( 

582 f"{label} needs a client-side check ({server.reason}), but cannot be evaluated in Python: {exc}" 

583 ) from exc 

584 collection = node.collection 

585 fields = collection.owner_fields(collection.fields_read(node.predicate)) 

586 read.update(dict.fromkeys(fields)) 

587 refinements.append(conjunct) 

588 if negated: 

589 sent = "nothing is sent to ADS for it (it is negated)" 

590 else: 

591 kept.append(server.expr) 

592 sent = f"ADS is sent the necessary condition {solr.compile(server.expr)}" 

593 notes.append( 

594 f"{'~' if negated else ''}{label}: checked client-side on each returned document " 

595 f"({server.reason}), reading {', '.join(fields)}; {sent}. Values are compared in Python: " 

596 f"names with the documented initial/full-name rule and text by its words, without the " 

597 f"curated synonyms known only to ADS. Offset and limit are then applied locally" 

598 ) 

599 return simplify(And(tuple(kept))), tuple(refinements), tuple(read) 

600 

601 

602def _replace_exact(node: Expr, model: type[Model], notes: list[str]) -> Expr: 

603 """A per-record condition below the top level: its exact translation, or ``UnsupportedQueryError``.""" 

604 if not isinstance(node, Quantified): 

605 return node 

606 server = _translate(node, model, notes) 

607 label = _label(node) 

608 if not server.exact: 

609 raise UnsupportedQueryError( 

610 f"{label} needs a client-side check ({server.reason}), so it must be a top-level & condition " 

611 f"of the query, optionally negated with ~, e.g. .where({label} & (...)); here it is inside " 

612 f"an |, a nested ~ or an operator. Restructure the query so that it is a top-level & " 

613 f"condition, or make it exact: a single condition on {node.collection.record_model.__name__} " 

614 f"fields, several joined with |, or conditions on one position ({node.collection.label()}[0].any(...))." 

615 ) 

616 notes.append(f"{label}: expressed exactly in the query as {solr.compile(server.expr)}") 

617 return server.expr 

618 

619 

620def _label(node: Quantified) -> str: 

621 return f"{node.collection.label(node.positions)}.{node.quantifier}(...)" 

622 

623 

624def _translate(node: Quantified, model: type[Model], notes: list[str]) -> _Server: 

625 """The condition on ``model``'s fields that ADS is sent for ``node``, and whether it is exact. 

626 

627 Leaves on record fields are moved to the owner field each is searched 

628 through (the collection's sources); a relation of the record model resolves 

629 to its keys as a document relation does. With positions, a leaf on a field in 

630 :data:`POSITIONAL_FIELDS` is wrapped in ``pos()``, any other is sent without 

631 it (not exact). ``|`` is exact if every part is; ``&`` only if one record is 

632 selected and every part is exact (otherwise different records could 

633 satisfy different parts); ``~`` and record fields ADS cannot search send 

634 nothing; ``all(...)`` is never exact. A condition that can never match is 

635 ``NOTHING``, exactly. 

636 """ 

637 collection = node.collection 

638 if not issubclass(model, collection.owner): 638 ↛ 639line 638 didn't jump to line 639 because the condition on line 638 was never true

639 raise QueryError(f"{_label(node)} is a condition on {collection.owner.__name__}, not on {model.__name__}") 

640 server = _server(node.predicate, node, model, notes) 

641 record = collection.record_model.__name__.lower() 

642 if node.quantifier == "all" and server.exact: 

643 server = _Server(server.expr, False, f"all(...) needs every {record} checked") 

644 expr = simplify(server.expr) 

645 if expr == NOTHING: 

646 return _Server(NOTHING, True) 

647 return _Server(expr, server.exact, server.reason) 

648 

649 

650def _server(predicate: Expr, node: Quantified, model: type[Model], notes: list[str]) -> _Server: 

651 """Translate one part of ``node``'s predicate (see :func:`_translate`).""" 

652 collection, positions = node.collection, node.positions 

653 record = collection.record_model 

654 if isinstance(predicate, Constant): 

655 where = "" if positions is None else " at those positions" 

656 return _Server(predicate, predicate == NOTHING, f"whether there is any {record.__name__.lower()}{where}") 

657 if isinstance(predicate, (Or, And)): 

658 parts = [_server(operand, node, model, notes) for operand in predicate.operands] 

659 reasons = [part.reason for part in parts if not part.exact] 

660 if isinstance(predicate, Or): 

661 return _Server(Or(tuple(p.expr for p in parts)), not reasons, reasons[0] if reasons else "") 

662 single = positions is not None and positions[0] == positions[1] 

663 if not single: 

664 reasons.insert(0, f"conditions joined with & may be met by different {record.__name__.lower()}s") 

665 return _Server(And(tuple(p.expr for p in parts)), not reasons, reasons[0] if reasons else "") 

666 if isinstance(predicate, Not): 

667 return _Server(EVERYTHING, False, "a ~ inside it") 

668 if isinstance(predicate, Related): 

669 relation = predicate.relation 

670 source = collection.sources.get(relation.key) 

671 if source is None or source.search is None: 671 ↛ 672line 671 didn't jump to line 672 because the condition on line 671 was never true

672 return _Server(EVERYTHING, False, f"{record.__name__}.{relation.name} cannot be searched by ADS") 

673 label = f"{_label(node)}: {record.__name__}.{relation.name}" 

674 condition = _keys_condition(relation, predicate.predicate, model._fields[source.search], label, notes) 

675 if condition == NOTHING: 

676 return _Server(NOTHING, True) 

677 return _position(simplify(condition), source.search, positions) 

678 if isinstance(predicate, (Match, In, Like, Range)): 678 ↛ 687line 678 didn't jump to line 687 because the condition on line 678 was always true

679 field = predicate.field 

680 source = collection.sources.get(field.name) 

681 if source is None or source.search is None: 

682 return _Server(EVERYTHING, False, f"{record.__name__}.{field.name} cannot be searched by ADS") 

683 leaf: Expr = replace(predicate, field=model._fields[source.search]) 

684 if isinstance(leaf, (Match, In)) and field.match_kind not in solr.EXPANDED_MATCH_KINDS: 

685 leaf = replace(leaf, exact=False) 

686 return _position(simplify(leaf), source.search, positions) 

687 raise QueryError(f"{_label(node)} cannot contain {predicate!r}") 

688 

689 

690def _position(leaf: Expr, field_name: str, positions: tuple[int, int] | None) -> _Server: 

691 """``leaf`` restricted to ``positions``: in ``pos()`` if ADS searches the field by position.""" 

692 if positions is None: 

693 return _Server(leaf, True) 

694 if field_name in POSITIONAL_FIELDS: 

695 return _Server(Func("pos", (leaf, *positions)), True) 

696 return _Server(leaf, False, f"{field_name} is not searched by position (search.POSITIONAL_FIELDS)") 

697 

698 

699def _collection_scope(expr: Expr, model: type[Model]) -> tuple[Expr | None, str | None]: 

700 """Pass 5: the condition limiting ``expr`` to the default collection, and a note. 

701 

702 ``(None, None)`` when no collection is configured. ``(None, note)`` when 

703 the search is exempt: it names the collection itself (a condition on 

704 ``database`` or ``collection`` anywhere, or raw Solr text containing 

705 ``database:`` or ``collection:``), or it names specific documents (a 

706 top-level ``&`` condition that is a positive ``==``/``in_`` on an 

707 identifying field, or a library). ``expr`` is the simplified filter. 

708 """ 

709 names = _config.config.resolve_collections() 

710 database = model._fields.get("database") 

711 if not names or database is None: 

712 return None, None 

713 setting = names[0] if len(names) == 1 else list(names) 

714 skipped = f"collection {setting!r} (scixplorer.config.collection) not applied" 

715 for node in walk(expr): 

716 if isinstance(node, (Match, In, Like, Range)) and _is_field(model, node.field, _COLLECTION_FIELDS): 

717 return None, f"{skipped}: the filter names a collection itself ({node.field.name})" 

718 if isinstance(node, Raw) and any(text in node.query.lower() for text in _COLLECTION_TEXT): 

719 return None, f"{skipped}: the raw query names a collection itself" 

720 naming = (*_identifiers(model), *_ALSO_NAMING) 

721 for conjunct in expr.operands if isinstance(expr, And) else (expr,): 

722 if isinstance(conjunct, InLibrary): 

723 return None, f"{skipped}: the filter asks for the documents of library {conjunct.library_id}" 

724 if isinstance(conjunct, (Match, In)) and _is_field(model, conjunct.field, naming): 

725 return None, f"{skipped}: the filter names specific documents by {conjunct.field.name}" 

726 scope = Match(database, names[0]) if len(names) == 1 else In(database, names) 

727 return scope, f"limited to collection {setting!r} (scixplorer.config.collection): {solr.compile(scope)} is added" 

728 

729 

730def _is_field(model: type[Model], field: Field[Any, Any], names: Sequence[str]) -> bool: 

731 """Whether ``field`` is the field of ``model`` with one of ``names``.""" 

732 return any(model._fields.get(name) is field for name in names) 

733 

734 

735def _large_set(expr: Expr, bibcode_field: Field[Any, Any], limit: int) -> In | None: 

736 """``expr`` if it is a bibcode set larger than ``limit``, else ``None``.""" 

737 if isinstance(expr, In) and expr.field is bibcode_field and len(expr.values) > limit: 

738 return expr 

739 return None 

740 

741 

742def _large_set_message(node: In, limit: int, from_library: bool) -> str: 

743 message = ( 

744 f"A set of {len(node.values)} bibcodes (more than max_inline_bibcodes={limit}) can only be searched " 

745 f"as a condition AND-ed with the rest of the query at the top level: " 

746 f"Document.bibcode.in_(...) & (...) is sent to /search/bigquery, and " 

747 f"~Document.bibcode.in_(...) & (...) excludes the set while streaming. Here it is " 

748 f"inside an |, a nested ~ or an operator. Either restructure the query so that the set " 

749 f"is a top-level & condition, or put the papers in an ADS library and use " 

750 f"Document.in_(library), which ADS evaluates itself." 

751 ) 

752 if from_library: 

753 message += ( 

754 " This set comes from a library because scixplorer.config.library_membership is " 

755 "'bibcodes'; with 'docs' (the default) ADS tests library membership directly." 

756 ) 

757 return message 

758 

759 

760def _field_list(query: Query[Any]) -> tuple[tuple[str, ...], str]: 

761 """Pass 7: the Solr names to fetch, in definition order, and a note describing them.""" 

762 model = query.model 

763 deferred: frozenset[str] = getattr(model, "_deferred", frozenset()) 

764 if query.fields: 

765 for field in query.fields: 

766 if not field.stored: 

767 raise QueryError( 

768 f"{model.__name__}.{field.name} is search-only: ADS can search it but not return it" 

769 ) 

770 wanted = {field.name for field in query.fields} | set(_identifiers(model)) 

771 note = f"fetching {len(wanted)} selected field(s); others load on first access" 

772 else: 

773 wanted = {name for name, field in model._fields.items() if field.stored and name not in deferred} 

774 note = ( 

775 f"fetching all {len(wanted)} stored fields except the deferred ones " 

776 f"({', '.join(sorted(deferred))}), which load on first access" 

777 ) 

778 fl = tuple(field.solr_name for name, field in model._fields.items() if name in wanted) 

779 return fl, note 

780 

781 

782def _identifiers(model: type[Model]) -> tuple[str, ...]: 

783 """The fields that identify a document, always fetched (``Document._identifiers``, else the model's key).""" 

784 identifiers: tuple[str, ...] | None = getattr(model, "_identifiers", None) 

785 return (model._key,) if identifiers is None else identifiers 

786 

787 

788def _sort(query: Query[Any]) -> tuple[str, str]: 

789 """Pass 6: the ``sort`` parameter, always ending in a unique key so paging is stable.""" 

790 model = query.model 

791 for order in query.order: 

792 field = order.field 

793 if isinstance(field, VirtualField): 

794 kind = "search-only" 

795 elif field.multivalued: 

796 kind = "multivalued" 

797 elif not field.indexed: 

798 kind = "not indexed: it can be returned but not searched or sorted by" 

799 else: 

800 continue 

801 raise QueryError(f"Cannot sort by {model.__name__}.{field.name}: it is {kind}") 

802 tiebreaker = solr.compile_order((Order(model._fields["id"]),)) 

803 given = solr.compile_order(query.order) 

804 if given is None: 

805 return ( 

806 f"score desc,{tiebreaker}", 

807 f"no order given: sorted by relevance (score desc), then {tiebreaker} so pages are stable", 

808 ) 

809 if any(order.field.name in _UNIQUE for order in query.order): 

810 return given, f"sorted by {given}" 

811 return f"{given},{tiebreaker}", f"sorted by {given}, then {tiebreaker} so pages are stable" 

812 

813 

814# Execution. 

815 

816 

817def _read_page(request: Request, response: Response | None) -> tuple[list[dict[str, Any]], int]: 

818 """The documents and ``numFound`` of a search response; ``APIError`` if it has another shape.""" 

819 data = None if response is None else response.data 

820 body = data.get("response") if isinstance(data, dict) else None 

821 docs = body.get("docs") if isinstance(body, dict) else None 

822 found = body.get("numFound") if isinstance(body, dict) else None 

823 if ( 

824 not isinstance(docs, list) 

825 or not all(isinstance(doc, dict) for doc in docs) 

826 or isinstance(found, bool) 

827 or not isinstance(found, int) 

828 ): 

829 detail = "" 

830 if isinstance(data, dict) and data.get("error"): 

831 detail = f": {data['error']!r}" 

832 raise APIError( 

833 f"{request.method} {request.path}: unexpected response from ADS (expected " 

834 f"response.docs as a list of objects and response.numFound as an int){detail}", 

835 status_code=None if response is None else response.status_code, 

836 response=response, 

837 ) 

838 return docs, found 

839 

840 

841def _fetch_libraries(resolved: _Resolved) -> Generator[Request, Response, dict[str, list[str]]]: 

842 """Yield the requests for the bibcodes of every library the plan needs, and return them.""" 

843 found: dict[str, list[str]] = {} 

844 for library_id in _library_ids(resolved): 

845 found[library_id] = yield from fetch_bibcodes(library_id) 

846 return found 

847 

848 

849class SearchBackend: 

850 """Runs document queries on the ADS search API (``/search/query`` and ``/search/bigquery``). 

851 

852 Pages are requested one at a time as results are consumed, with 

853 ``rows = min(config.page_size, remaining)`` (at most 2000). Each document 

854 remembers its page so that unfetched fields load for the whole page at once. 

855 """ 

856 

857 def __repr__(self) -> str: 

858 return "<SearchBackend>" 

859 

860 def _plan(self, query: Query[Any]) -> Generator[Request, Response, SearchPlan]: 

861 resolved = _resolve(query) 

862 library_bibcodes = yield from _fetch_libraries(resolved) 

863 return _finish(query, resolved, library_bibcodes) 

864 

865 def run(self, query: Query[Any]) -> Generator[Request | list[Any], Response | None, None]: 

866 """Yield the search requests, and each page of documents as soon as it arrives.""" 

867 search = yield from self._plan(query) 

868 if search.empty: 

869 return 

870 page_size = _page_size() 

871 model = query.model 

872 requested = [name for name, field in model._fields.items() if field.solr_name in search.fl] 

873 local = _LocalFilter.of(search, model) 

874 remaining = query.limit_ 

875 start, skip = (query.offset_, 0) if local is None else (0, query.offset_) 

876 while remaining is None or remaining > 0: 

877 rows = page_size if remaining is None or local is not None else min(page_size, remaining) 

878 request = search.request(start, rows) 

879 response = yield request 

880 docs, found = _read_page(request, response) 

881 start += len(docs) 

882 candidates = ((doc, None) for doc in docs) if local is None else local.survivors(docs, requested) 

883 kept: list[Model] = [] 

884 for doc, document in candidates: 

885 if skip: 

886 skip -= 1 

887 continue 

888 if remaining is not None: 

889 if remaining == 0: 

890 break 

891 remaining -= 1 

892 kept.append(_document(model, doc, requested) if document is None else document) 

893 if kept: 

894 page = ResultPage(query.client) 

895 for document in kept: 

896 page.attach(document) 

897 yield kept 

898 if not docs or start >= found: 

899 return 

900 

901 def count(self, query: Query[Any]) -> Generator[Request, Response, int]: 

902 """Return the number of matching documents, ignoring offset and limit. 

903 

904 One request with ``rows=0``, unless results are filtered locally 

905 (excluded bibcodes, or a refinement): then every matching document is 

906 fetched, with only the fields the filtering reads, and the survivors counted. 

907 """ 

908 search = yield from self._plan(query) 

909 if search.empty: 909 ↛ 910line 909 didn't jump to line 910 because the condition on line 909 was never true

910 return 0 

911 model = query.model 

912 bibcode_name = model._fields["bibcode"].solr_name 

913 local = _LocalFilter.of(search, model) 

914 if local is None: 

915 request = search.request(0, 0, fl=(bibcode_name,)) 

916 response = yield request 

917 return _read_page(request, response)[1] 

918 page_size = _page_size() 

919 fl = (bibcode_name, *search.refinement_fl) 

920 requested = [name for name, field in model._fields.items() if field.solr_name in fl] 

921 total = start = 0 

922 while True: 

923 request = search.request(start, page_size, fl=fl) 

924 response = yield request 

925 docs, found = _read_page(request, response) 

926 total += sum(1 for _ in local.survivors(docs, requested)) 

927 start += len(docs) 

928 if not docs or start >= found: 

929 return total 

930 

931 def explain(self, query: Query[Any]) -> Explanation: 

932 """Describe the first request(s) and the planner's decisions, without any I/O.""" 

933 resolved = _resolve(query) 

934 ids = _library_ids(resolved) 

935 if ids: 

936 requests = tuple(_first_request(fetch_bibcodes(library_id)) for library_id in ids) 

937 noun = "library" if len(ids) == 1 else "libraries" 

938 return Explanation( 

939 f"Fetches the bibcodes of {len(ids)} {noun} first (library_membership='bibcodes'); " 

940 f"the search request follows once they are known.", 

941 requests, 

942 (*resolved.notes, "the search endpoint depends on how many bibcodes the libraries hold"), 

943 ) 

944 search = _finish(query, resolved, {}) 

945 if search.empty: 

946 return Explanation("No request is made: the filter can never match.", (), search.notes) 

947 if query.limit_ == 0: 

948 return Explanation("No request is made: the limit is 0.", (), search.notes) 

949 page_size = _page_size() 

950 if not search.filters_locally: 

951 start = query.offset_ 

952 rows = page_size if query.limit_ is None else min(page_size, query.limit_) 

953 else: 

954 start, rows = 0, page_size 

955 request = search.request(start, rows) 

956 summary = f"Searches ADS with {request.method} {request.path}, up to {page_size} rows per request." 

957 if search.bigquery_bibcodes is not None: 

958 summary += f" Uploads {len(search.bigquery_bibcodes)} bibcodes." 

959 return Explanation(summary, (request,), search.notes) 

960 

961 

962def _first_request(gen: Generator[Request, Response, Any]) -> Request: 

963 """The first request a protocol generator would yield, without running the rest.""" 

964 try: 

965 return next(gen) 

966 finally: 

967 gen.close() 

968 

969 

970def _document(model: type[Model], row: Mapping[str, Any], requested: list[str]) -> Model: 

971 """A document from one result row. 

972 

973 Fields that were requested but are absent from the row (ADS omits empty 

974 values) are set to ``None``, so reading them does not load them again. 

975 """ 

976 document = model._from_row(row) 

977 for name in requested: 

978 document._data.setdefault(name, None) 

979 return document 

980 

981 

982class _LocalFilter: 

983 """What a plan drops while streaming: excluded bibcodes, and documents failing its refinement. 

984 

985 Running and counting share it, so both keep exactly the same rows. 

986 """ 

987 

988 def __init__(self, search: SearchPlan, model: type[Model]) -> None: 

989 self.model = model 

990 self.exclude = search.exclude_bibcodes 

991 self.bibcode_name = model._fields["bibcode"].solr_name 

992 self.test: Callable[[Any], bool] | None = ( 

993 None if search.refinement is None else evaluate.predicate(search.refinement) 

994 ) 

995 

996 @classmethod 

997 def of(cls, search: SearchPlan, model: type[Model]) -> _LocalFilter | None: 

998 """The filter for ``search``, or ``None`` if it filters nothing locally.""" 

999 return cls(search, model) if search.filters_locally else None 

1000 

1001 def survivors( 

1002 self, rows: list[dict[str, Any]], requested: list[str] 

1003 ) -> Iterator[tuple[dict[str, Any], Model | None]]: 

1004 """The rows that are kept, each with its document if one was built to test it.""" 

1005 for row in rows: 

1006 if self.exclude is not None and row.get(self.bibcode_name) in self.exclude: 

1007 continue 

1008 if self.test is None: 

1009 yield row, None 

1010 continue 

1011 document = _document(self.model, row, requested) 

1012 if self.test(document): 

1013 yield row, document