Coverage for src/scixplorer/models/document.py: 99%
285 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""Documents in ADS / SciX, searched with the ADS search API.
3Field definitions follow the search index's Solr schema (``schema.xml`` in the
4``adsabs/montysolr`` repository; ``scripts/schema_report.py`` compares the two)
5and the query parser's virtual fields (``abs``, ``full``, ``inst``, ...).
6"""
8from __future__ import annotations
10import warnings
11from collections.abc import Iterable
12from typing import Any, ClassVar, TypeAlias
14from ..exceptions import LazyLoadWarning, QueryError
15from ..expr import Expr, Func, In, InLibrary, Order, Raw
16from ..fields import (
17 DateField,
18 DateTimeField,
19 Field,
20 FieldExpr,
21 FloatField,
22 IntegerField,
23 NameField,
24 NumericStringField,
25 StringField,
26 TextField,
27 VirtualField,
28 advised,
29 outside_package_stacklevel,
30)
31from ..model import Model, Relation
32from ..search import ResultPage, SearchBackend
33from ..utils import _orcid_problem, parse_bibcode, to_bibcodes
34from .affiliation import Affiliation
35from .author import document_authors
36from .journal import Journal
37from .library import Library
38from .planetary import PlanetaryFeature
39from .uat import UATConcept
41__all__ = ["Document"]
43#: One entry of ``Document.affiliation``: per author, an affiliation, several, or none.
44AuthorAffiliation: TypeAlias = Affiliation | tuple[Affiliation, ...] | None
47def _journal_of(document: Document) -> Journal | None:
48 """The journal named by the bibcode's journal part, else by the first bibstem."""
49 bibcode = document.bibcode
50 if bibcode is not None:
51 try:
52 abbreviation = parse_bibcode(bibcode)["journal_abbreviation"]
53 except ValueError:
54 pass
55 else:
56 return Journal.lookup(abbreviation)
57 bibstems = document.bibstem
58 return Journal.lookup(bibstems[0]) if bibstems else None
61def _affiliations_of(document: Document) -> list[AuthorAffiliation] | None:
62 """One entry per author, parsed from ``aff_id``.
64 ``"-"`` (no affiliation) gives ``None``; ``"A1; A2"`` gives a tuple of the
65 affiliations; ids missing from the local affiliation data are skipped.
66 """
67 entries = document.aff_id
68 if entries is None:
69 return None
70 return [_author_affiliation(entry) for entry in entries]
73def _author_affiliation(entry: str) -> AuthorAffiliation:
74 ids = (part.strip() for part in entry.split(";"))
75 found = [Affiliation.lookup(i) for i in ids if i and i != "-"]
76 known = [affiliation for affiliation in found if affiliation is not None]
77 if not known:
78 return None
79 return known[0] if len(known) == 1 else tuple(known)
82def _uat_concepts_of(document: Document) -> list[UATConcept]:
83 """The UAT concepts named by ``uat_id``, in order; unknown ids are skipped.
85 Needs the thesaurus (``data.refresh("uat")``) only if there are ids.
86 """
87 found = (UATConcept.lookup(concept_id) for concept_id in document.uat_id or ())
88 return [concept for concept in found if concept is not None]
91def _planetary_features_of(document: Document) -> list[PlanetaryFeature]:
92 """The planetary features named by ``planetary_feature_id``, in order; unknown ids are skipped.
94 Needs the gazetteer (``data.refresh("planetary_features")``) only if there are ids.
95 """
96 found = (PlanetaryFeature.lookup(feature_id) for feature_id in document.planetary_feature_id or ())
97 return [feature for feature in found if feature is not None]
100def _operand(name: str, expr: Expr | str) -> Expr:
101 """The expression argument of an operator: an ``Expr``, or a ``str`` of raw Solr syntax."""
102 if isinstance(expr, Expr):
103 return expr
104 if isinstance(expr, str):
105 if not expr.strip():
106 raise QueryError(f"Document.{name}() needs a non-empty query")
107 return Raw(expr)
108 raise TypeError(f"Document.{name}() needs an expression or a Solr query string, not {expr!r}")
111def _operator(name: str, solr_name: str, doc: str) -> classmethod[Any, [Expr | str], Expr]:
112 """A classmethod building the one-argument Solr operator ``solr_name(expr)``."""
114 def operator(cls: Any, expr: Expr | str) -> Expr:
115 return Func(solr_name, (_operand(name, expr),))
117 operator.__name__ = name
118 operator.__qualname__ = f"Document.{name}"
119 operator.__doc__ = doc
120 return classmethod(operator)
123def _positive_int(name: str, value: Any) -> int:
124 if isinstance(value, bool) or not isinstance(value, int):
125 raise TypeError(f"{name} must be an int, not {value!r}")
126 if value < 1:
127 raise QueryError(f"{name} must be at least 1, not {value}")
128 return value
131class Document(Model):
132 """A document (paper, book, dataset, software, ...) in ADS / SciX.
134 Search with :meth:`select` and ``where``::
136 papers = (
137 Document
138 .select(Document.title)
139 .where((Document.author[0] == "Kewley, L") & Document.year.between(2015, 2020))
140 .order_by(Document.citation_count.desc())
141 .limit(10)
142 )
144 Fields hold the values ADS returned; ``None`` means ADS had no value.
145 Search-only fields (such as :attr:`full`) can be queried but not read.
147 Deferred fields (``_deferred``): ``ack``, ``body``, ``caption``,
148 ``citation``, ``credit``, ``mention`` and ``reference`` are not fetched by
149 a plain ``Document.select()``, because they are large (full text, or lists
150 of bibcodes that can run to tens of thousands) and rarely needed. They are
151 fetched when selected explicitly, or loaded on first access.
153 Identity: a document is identified by the first of its identifiers
154 (``_identifiers``: ``bibcode``, ``scix_id``, ``id``) that has a value. Two
155 documents are equal when that is the same field with the same value; a
156 document with no identifier is equal only to itself.
158 Lazy loading: reading a stored field that was not fetched sends one search
159 request that loads it for every document of the same result page that
160 lacks it, with a :class:`~scixplorer.exceptions.LazyLoadWarning`. Documents are
161 found by their identifier (in practice the bibcode; documents of the page
162 identified by another field are loaded with one more request per field).
163 The request is synchronous, even inside async code, so there select the
164 fields you need. The identifiers (always fetched) and ``score`` (only
165 meaningful for the query that produced the document) are never loaded
166 this way, and a document with no identifier loads nothing.
168 Relations: :attr:`journal` (from the bibcode), :attr:`affiliation` (from
169 ``aff_id``), :attr:`uat_concepts` (from ``uat_id``) and :attr:`planetary_features`
170 (from ``planetary_feature_id``) give :class:`~scixplorer.models.journal.Journal`,
171 :class:`~scixplorer.models.affiliation.Affiliation`,
172 :class:`~scixplorer.models.uat.UATConcept` and
173 :class:`~scixplorer.models.planetary.PlanetaryFeature` objects, and can be searched
174 by their fields (``Document.journal.title.contains("astro")``), as can those
175 models' fields directly (``Journal.title.contains("astro")``). The last two
176 need their data downloaded once (``scixplorer.data.refresh("uat")``,
177 ``scixplorer.data.refresh("planetary_features")``), except to match ids directly
178 (``Document.uat_concepts == 498``). Each such condition is about any related
179 object; ``.any(...)`` makes several about the same one:
180 ``Document.planetary_features.any((PlanetaryFeature.target == "Titan") & (PlanetaryFeature.feature_type == "Mare"))``.
182 Per-author conditions: ``doc.authors`` is one
183 :class:`~scixplorer.models.author.Author` per author (``.name``, ``.aff``,
184 ``.affiliation``, ``.email``, ``.orcid``, ...), built from the per-author
185 arrays ``author``, ``aff``, ``aff_id``, ``email`` and the ORCID fields.
186 In a search, everything inside one ``Document.authors.any(...)`` (or
187 ``.all(...)``, every author) is about the same author, and an index picks
188 a position::
190 Document.authors.any((Author.name == "Kewley, L") & (Author.affiliation.country == "Australia"))
191 Document.authors[0].orcid == "0000-0002-1825-0097"
193 A single condition means the same as its shorthand:
194 ``Document.authors[0].name == x`` is ``Document.author[0] == x``, and
195 ``Document.authors.any(Author.affiliation.country == x)`` is
196 ``Document.affiliation.country == x``. A condition Solr cannot express
197 exactly (several about one author at any position, or ``all``) is sent as
198 a necessary condition and checked on each returned document.
199 """
201 #: The fields that can identify a document, in order of preference. Every
202 #: search fetches them all, and identity, lazy loading and ``repr`` use the
203 #: first one that has a value.
204 _identifiers: ClassVar[tuple[str, ...]] = ("bibcode", "scix_id", "id")
205 _backend = SearchBackend()
206 _deferred: ClassVar[frozenset[str]] = frozenset(
207 {"ack", "body", "caption", "citation", "credit", "mention", "reference"}
208 )
209 #: Fields never loaded on access: identifiers are always fetched, and a
210 #: score belongs to the query that produced the document.
211 _not_lazy: ClassVar[frozenset[str]] = frozenset({*_identifiers, "score"})
213 abs = VirtualField("Search for a word or phrase in abstract, title, and keywords.")
214 abstract = TextField("The document abstract.")
215 ack = TextField("The acknowledgements extracted from the full text.")
216 aff = TextField("The raw, provided affiliation field: one string per author.", multivalued=True)
217 aff_abbrev = TextField("Abbreviations of the curated affiliations, one entry per author.", multivalued=True)
218 aff_canonical = TextField("Canonical names of the curated affiliations, one entry per author.", multivalued=True)
219 aff_id = StringField(
220 "Curated affiliation identifiers, parsed from the given affiliation string, one entry per "
221 "author ('-' for none; 'A1; A2' for several). See https://ui.adsabs.harvard.edu/blog/affils-update.",
222 multivalued=True,
223 )
224 affil = VirtualField(
225 "Search all affiliation fields at once: raw strings, canonical names, abbreviations and identifiers."
226 )
227 all = VirtualField("Search by author_norm, alternate_title, bibcode, doi, and identifier.")
228 alternate_bibcode = StringField("Alternate bibcodes of the record.", multivalued=True)
229 alternate_title = TextField(
230 "Alternate title, usually present when the original title is not in English.", multivalued=True
231 )
232 arxiv = VirtualField("Search by arXiv identifier (an alias of identifier).")
233 arxiv_class = TextField("The arXiv classes a document was submitted to.", multivalued=True)
234 author = NameField("Author names, 'Lastname, First M', in order.", multivalued=True)
235 author_count = IntegerField("The number of authors.")
236 author_norm = StringField("Author names in the form 'Lastname, F'.", multivalued=True)
237 bibcode = StringField(
238 "Document bibliographic code. See https://ui.adsabs.harvard.edu/help/actions/bibcode for more information."
239 )
240 bibgroup = StringField("Records by bibliographic groups, curated by staff outside of ADS.", multivalued=True)
241 bibstem = StringField("Abbreviated name(s) of the journal or publication (e.g., ApJ).", multivalued=True)
242 body = TextField("The full text, where ADS has it. Search it with body == '...'.")
243 book_author = NameField("Authors of the book containing the record (e.g. for a chapter).", multivalued=True)
244 caption = TextField("Figure and table captions extracted from the full text.", multivalued=True)
245 citation = StringField("Bibcodes of the documents citing this one.", multivalued=True)
246 citation_count = IntegerField("The number of citations to this document.")
247 citation_count_norm = FloatField("Normalised citation count: citations divided by the number of authors.")
248 cite_read_boost = FloatField("The normalized boost factor.")
249 classic_factor = IntegerField(
250 "A classic prestige score, designed to more highly rank papers that are relevant and popular now."
251 )
252 collection = VirtualField("Search by collection (an alias of database), e.g. 'astronomy'.")
253 comment = TextField("Comments on the record, e.g. from the publisher.", multivalued=True)
254 copyright = TextField("The copyright statement.")
255 credit = StringField("Bibcodes of the documents that mention (credit) this record.", multivalued=True)
256 credit_count = IntegerField("The number of documents that mention (credit) this record.")
257 data = StringField(
258 "Related data sources. For example: data == 'CDS' will return records that have CDS data.",
259 multivalued=True,
260 )
261 data_count = IntegerField("The number of related data sources.")
262 database = StringField(
263 "The database(s) the document resides in (e.g., astronomy or physics).", multivalued=True
264 )
265 date = DateTimeField(
266 "Publication date, represented by a time format and used for indexing. "
267 "For example: date == datetime(2015, 7, 1)."
268 )
269 doctype = StringField("Search documents by their type: article, thesis, et cetera.")
270 doi = StringField("Digital object identifier(s).", multivalued=True)
271 editor = NameField("Editors of the publication.", multivalued=True)
272 eid = StringField("Electronic identifier of the paper (equivalent of page number).")
273 email = TextField(
274 "Search by email addresses for the authors that included them in the article ('-' for none).",
275 multivalued=True,
276 )
277 entry_date = DateTimeField(
278 "Creation date of the ADS record. Note that this can be used like Document.entry_date >= days_ago(7)."
279 )
280 esources = StringField(
281 "Types of electronic sources available for a record (e.g., pub_html, eprint_pdf).", multivalued=True
282 )
283 facility = TextField(
284 "Facilities declared in a record, based on a controlled list by AAS journals.", multivalued=True
285 )
286 first_author = NameField("The first author's name, 'Lastname, First M'.")
287 first_author_norm = StringField("The first author's name in the form 'Lastname, F'.")
288 full = VirtualField("Search by title, abstract, body, keyword, and ack.")
289 gpn = TextField(
290 "Planetary features named in the record, from the Gazetteer of Planetary Nomenclature.",
291 multivalued=True,
292 )
293 gpn_id = IntegerField("Gazetteer of Planetary Nomenclature identifiers of those features.", multivalued=True)
294 grant = TextField("Search by grant identifiers and grant agencies.", multivalued=True)
295 grant_agencies = VirtualField(
296 "A field with just the grant agencies name (e.g., NASA). Not in the published index schema."
297 )
298 grant_id = VirtualField("Search by grant identifier. Not in the published index schema.")
299 has = StringField(
300 "The names of the fields this record has values for; e.g. has == 'body' finds records with full text.",
301 multivalued=True,
302 )
303 id = NumericStringField(
304 "A unique identifier for the document, curated by ADS: a string of digits. Queries also accept an "
305 "int, e.g. Document.id == 12312494."
306 )
307 identifier = StringField(
308 "Search by an array of alternative identifiers for a record. May contain alternative bibcodes, "
309 "DOIs, and/or arXiv identifiers.",
310 multivalued=True,
311 )
312 indexstamp = DateTimeField("Datetime when the document was last indexed by the ADS Solr service.")
313 inst = VirtualField(
314 "Find records that contain a curated (ADS-identified) affiliation or institution, including its "
315 "child institutions. See also: Document.affiliation."
316 )
317 institution = StringField(
318 "Curated institution abbreviations, one entry per author (searched by inst).", multivalued=True
319 )
320 isbn = StringField("International Standard Book Number(s).", multivalued=True)
321 issn = StringField("International Standard Serial Number(s).", multivalued=True)
322 issue = StringField("Issue number of the journal that includes the article.")
323 keyword = TextField(
324 "An array of normalized and non-normalized keyword values associated with the record.", multivalued=True
325 )
326 keyword_norm = TextField("Keywords normalised to a controlled vocabulary.", multivalued=True)
327 keyword_schema = TextField("The vocabulary each keyword in keyword comes from.", multivalued=True)
328 lang = StringField("The language of the main title. Search-only.", stored=False)
329 links_data = StringField(
330 "Information on what linked documents are available (JSON strings). Returned, but not searchable.",
331 multivalued=True,
332 indexed=False,
333 )
334 mention = StringField("Bibcodes of the records (e.g. software) this document mentions.", multivalued=True)
335 mention_count = IntegerField("The number of records (e.g. software) this document mentions.")
336 nedid = StringField("List of NED IDs for a record.", multivalued=True)
337 nedtype = StringField("Keywords used to describe the NED type (e.g., galaxy, star).", multivalued=True)
338 orcid = advised(VirtualField("ORCID identifier, from all possible sources."), _orcid_problem)
339 orcid_other = advised(
340 TextField("ORCID claims from users who used the ADS claiming interface.", multivalued=True), _orcid_problem
341 )
342 orcid_pub = advised(TextField("ORCIDs supplied by publishers.", multivalued=True), _orcid_problem)
343 orcid_user = advised(
344 TextField("ORCID claims from users who gave ADS consent to expose their public profile.", multivalued=True),
345 _orcid_problem,
346 )
347 page = StringField("Page number of a record.", multivalued=True)
348 page_count = IntegerField(
349 "If page_range is present, it gives the difference between the first and last page numbers in the range."
350 )
351 page_range = StringField("The page range of the record. Returned, but not searchable.", indexed=False)
352 planetary_feature_id = IntegerField(
353 "Gazetteer of Planetary Nomenclature feature ids of the planetary features in the record. "
354 "See also: Document.planetary_features.",
355 multivalued=True,
356 )
357 planetary_feature = TextField(
358 "Planetary features mentioned in the record, as text "
359 "(Document.planetary_features is the relation to PlanetaryFeature).",
360 multivalued=True,
361 )
362 property = StringField(
363 "An array of miscellaneous flags associated with a record. Examples include: refereed, "
364 "notrefereed, article, nonarticle, ads_openaccess, eprint_openaccess, pub_openaccess, "
365 "openaccess, ocrabstract.",
366 multivalued=True,
367 )
368 pub = StringField("The canonical name of the publication that the record appeared in.")
369 pub_abbrev = StringField("The abbreviated name of the publication.")
370 pub_raw = TextField("Name of the publisher, but also includes the volume, page, and issue if exists.")
371 pubdate = DateField("Publication date (to month-level granularity only).")
372 publisher = TextField("Name of the publisher.")
373 pubnote = TextField("Notes about the publication, e.g. 'Accepted for publication in ApJ'.", multivalued=True)
374 read_count = IntegerField("The number of times the record has been viewed within a 90 day window.")
375 reference = StringField("Bibcodes of the documents this one cites.", multivalued=True)
376 reference_count = IntegerField("The number of documents this one cites.")
377 score = FloatField(
378 "The closeness of the document to the query match (Solr's relevance score for the query "
379 "that returned it; not an index field)."
380 )
381 scix_id = StringField("The SciX identifier of the record.")
382 series = TextField("Name of the series, e.g. of a book or of conference proceedings.")
383 simbid = IntegerField(
384 "List of SIMBAD IDs within a document. This field has privacy restrictions.", multivalued=True
385 )
386 simbtype = TextField("Keywords used to describe the SIMBAD type.", multivalued=True)
387 thesis = TextField("Thesis information, such as the degree-granting institution.")
388 title = TextField("The title of the record (and any other titles it has).", multivalued=True)
389 uat_id = IntegerField(
390 "Unified Astronomy Thesaurus concept numbers of the record. See also: Document.uat_concepts.", multivalued=True
391 )
392 uat = StringField(
393 "Unified Astronomy Thesaurus (UAT) concepts assigned to the record, as text "
394 "(Document.uat_concepts is the relation to UATConcept).",
395 multivalued=True,
396 )
397 vizier = StringField("Keywords, 'subject' tags from Vizier.", multivalued=True)
398 volume = StringField("The journal volume.")
399 year = IntegerField("Year of publication.")
401 journal: Relation[Journal | None] = Relation(
402 Journal,
403 key="bibstem",
404 related_key="abbreviation",
405 resolve=_journal_of,
406 doc="The journal the document appeared in, from the journal part of its bibcode (None if unknown).",
407 )
408 affiliation: Relation[list[AuthorAffiliation] | None] = Relation(
409 Affiliation,
410 key="aff_id",
411 related_key="id",
412 resolve=_affiliations_of,
413 doc=(
414 "The curated affiliations, one entry per author: None, an Affiliation, or a tuple of them "
415 "(from aff_id; ids missing from the local affiliation data are skipped). Use scixplorer.utils.flatten() "
416 "to scan them."
417 ),
418 )
419 uat_concepts: Relation[list[UATConcept]] = Relation(
420 UATConcept,
421 key="uat_id",
422 related_key="id",
423 resolve=_uat_concepts_of,
424 doc=(
425 "The Unified Astronomy Thesaurus concepts of the document (from uat_id; unknown ids are "
426 "skipped, and a document without any gives an empty list). Needs data.refresh('uat') once."
427 ),
428 )
429 planetary_features: Relation[list[PlanetaryFeature]] = Relation(
430 PlanetaryFeature,
431 key="planetary_feature_id",
432 related_key="id",
433 resolve=_planetary_features_of,
434 doc=(
435 "The planetary features named in the document (from planetary_feature_id; unknown ids are "
436 "skipped, and a document without any gives an empty list). Needs "
437 "data.refresh('planetary_features') once."
438 ),
439 )
441 def __init__(self, **values: Any) -> None:
442 self._page: ResultPage | None = None
443 super().__init__(**values)
445 def __getstate__(self) -> dict[str, Any]:
446 state = dict(self.__dict__)
447 state["_page"] = None
448 return state
450 def _key_value(self) -> tuple[str, Any] | None:
451 """The first identifier with a value, as ``(field name, value)``; ``None`` if there is none.
453 ``Model`` compares and hashes instances by this.
454 """
455 for name in self._identifiers:
456 value = self._data.get(name)
457 if value is not None:
458 return name, value
459 return None
461 def __repr__(self) -> str:
462 identity = self._key_value()
463 if identity is None:
464 return "<Document>"
465 name, value = identity
466 return f"<Document: {name}={value!r}>"
468 def __str__(self) -> str:
469 identity = self._key_value()
470 return repr(self) if identity is None else str(identity[1])
472 # Second-order and other operators.
474 citations = _operator(
475 "citations",
476 "citations",
477 """Documents that cite the documents matching ``expr``.
479 ``Document.citations(Document.bibcode == "2003AJ....125..525J")`` finds the
480 documents citing that one; :meth:`references` finds those it cites. See
481 https://ui.adsabs.harvard.edu/help/search/citations-and-references.
483 :param expr: an expression, or a Solr query string.
484 """,
485 )
486 references = _operator(
487 "references",
488 "references",
489 """Documents cited by the documents matching ``expr``.
491 ``Document.references(Document.bibcode == "2003AJ....125..525J")`` finds the
492 documents that one cites; :meth:`citations` finds those citing it. See
493 https://ui.adsabs.harvard.edu/help/search/citations-and-references.
495 :param expr: an expression, or a Solr query string.
496 """,
497 )
498 trending = _operator(
499 "trending",
500 "trending",
501 """Documents most read by users who read recent papers matching ``expr``.
503 These are papers currently being read by people interested in the field. See
504 https://ui.adsabs.harvard.edu/help/search/second-order.
506 :param expr: an expression, or a Solr query string.
507 """,
508 )
509 useful = _operator(
510 "useful",
511 "useful",
512 """Documents frequently cited by the most relevant papers matching ``expr``.
514 These are usually studies that discuss methods and techniques useful to
515 conduct research in the field. See https://ui.adsabs.harvard.edu/help/search/second-order.
517 :param expr: an expression, or a Solr query string.
518 """,
519 )
520 reviews = _operator(
521 "reviews",
522 "reviews",
523 """Documents citing the most relevant papers matching ``expr``: the reviews of the field.
525 Takes the papers citing those matching ``expr``, and ranks them by how many
526 of them each cites. See https://ui.adsabs.harvard.edu/help/search/second-order.
528 :param expr: an expression, or a Solr query string.
529 """,
530 )
531 similar = _operator(
532 "similar",
533 "similar",
534 """Documents whose abstracts are similar in wording to those of the documents matching ``expr``.
536 See https://ui.adsabs.harvard.edu/help/search/second-order.
538 :param expr: an expression, or a Solr query string.
539 """,
540 )
541 citis = _operator(
542 "citis",
543 "citis",
544 """Like :meth:`citations`, using less memory but more slowly.
546 :param expr: an expression, or a Solr query string.
547 """,
548 )
549 classic_relevance = _operator(
550 "classic_relevance",
551 "classic_relevance",
552 """The documents matching ``expr``, ranked (almost) as ADS Classic's relevance score did.
554 :param expr: an expression, or a Solr query string.
555 """,
556 )
557 instructive = _operator(
558 "instructive",
559 "instructive",
560 """A synonym of :meth:`reviews`.
562 :param expr: an expression, or a Solr query string.
563 """,
564 )
565 join_citations = _operator(
566 "join_citations",
567 "joincitations",
568 """Like :meth:`citations`, using a Lucene block join (Solr ``joincitations()``).
570 :param expr: an expression, or a Solr query string.
571 """,
572 )
573 join_references = _operator(
574 "join_references",
575 "joinreferences",
576 """Like :meth:`references`, using a Lucene block join (Solr ``joinreferences()``).
578 :param expr: an expression, or a Solr query string.
579 """,
580 )
581 reviews2 = _operator(
582 "reviews2",
583 "reviews2",
584 """The original implementation of :meth:`reviews`.
586 :param expr: an expression, or a Solr query string.
587 """,
588 )
589 useful2 = _operator(
590 "useful2",
591 "useful2",
592 """The original implementation of :meth:`useful`.
594 :param expr: an expression, or a Solr query string.
595 """,
596 )
598 @classmethod
599 def top_n(cls, n: int, expr: Expr | str, order_by: Order | FieldExpr | None = None) -> Expr:
600 """The first ``n`` documents matching ``expr`` (Solr ``topn()``).
602 :param n: how many documents.
603 :param expr: an expression, or a Solr query string.
604 :param order_by: how to rank them before taking the first ``n``: an
605 :class:`~scixplorer.expr.Order` such as ``Document.citation_count.desc()``, or
606 a field handle (ascending). By default, by relevance.
607 """
608 args: list[Any] = [_positive_int("top_n() n", n), _operand("top_n", expr)]
609 if isinstance(order_by, Order):
610 args.append(Order(cls._field(order_by.field), order_by.descending))
611 elif isinstance(order_by, FieldExpr):
612 cls._field(order_by)
613 args.append(order_by.asc())
614 elif order_by is not None:
615 raise TypeError(f"top_n() order_by must be an Order or a field, not {order_by!r}")
616 return Func("topn", tuple(args))
618 @classmethod
619 def pos(cls, expr: Expr | str, start: int, end: int | None = None) -> Expr:
620 """Documents where ``expr`` matches at a position (1-indexed, inclusive) of a multivalued field.
622 For authors prefer indexing: ``Document.author[0] == "Kewley, L"`` (first
623 author) is ``pos(author == ..., 1)``, and ``Document.author[0:3]`` the first
624 three. ``pos`` is for expressions written as Solr strings.
626 :param expr: an expression, or a Solr query string.
627 :param start: the first position, counting from 1.
628 :param end: the last position (inclusive); ``None`` means ``start``.
629 """
630 first = _positive_int("pos() start", start)
631 last = first if end is None else _positive_int("pos() end", end)
632 if last < first:
633 raise QueryError(f"pos() end ({last}) is before start ({first})")
634 return Func("pos", (_operand("pos", expr), first, last))
636 @classmethod
637 def raw(cls, query: str) -> Expr:
638 """A condition written in Solr syntax, sent as is (combine it with ``&``, ``|``, ``~``)."""
639 if not isinstance(query, str):
640 raise TypeError(f"Document.raw() needs a str, not {query!r}")
641 if not query.strip():
642 raise QueryError("Document.raw() needs a non-empty query")
643 return Raw(query)
645 @classmethod
646 def in_(cls, source: Any) -> Expr:
647 """Documents in ``source``: a :class:`~scixplorer.models.library.Library`, or bibcodes.
649 A library is tested by ADS itself (``docs(library/<id>)``), without
650 fetching its bibcodes. Anything else may be bibcode strings, documents,
651 or iterables of them, and becomes ``Document.bibcode.in_(...)``.
652 """
653 if isinstance(source, Library):
654 library_id = source._data.get("id")
655 if not isinstance(library_id, str) or not library_id.strip():
656 raise QueryError(f"{source!r} has no id, so it is not on ADS; use Library.create()")
657 return InLibrary(library_id)
658 return In(cls._fields["bibcode"], tuple(to_bibcodes(source)))
660 @classmethod
661 def not_in(cls, source: Any) -> Expr:
662 """Documents not in ``source`` (see :meth:`in_`)."""
663 return ~cls.in_(source)
665 # Authors.
667 authors = document_authors()
669 # Lazy loading.
671 def _load_missing(self, field: Field[Any, Any]) -> Any:
672 """Load ``field`` for this document and the documents of its page that lack it.
674 Documents are found by their identifier, with one request per
675 identifier field in use (in practice only ``bibcode``).
676 """
677 if not field.stored:
678 raise AttributeError(f"Document.{field.name} is search-only and has no value on an instance")
679 self._load_fields((field,))
680 return self._data.get(field.name)
682 def _load_fields(self, fields: Iterable[Field[Any, Any]]) -> None:
683 """Load those of ``fields`` this document lacks, for it and the documents of its page lacking any of them.
685 One search request fetches them all (one per identifier field in use;
686 in practice only ``bibcode``), with one ``LazyLoadWarning`` naming them.
687 Search-only fields, identifiers and ``score`` are never loaded, and a
688 document with no identifier loads nothing.
689 """
690 order = list(self._fields)
691 missing = sorted(
692 (field for field in fields if field.stored and field.name not in self._data and field.name not in self._not_lazy),
693 key=lambda field: order.index(field.name),
694 )
695 if not missing or self._key_value() is None:
696 return
697 names = {field.name for field in missing}
698 page = self._page
699 candidates: list[Document] = [self]
700 if page is not None:
701 candidates += [
702 member
703 for member in page.members()
704 if isinstance(member, Document) and member is not self and not names <= member._data.keys()
705 ]
706 groups: dict[str, list[Document]] = {}
707 for document in candidates:
708 identity = document._key_value()
709 if identity is not None:
710 groups.setdefault(identity[0], []).append(document)
711 count = sum(len(group) for group in groups.values())
712 requests = "another search request" if len(groups) == 1 else f"{len(groups)} more search requests"
713 labels = ", ".join(f"Document.{field.name}" for field in missing)
714 verb, them = ("was", "it") if len(missing) == 1 else ("were", "them")
715 warnings.warn(
716 f"{labels} {verb} not fetched; loading {them} for {count} document(s) with "
717 f"{requests}. Select the fields you need, e.g. "
718 f"Document.select({labels}, ...), to avoid this.",
719 LazyLoadWarning,
720 stacklevel=outside_package_stacklevel(),
721 )
722 client = None if page is None else page.client
723 for name, group in groups.items():
724 identifier: FieldExpr = getattr(Document, name)
725 query = Document.select(*missing).where(identifier.in_([document._data[name] for document in group]))
726 loaded = {row._data.get(name): row for row in query.using(client)}
727 for document in group:
728 row = loaded.get(document._data[name])
729 for field in missing:
730 if field.name not in document._data: 730 ↛ 729line 730 didn't jump to line 729 because the condition on line 730 was always true
731 document._data[field.name] = None if row is None else row._data.get(field.name)
732 document._related.clear()