diff --git a/service/src/main/inse/models/openalex/work.py b/service/src/main/inse/models/openalex/work.py index 31934220..3ad6f785 100644 --- a/service/src/main/inse/models/openalex/work.py +++ b/service/src/main/inse/models/openalex/work.py @@ -94,7 +94,10 @@ class Work(BaseModel): content_url: StrictStr | None = Field(default=None, description="URL for downloading full-text content. Only present when `has_content.pdf` or `has_content.grobid_xml` is true.") created_date: date | None = Field(default=None, description="When this work was added to OpenAlex (ISO 8601 date).") updated_date: datetime | None = Field(default=None, description="When this work was last updated (ISO 8601 datetime).") - __properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date"] + snippet: StrictStr | None = Field(default=None, description="Passage of the title or abstract containing the searched keyword, with the matches wrapped in ``. Only set by the keyword search, and only when the keyword actually occurs in the text.") + snippet_field: StrictStr | None = Field(default=None, description="Which field `snippet` was taken from: `title` or `abstract`.") + matched_via: list[StrictStr] | None = Field(default=None, description="Names of the topics and OpenAlex keywords that matched the searched keywords. Set by the keyword search so a work matched purely on metadata can explain itself when there is no `snippet`.") + __properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date", "snippet", "snippet_field", "matched_via"] model_config = ConfigDict( validate_by_name=True, @@ -273,7 +276,10 @@ class Work(BaseModel): "has_content": WorkHasContent.from_dict(obj["has_content"]) if obj.get("has_content") is not None else None, "content_url": obj.get("content_url"), "created_date": obj.get("created_date"), - "updated_date": obj.get("updated_date") + "updated_date": obj.get("updated_date"), + "snippet": obj.get("snippet"), + "snippet_field": obj.get("snippet_field"), + "matched_via": obj.get("matched_via") }) return _obj diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 20e139a8..5d9630bc 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -372,6 +372,19 @@ async def get_works_by_keywords( track_total_hits=True, offset=page * size, sort=sort, + # A work matches on its topic and keyword metadata as well as on its + # text, so roughly half the hits contain the searched keyword nowhere in + # title or abstract. Highlighting tells the two apart: a fragment comes + # back only for the works that really do carry the phrase. + highlight={ + "fields": { + "title": {"number_of_fragments": 0}, + "abstract": {"fragment_size": 240, "number_of_fragments": 1}, + }, + "pre_tags": [""], + "post_tags": [""], + "encoder": "html", + }, cluster=ESCluster.NES, ) print(f"Elasticsearch response: {response}") @@ -388,11 +401,63 @@ async def get_works_by_keywords( work = Work.from_dict(source) # type: ignore if work is not None: + snippet, snippet_field = _keyword_snippet(hit) + work.snippet = snippet + work.snippet_field = snippet_field + work.matched_via = _matched_via(source, keywords) elements.append(work) return WorkPageV2(elements=elements, total=total, page=page, size=size) +def _keyword_snippet(hit: dict) -> tuple[str | None, str | None]: + """Picks the passage to show for a hit, preferring the title over the abstract.""" + highlight = hit.get("highlight") or {} + + for field in ("title", "abstract"): + fragments = highlight.get(field) + if fragments: + return fragments[0], field + + return None, None + + +def _matched_via(source: dict, keywords: list[str] | None) -> list[str] | None: + """Names the topics and keywords a work was matched through. + + Only needed when there is no snippet: those works carry the searched term in + their metadata rather than in their text, and would otherwise expand into an + empty row. Matching mirrors the `match_phrase` clauses above closely enough + for a label - it is not used for retrieval. + """ + wanted = [kw.strip().lower() for kw in (keywords or []) if kw and kw.strip()] + if not wanted: + return None + + candidates: list[str] = [] + + primary_topic = source.get("primary_topic") or {} + candidates.append(primary_topic.get("display_name")) + + for topic in source.get("topics") or []: + candidates.append(topic.get("display_name")) + for level in ("field", "subfield", "domain"): + candidates.append((topic.get(level) or {}).get("display_name")) + + for keyword in source.get("keywords") or []: + candidates.append(keyword.get("display_name")) + + names: list[str] = [] + for name in candidates: + if not name or name in names: + continue + lowered = name.lower() + if any(kw in lowered for kw in wanted): + names.append(name) + + return names or None + + async def get_author_works( raw_oa_author_id: str, page: int, diff --git a/webapp/src/app/api/model/work.ts b/webapp/src/app/api/model/work.ts index 07d94a1c..97c4d648 100644 --- a/webapp/src/app/api/model/work.ts +++ b/webapp/src/app/api/model/work.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -24,48 +24,49 @@ import { WorkHasContent } from './workHasContent'; import { Location } from './location'; import { WorkBiblio } from './workBiblio'; - /** * A scholarly document (article, book, dataset, thesis, etc.) */ -export interface Work { - id?: string | null; - doi?: string | null; - title?: string | null; - display_name?: string | null; - publication_year?: number | null; - publication_date?: string | null; - type?: string | null; - language?: string | null; - cited_by_count?: number | null; - is_retracted?: boolean | null; - is_paratext?: boolean | null; - primary_location?: Location | null; - locations?: Array | null; - best_oa_location?: Location | null; - open_access?: OpenAccess | null; - authorships?: Array | null; - ids?: WorkIds | null; - biblio?: WorkBiblio | null; - abstract_inverted_index?: object | null; - referenced_works?: Array | null; - referenced_works_count?: number | null; - related_works?: Array | null; - topics?: Array | null; - primary_topic?: WorkTopic | null; - keywords?: Array | null; - funders?: Array | null; - awards?: Array | null; - fwci?: Fwci | null; - citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; - cited_by_percentile_year?: WorkCitedByPercentileYear | null; - counts_by_year?: Array | null; - sustainable_development_goals?: Array | null; - mesh?: Array | null; - indexed_in?: Array | null; - has_content?: WorkHasContent | null; - content_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Work { + id?: string | null; + doi?: string | null; + title?: string | null; + display_name?: string | null; + publication_year?: number | null; + publication_date?: string | null; + type?: string | null; + language?: string | null; + cited_by_count?: number | null; + is_retracted?: boolean | null; + is_paratext?: boolean | null; + primary_location?: Location | null; + locations?: Array | null; + best_oa_location?: Location | null; + open_access?: OpenAccess | null; + authorships?: Array | null; + ids?: WorkIds | null; + biblio?: WorkBiblio | null; + abstract_inverted_index?: object | null; + referenced_works?: Array | null; + referenced_works_count?: number | null; + related_works?: Array | null; + topics?: Array | null; + primary_topic?: WorkTopic | null; + keywords?: Array | null; + funders?: Array | null; + awards?: Array | null; + fwci?: Fwci | null; + citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; + cited_by_percentile_year?: WorkCitedByPercentileYear | null; + counts_by_year?: Array | null; + sustainable_development_goals?: Array | null; + mesh?: Array | null; + indexed_in?: Array | null; + has_content?: WorkHasContent | null; + content_url?: string | null; + created_date?: string | null; + updated_date?: string | null; + snippet?: string | null; + snippet_field?: string | null; + matched_via?: Array | null; } - diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index 7f6d987c..aa5496a9 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -5,11 +5,47 @@ [selectedAuthorsPage]="selectedAuthorsPage()" [showTopicFilter]="fuzzySearch()" /> + +
+ @if (snippetSegments().get(work.id); as segments) { + + Fundstelle im {{ snippetSourceLabel(work) }} + +

+ @for (segment of segments; track $index) { + @if (segment.isSearchMatch) { + {{ segment.text }} + } @else { + {{ segment.text }} + } + } +

+ } @else if (work.matched_via?.length) { + Kein Treffer im Text +

+ Das gesuchte Keyword kommt weder im Titel noch im Abstract vor. Die + Publikation wurde über + {{ work.matched_via!.length === 1 ? 'das Thema' : 'die Themen' }} + @for (name of work.matched_via; track name; let last = $last) { + {{ name }}{{ last ? '' : ', ' }} + } + gefunden. +

+ } @else { + + Für diese Publikation liegt keine Fundstelle vor. + + } +
+
+ + [topicFilterEnabled]="fuzzySearch()" + [detailTemplate]="snippetTmp" /> ') + .replace(/"/g, '"') + .replace(/&#(?:39|x27);/g, "'") + .replace(/&/g, '&'); +} + @Component({ selector: 'app-works-results', imports: [ @@ -64,6 +83,48 @@ export class KeywordsToWorksResultsComponent implements OnInit { fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true'); + readonly snippetSegments = computed(() => { + const byWorkId = new Map(); + + for (const work of this.elements()) { + if (!work.id || !work.snippet) { + continue; + } + byWorkId.set(work.id, this.buildSegments(work.snippet)); + } + + return byWorkId; + }); + + private buildSegments(snippet: string): SnippetSegment[] { + const searchMatch = /([\s\S]*?)<\/em>/g; + const segments: SnippetSegment[] = []; + + let lastIndex = 0; + let match: RegExpExecArray | null; + + const pushPlain = (raw: string) => { + const text = decodeHtml(raw); + if (text) { + segments.push({ text, isSearchMatch: false }); + } + }; + + while ((match = searchMatch.exec(snippet)) !== null) { + pushPlain(snippet.slice(lastIndex, match.index)); + segments.push({ text: decodeHtml(match[1]), isSearchMatch: true }); + lastIndex = searchMatch.lastIndex; + } + + pushPlain(snippet.slice(lastIndex)); + + return segments; + } + + snippetSourceLabel(work: Work): string { + return work.snippet_field === 'title' ? 'Titel' : 'Abstract'; + } + ngOnInit(): void {} clearFilters(): void { diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 85b8df3f..61871fe2 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -61,6 +61,7 @@ mat-row *matRowDef="let row; columns: displayedColumns()" class="element-row" + [class.is-expanded]="row === expandedElement()" (click)="toggleRow(row)"> + + @let expanded = isRowExpanded(work); + + + {{ work.title }} @@ -16,7 +33,7 @@ [class.active]="isTypeActive(work.type)" matTooltip="Nach Typ filtern" matTooltipPosition="above" - (click)="toggleTypeFilter(work.type)"> + (click)="$event.stopPropagation(); toggleTypeFilter(work.type)"> {{ work.type | workType }} @@ -34,7 +51,9 @@ [class.active]="isYearActive(work.publication_year)" matTooltip="Nach Jahr filtern" matTooltipPosition="above" - (click)="toggleYearFilter(work.publication_year)"> + (click)=" + $event.stopPropagation(); toggleYearFilter(work.publication_year) + "> {{ work.publication_year }} } @else { @@ -50,7 +69,7 @@ [class.active]="isLanguageActive(work.language)" matTooltip="Nach Sprache filtern" matTooltipPosition="above" - (click)="toggleLanguageFilter(work.language)"> + (click)="$event.stopPropagation(); toggleLanguageFilter(work.language)"> {{ work.language | languageCode }} } @else { @@ -81,7 +100,8 @@
+ style="padding: 0.5rem 0" + (click)="$event.stopPropagation()"> @for (institution of visibleInstitutions; track institution.id) { +
@for ( author of visibleAuthors; track author.id ?? 'name-' + author.display_name @@ -133,7 +157,11 @@ @let workTopics = work.topics ?? []; -
+
@for (topic of workTopics; track topic.id) { + matTooltip="Details anzeigen" + (click)="$event.stopPropagation()"> {{ OPEN_IN_NEW_ICON }} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss index 6df1e4e9..7a1d7b66 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss @@ -562,3 +562,12 @@ mat-panel-description { align-items: flex-start; max-width: 350px; } + +.expand-icon { + color: var(--sg-text-muted); + transition: transform 150ms ease-in-out; + + &.is-expanded { + transform: rotate(180deg); + } +} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts index 4977dea8..e5d6532a 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts @@ -70,6 +70,8 @@ export class PublicationTableComponent { rawOaAuthorId = input(undefined); rawOaInstitutionId = input(undefined); + detailTemplate = input | null>(null); + shouldFetchClassifications = computed(() => { return ( this.rawOaAuthorId() !== undefined || @@ -85,6 +87,7 @@ export class PublicationTableComponent { elements = computed(() => this.page().elements ?? []); + expandTmp = viewChild.required>('expandTmp'); titleTmp = viewChild.required>('titleTmp'); typeTmp = viewChild.required>('typeTmp'); yearTmp = viewChild.required>('yearTmp'); @@ -202,9 +205,24 @@ export class PublicationTableComponent { }, ); + if (this.detailTemplate()) { + baseColumns.unshift({ + id: 'expand', + header: '', + type: 'display', + cellTemplate: this.expandTmp(), + }); + } + return baseColumns; }); + private readonly dataTable = viewChild(DataTableComponent); + + isRowExpanded(work: Work): boolean { + return this.dataTable()?.expandedElement() === work; + } + workIds = computed( () => this.elements()