feat(keyword-search-works): expand rows to show matched content

This commit is contained in:
2026-08-24 21:49:05 +02:00
parent 2c03f53604
commit 2f509fbbfe
10 changed files with 332 additions and 53 deletions
@@ -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 `<em>`. 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
+65
View File
@@ -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": ["<em>"],
"post_tags": ["</em>"],
"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,
+43 -42
View File
@@ -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<Location> | null;
best_oa_location?: Location | null;
open_access?: OpenAccess | null;
authorships?: Array<Authorship> | null;
ids?: WorkIds | null;
biblio?: WorkBiblio | null;
abstract_inverted_index?: object | null;
referenced_works?: Array<string> | null;
referenced_works_count?: number | null;
related_works?: Array<string> | null;
topics?: Array<WorkTopic> | null;
primary_topic?: WorkTopic | null;
keywords?: Array<WorkKeyword> | null;
funders?: Array<DehydratedFunder> | null;
awards?: Array<Award> | null;
fwci?: Fwci | null;
citation_normalized_percentile?: WorkCitationNormalizedPercentile | null;
cited_by_percentile_year?: WorkCitedByPercentileYear | null;
counts_by_year?: Array<WorkCountsByYearInner> | null;
sustainable_development_goals?: Array<WorkSustainableDevelopmentGoalsInner> | null;
mesh?: Array<WorkMeshInner> | null;
indexed_in?: Array<string> | 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<Location> | null;
best_oa_location?: Location | null;
open_access?: OpenAccess | null;
authorships?: Array<Authorship> | null;
ids?: WorkIds | null;
biblio?: WorkBiblio | null;
abstract_inverted_index?: object | null;
referenced_works?: Array<string> | null;
referenced_works_count?: number | null;
related_works?: Array<string> | null;
topics?: Array<WorkTopic> | null;
primary_topic?: WorkTopic | null;
keywords?: Array<WorkKeyword> | null;
funders?: Array<DehydratedFunder> | null;
awards?: Array<Award> | null;
fwci?: Fwci | null;
citation_normalized_percentile?: WorkCitationNormalizedPercentile | null;
cited_by_percentile_year?: WorkCitedByPercentileYear | null;
counts_by_year?: Array<WorkCountsByYearInner> | null;
sustainable_development_goals?: Array<WorkSustainableDevelopmentGoalsInner> | null;
mesh?: Array<WorkMeshInner> | null;
indexed_in?: Array<string> | 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<string> | null;
}
@@ -5,11 +5,47 @@
[selectedAuthorsPage]="selectedAuthorsPage()"
[showTopicFilter]="fuzzySearch()" />
<ng-template #snippetTmp let-work>
<div class="snippet-detail">
@if (snippetSegments().get(work.id); as segments) {
<span class="snippet-label">
Fundstelle im {{ snippetSourceLabel(work) }}
</span>
<p class="snippet">
@for (segment of segments; track $index) {
@if (segment.isSearchMatch) {
<mark class="snippet-mark">{{ segment.text }}</mark>
} @else {
<span>{{ segment.text }}</span>
}
}
</p>
} @else if (work.matched_via?.length) {
<span class="snippet-label">Kein Treffer im Text</span>
<p class="snippet">
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) {
<span class="matched-topic">{{ name }}</span
>{{ last ? '' : ', ' }}
}
gefunden.
</p>
} @else {
<span class="empty-text">
Für diese Publikation liegt keine Fundstelle vor.
</span>
}
</div>
</ng-template>
<app-publication-table
[page]="workPage()"
[authorFilterEnabled]="true"
[institutionFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()" />
[topicFilterEnabled]="fuzzySearch()"
[detailTemplate]="snippetTmp" />
<app-query-param-paginator
[total]="total()"
@@ -82,3 +82,56 @@
align-items: center;
gap: 0.5rem;
}
/* ============================================================
EXPANDED DETAIL ROW
============================================================ */
:host ::ng-deep {
.detail-row .mat-mdc-cell {
padding: 0;
}
.element-row.is-expanded .mat-mdc-cell {
border-bottom-color: transparent;
}
}
.snippet-detail {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.875rem 1rem 1rem 4rem;
background: var(--sg-surface-soft);
}
.snippet-label {
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.snippet {
margin: 0;
font-size: 12.5px;
line-height: 1.6;
color: var(--sg-text-secondary);
overflow-wrap: anywhere;
}
.snippet-mark {
background: transparent;
color: var(--sg-blue-highlight);
font-weight: 700;
}
.matched-topic {
color: var(--sg-text);
font-weight: 600;
}
.empty-text {
color: var(--sg-text-muted);
}
@@ -11,9 +11,28 @@ import { PublicationTableComponent } from '../../../../shared/ui/publication-tab
import { WorkPageV2 } from '../../../../api/model/workPageV2';
import { PaginationService } from '../../../../shared/services/pagination.service';
import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component';
import { AuthorPage, InstitutionPageV2, TopicPageV2 } from '../../../../api';
import {
AuthorPage,
InstitutionPageV2,
TopicPageV2,
Work,
} from '../../../../api';
import { SearchResultsStateService } from '../search-results-state.service';
interface SnippetSegment {
text: string;
isSearchMatch: boolean;
}
function decodeHtml(text: string): string {
return text
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#(?:39|x27);/g, "'")
.replace(/&amp;/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<string, SnippetSegment[]>();
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 = /<em>([\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 {
@@ -61,6 +61,7 @@
mat-row
*matRowDef="let row; columns: displayedColumns()"
class="element-row"
[class.is-expanded]="row === expandedElement()"
(click)="toggleRow(row)"></tr>
<tr
@@ -1,9 +1,26 @@
<app-data-table
[columns]="columns()"
[data]="elements()"
[detailTemplate]="detailTemplate()"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
<ng-template #expandTmp let-work>
@let expanded = isRowExpanded(work);
<button
mat-icon-button
class="expand-toggle"
[attr.aria-expanded]="expanded"
[matTooltip]="expanded ? 'Fundstelle ausblenden' : 'Fundstelle anzeigen'"
[attr.aria-label]="
expanded ? 'Fundstelle ausblenden' : 'Fundstelle anzeigen'
">
<mat-icon class="expand-icon" [class.is-expanded]="expanded">
expand_more
</mat-icon>
</button>
</ng-template>
<ng-template #titleTmp let-work>
<span>{{ work.title }}</span>
</ng-template>
@@ -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)">
<app-chip [color]="typeColor(work.type)">
{{ work.type | workType }}
</app-chip>
@@ -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 }}
</button>
} @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 }}
</button>
} @else {
@@ -81,7 +100,8 @@
<div
class="institution-chips"
aria-label="Institutionen"
style="padding: 0.5rem 0">
style="padding: 0.5rem 0"
(click)="$event.stopPropagation()">
@for (institution of visibleInstitutions; track institution.id) {
<app-institution-chip
size="mini"
@@ -107,7 +127,11 @@
@let workAuthorsExpanded = isWorkAuthorsExpanded(work);
@let visibleAuthors =
workAuthorsExpanded ? workAuthors : workAuthors.slice(0, 3);
<div class="author-chips" aria-label="Autoren" style="padding: 0.5rem 0">
<div
class="author-chips"
aria-label="Autoren"
style="padding: 0.5rem 0"
(click)="$event.stopPropagation()">
@for (
author of visibleAuthors;
track author.id ?? 'name-' + author.display_name
@@ -133,7 +157,11 @@
<ng-template #topicsTmp let-work>
@let workTopics = work.topics ?? [];
<div class="topic-chips" aria-label="Themen" style="display: flex">
<div
class="topic-chips"
aria-label="Themen"
style="display: flex"
(click)="$event.stopPropagation()">
@for (topic of workTopics; track topic.id) {
<app-topic-chip-2
size="mini"
@@ -157,7 +185,8 @@
mat-icon-button
color="primary"
[routerLink]="['/publication', extractRawId(work.id)]"
matTooltip="Details anzeigen">
matTooltip="Details anzeigen"
(click)="$event.stopPropagation()">
<mat-icon>{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
</ng-template>
@@ -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);
}
}
@@ -70,6 +70,8 @@ export class PublicationTableComponent {
rawOaAuthorId = input<string | undefined>(undefined);
rawOaInstitutionId = input<string | undefined>(undefined);
detailTemplate = input<TemplateRef<any> | null>(null);
shouldFetchClassifications = computed(() => {
return (
this.rawOaAuthorId() !== undefined ||
@@ -85,6 +87,7 @@ export class PublicationTableComponent {
elements = computed(() => this.page().elements ?? []);
expandTmp = viewChild.required<TemplateRef<any>>('expandTmp');
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
typeTmp = viewChild.required<TemplateRef<any>>('typeTmp');
yearTmp = viewChild.required<TemplateRef<any>>('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()