added autocompletion for person search
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<AuthorsListResponse>;
|
||||
public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
|
||||
public searchPersonsAutocomplete(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
|
||||
public searchPersonsAutocomplete(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
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,
|
||||
<any>authorName, 'author_name');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>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<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for persons by institution name.
|
||||
* @endpoint get /persons/searchByInstitution
|
||||
|
||||
@@ -52,6 +52,15 @@ export interface PersonsOpenApiServiceInterface {
|
||||
*/
|
||||
searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
|
||||
|
||||
/**
|
||||
* 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<AuthorsListResponse>;
|
||||
|
||||
/**
|
||||
* Searches for persons by institution name.
|
||||
*
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -34,17 +34,7 @@
|
||||
<span>Zurück zur Suche</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label class="search-box">
|
||||
<mat-icon>search</mat-icon>
|
||||
<input
|
||||
[formControl]="searchValue"
|
||||
type="search"
|
||||
placeholder="Suchen nach Personen, Themen, Projekten..."
|
||||
(keyup.enter)="startSearch()"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<app-searchbar/>
|
||||
<div class="topbar-actions">
|
||||
<ng-content select="[menu]"></ng-content>
|
||||
</div>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<label class="search-box">
|
||||
<mat-icon>search</mat-icon>
|
||||
<input matInput
|
||||
type="search"
|
||||
aria-label="Search"
|
||||
|
||||
[matAutocomplete]="auto"
|
||||
[formControl]="searchControl"
|
||||
(keydown.tab)="filteredPersons.results?.length ? onKeydownTab($any($event)) : null"
|
||||
placeholder="Suche nach Personen, Themen, Projekten..."
|
||||
(keyup.enter)="onEnter()"
|
||||
(focus)="onFocus()">
|
||||
|
||||
<mat-autocomplete #auto="matAutocomplete"
|
||||
>
|
||||
@for (person of filteredPersons.results; track person.id) {
|
||||
<mat-option [value]="person.display_name"
|
||||
(click)="selectPerson(person.display_name)">
|
||||
<span>{{ person.display_name }}</span>
|
||||
</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
</label>
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user