From c24686258cfe9ddbc68386229a440f9d570ec012 Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 3 Jun 2026 17:40:25 +0200 Subject: [PATCH] added autocompletion for person search --- service/src/main/inse/logic.py | 90 +++++++++++++- service/src/main/inse/service.py | 16 +++ webapp/src/app/api/api/persons.service.ts | 66 ++++++++++ .../app/api/api/persons.serviceInterface.ts | 9 ++ .../app/modules/person/person.component.ts | 15 ++- .../ui/app-layout/app-layout.component.html | 12 +- .../ui/app-layout/app-layout.component.scss | 29 ----- .../ui/app-layout/app-layout.component.ts | 15 +-- .../app-searchbar.component.html | 23 ++++ .../app-searchbar.component.scss | 28 +++++ .../app-searchbar/app-searchbar.component.ts | 115 ++++++++++++++++++ 11 files changed, 361 insertions(+), 57 deletions(-) create mode 100644 webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html create mode 100644 webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss create mode 100644 webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 5bd6d268..b47f9930 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -390,6 +390,94 @@ def search_persons_by_name(author_name: str, limit: Optional[int] = 10, include: return AuthorsListResponse(results=persons) + +def search_persons_autocomplete(author_name: str, limit: Optional[int] = 5, include: Optional[str] = None) -> AuthorsListResponse: + if not author_name: + raise HTTPException( + status_code=400, + detail="name must be provided" + ) + + search_query = { + "function_score": { + "query": { + "wildcard": { + "display_name.keyword": { + "value": author_name + "*", + "case_insensitive": True + } + } + }, + "functions": [ + { + "script_score": { + "script": { + "lang": "painless", + "source": "String name = doc['display_name.keyword'].value.toLowerCase(); String[] parts = name.splitOnToken(' '); Set unique = new HashSet(); for (String p : parts) { unique.add(p); } return unique.size() > 1 ? 1.0 : 0.3;" + } + } + } + ], + "boost_mode": "multiply" + } + } + script_fields ={ + "affiliations": { + "script": { + "lang": "painless", + "source": "def aff = params._source['affiliations']; if (aff != null && aff.size() > 0) { return aff[aff.size() - 1]; } return [];" + } + } + } + collapse ={ + "field":"display_name.keyword" + } + body = { + "size":limit, + "query":search_query, + "script_fields":script_fields, + "_source":include.split(",") if include else True, + "sort":[{"works_count": {"order": "desc"}}], + "collapse":collapse + } + try: + response = elasticsearch.search( + index="openalex-authors", + body=body + ) + + except Exception as e: + raise HTTPException( + status_code=500, + detail=f"Elasticsearch search failed: {str(e)}" + ) + + hits = response.get("hits", {}).get("hits", []) + + persons = [] + for hit in hits: + fields = hit.get("fields",{}) + source = hit.get("_source",{}) + source_copy = dict (source) + source_copy["id"] = hit.get("_id", "") or source_copy.get("id") + + # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) + ids = source_copy.get("ids") + if isinstance(ids, dict): + ids_copy = dict(ids) + for str_field in ["openalex", "orcid", "scopus"]: + val = ids_copy.get(str_field) + if val is not None and not isinstance(val, str): + ids_copy[str_field] = str(val) + source_copy["ids"] = ids_copy + + for key,value in fields.items(): + source_copy[key] = value + author = Author.from_dict(source_copy) + persons.append(author) + + return AuthorsListResponse(results=persons) + def search_persons_by_institution( institution_name: str, limit: Optional[int] = 10, @@ -417,8 +505,8 @@ def search_persons_by_institution( "query":search_query, "_source":include.split(",") if include else True, "sort":[{"works_count": {"order": "desc"}}] + } - print(body) try: response = elasticsearch.search( index="openalex-authors", diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 73c0fc65..522087ee 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -224,6 +224,22 @@ def search_persons_by_name( )]): return logic.search_persons_by_name(author_name=author_name,include=include) +@app.get('/persons/autocomplete', + operation_id='searchPersonsAutocomplete', + response_model=AuthorsListResponse, + summary='Searches for person by name.', + tags=[ 'Persons' ]) +def search_persons_autocomplete( + author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], + include : Annotated[Optional[str], Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share" + )]): + return logic.search_persons_autocomplete(author_name=author_name,include=include) + @app.get('/persons/searchByInstitution', operation_id='searchPersonsByInstitution', response_model=AuthorsListResponse, diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index aa9747cb..810bc2cd 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -234,6 +234,72 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi ); } + /** + * Searches for person by name. + * @endpoint get /persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsAutocomplete.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsAutocomplete.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/persons/autocomplete`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Searches for persons by institution name. * @endpoint get /persons/searchByInstitution diff --git a/webapp/src/app/api/api/persons.serviceInterface.ts b/webapp/src/app/api/api/persons.serviceInterface.ts index 67b9a127..23fd7a08 100644 --- a/webapp/src/app/api/api/persons.serviceInterface.ts +++ b/webapp/src/app/api/api/persons.serviceInterface.ts @@ -52,6 +52,15 @@ export interface PersonsOpenApiServiceInterface { */ searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable; + /** + * Searches for person by name. + * + * @endpoint get /persons/autocomplete + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + */ + searchPersonsAutocomplete(authorName: string, include: string, extraHttpRequestParams?: any): Observable; + /** * Searches for persons by institution name. * diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 06674875..55099c5a 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -7,7 +7,7 @@ import { MatTabsModule } from '@angular/material/tabs'; import { ActivatedRoute, RouterModule, RouterOutlet } from '@angular/router'; import { of, switchMap, finalize, map, catchError } from 'rxjs'; -import { Author, PersonsOpenApiService } from '../../api'; +import { Author, AuthorAffiliationsInner, PersonsOpenApiService } from '../../api'; import { PersonInterestingComponent } from '../person-interesting/person-interesting.component'; const PERSON_INCLUDE_TAGS = @@ -93,11 +93,20 @@ readonly personBio = toSignal( readonly primaryAffiliation = computed( () => this.person()?.affiliations?.[0] ?? null, ); + readonly lastAffiliation = computed( + ()=> { + let lastAffiliation: number | undefined = 0 + if (this.person()?.affiliations?.length != undefined){ + lastAffiliation = this.person()?.affiliations?.length + } + return (lastAffiliation ? this.person()?.affiliations?.[lastAffiliation - 1] : this.person()?.affiliations?.[0]) ?? null + } + ) readonly institution = computed( - () => this.primaryAffiliation()?.institution?.display_name ?? 'Unbekannte Institution', + () => this.lastAffiliation()?.institution?.display_name ?? 'Unbekannte Institution', ); readonly countryCode = computed( - () => this.primaryAffiliation()?.institution?.country_code ?? null, + () => this.lastAffiliation()?.institution?.country_code ?? null, ); readonly worksCount = computed(() => this.person()?.works_count ?? null); readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null); diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index b2fe1274..ef8b9baa 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -34,17 +34,7 @@ Zurück zur Suche - - - +
diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss index 83fb51a9..2b4f48bb 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.scss +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.scss @@ -1,5 +1,4 @@ @use '@angular/material' as mat; -@import '../../../../m3-theme.scss'; .app-shell { height: 100svh; @@ -72,34 +71,6 @@ mat-toolbar.main { height: 20px; } -.search-box { - display: flex; - align-items: center; - gap: 12px; - height: 44px; - align-self: center; - padding: 0 18px; - background: var(--sg-surface-muted); - border: 1px solid var(--sg-border); - border-radius: var(--sg-radius-sm); - color: var(--sg-text-soft); - font-size: 13px; - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8); -} - -.search-box input { - width: 100%; - min-width: 0; - border: 0; - outline: 0; - background: transparent; - color: var(--sg-text); -} - -.search-box input::placeholder { - color: var(--sg-text-muted); -} - .drawer { width: var(--sg-sidebar-width); background: var(--sg-surface); diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index e246822d..d858400d 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -9,13 +9,12 @@ import { MediaMatcher } from '@angular/cdk/layout'; import { AppMenuComponent } from '../app-menu/app-menu.component'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CredentialService } from '../../services/credential.service'; -import { FormControl,ReactiveFormsModule } from '@angular/forms'; -import { SharedStateService } from '../../services/shared-state.service'; import { Location } from '@angular/common'; +import { AppSearchbarComponent } from "../app-searchbar/app-searchbar.component"; @Component({ selector: 'app-layout', - imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, AppMenuComponent, MatTooltipModule,ReactiveFormsModule], + imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, AppMenuComponent, MatTooltipModule, AppSearchbarComponent], templateUrl: './app-layout.component.html', styleUrl: './app-layout.component.scss', standalone: true, @@ -30,10 +29,8 @@ export class AppLayoutComponent implements OnInit, OnDestroy { mediaQueryListener: () => void; sideNavOpen = false; - searchValue = new FormControl(''); constructor(public credentialService: CredentialService, public router: Router, private location:Location, - private state: SharedStateService, public changeDetector: ChangeDetectorRef, media: MediaMatcher) { this.mediaQuery = media.matchMedia('(max-width: 600px)'); this.mediaQueryListener = () => { @@ -61,14 +58,6 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.credentialService.logoutAcount(); this.router.navigate(['/']) } - startSearch(){ - console.log("updated to", this.searchValue.value,this.router.url) - - if (this.router.url.startsWith('/persons')) { - this.router.navigate(['/persons']); - } - this.state.searchValue.set(this.searchValue.value); - } navigateBack(){ this.location.back() } diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html new file mode 100644 index 00000000..145c976a --- /dev/null +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.html @@ -0,0 +1,23 @@ + \ No newline at end of file diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss new file mode 100644 index 00000000..3f1cae7d --- /dev/null +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.scss @@ -0,0 +1,28 @@ + +.search-box { + display: flex; + align-items: center; + gap: 12px; + height: 44px; + align-self: center; + padding: 0 18px; + background: var(--sg-surface-muted); + border: 1px solid var(--sg-border); + border-radius: var(--sg-radius-sm); + color: var(--sg-text-soft); + font-size: 13px; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8); +} + +.search-box input { + width: 100%; + min-width: 0; + border: 0; + outline: 0; + background: transparent; + color: var(--sg-text); +} + +.search-box input::placeholder { + color: var(--sg-text-muted); +} diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts new file mode 100644 index 00000000..7a7c9628 --- /dev/null +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts @@ -0,0 +1,115 @@ +import { Component, signal, inject,ViewChild } from '@angular/core'; +import { MatIcon } from '@angular/material/icon'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { Observable } from 'rxjs'; +import { Router } from '@angular/router'; +import { SharedStateService } from '../../services/shared-state.service'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; +import { MatInputModule } from '@angular/material/input'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { map, switchMap, filter } from 'rxjs/operators'; +import { toObservable } from '@angular/core/rxjs-interop'; +import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; +import { PersonsOpenApiService } from '../../../api'; +import { AuthorsListResponse, Author } from '../../../api'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { DestroyRef } from '@angular/core'; +import { of } from 'rxjs'; +import { MatAutocompleteTrigger,MatAutocomplete } from '@angular/material/autocomplete'; +export interface State { + flag: string; + name: string; + population: string; +} + +@Component({ + selector: 'app-searchbar', + standalone: true, + imports: [ + MatIcon, + ReactiveFormsModule, + MatAutocompleteModule, + MatInputModule, + MatFormFieldModule, + ], + templateUrl: './app-searchbar.component.html', + styleUrl: './app-searchbar.component.scss', +}) +export class AppSearchbarComponent { + @ViewChild(MatAutocompleteTrigger) autocompleteTrigger!: MatAutocompleteTrigger; + @ViewChild(MatAutocomplete) autocomplete!: MatAutocomplete; + searchValue = new FormControl(''); + searchControl = new FormControl(''); + showAutocomplete = false; + + filteredPersons: AuthorsListResponse = { + meta: null, + results: [], + group_by: [], + }; + + private destroyRef = inject(DestroyRef); + constructor( + public router: Router, + private state: SharedStateService, + private personService: PersonsOpenApiService, + ) { + this.searchControl.valueChanges + .pipe( + debounceTime(100), + distinctUntilChanged(), + switchMap((v: any) => { + const value = v ?? ''; + + if (value.length < 2) { + return of(this.emptyPersons()); + } + + return this.personService.searchPersonsAutocomplete( + value, + 'display_name', + ); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((results) => { + this.filteredPersons = results; + }); + } + emptyPersons(): AuthorsListResponse { + return { + meta: null, + results: [], + group_by: [], + }; + } + selectPerson(personName: string | undefined | null) { + if (personName) { + this.searchControl.setValue(personName); + this.startSearch() + } + } + onKeydownTab(event: KeyboardEvent) { + event.preventDefault(); // stop focus jump + const first = this.filteredPersons?.results?.[0]; + if (first && first.display_name) { + this.searchControl.setValue(first.display_name); + } + } + onEnter() { + this.autocompleteTrigger.closePanel() + this.startSearch(); + } + onFocus() { + this.autocompleteTrigger.openPanel() + } + + startSearch() { + console.log('updated to', this.searchControl.value, this.router.url); + + if (this.router.url.startsWith('/persons')) { + this.router.navigate(['/persons']); + } + this.state.searchValue.set(this.searchControl.value); + } +}