refactor search & added button to filter newest affiliation of institution
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -3,6 +3,8 @@ import logging
|
||||
import hashlib
|
||||
from typing import List, Optional
|
||||
from fastapi import HTTPException
|
||||
from elasticsearch import NotFoundError, RequestError, ApiError
|
||||
from inse.search.query_builder import build_authors_search
|
||||
|
||||
from inse import util
|
||||
from inse.logic import es_client
|
||||
@@ -11,6 +13,7 @@ from inse.models.meta import Meta
|
||||
from inse.search.model import CustomAuthor, CustomAuthorsListResponse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
|
||||
def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
|
||||
if not author_data:
|
||||
@@ -36,7 +39,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
|
||||
else:
|
||||
relevance_rating = "Möglich"
|
||||
|
||||
# Resilient sanitization of IDs to protect against model type conflicts (Generated)
|
||||
# Resilient sanitization of IDs to protect against model type conflicts (Generated) TODO: multiple code occurrences (e.g. in util.py) => refactor into seperate utility function (if required, after all merges)
|
||||
ids = author_data.get("ids")
|
||||
if isinstance(ids, dict):
|
||||
ids_copy = dict(ids)
|
||||
@@ -63,69 +66,40 @@ def advanced_search_persons(
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
include: Optional[set[str]] = None,
|
||||
strict: Optional[bool] = False,
|
||||
) -> CustomAuthorsListResponse:
|
||||
must_clauses = []
|
||||
filter_clauses = []
|
||||
|
||||
if query:
|
||||
must_clauses.append({
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"display_name": {"query": query, "boost": 5}}},
|
||||
{"match_phrase_prefix": {"display_name": {"query": query, "boost": 3}}},
|
||||
{"match": {"display_name": {"query": query, "fuzziness": 1}}},
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
})
|
||||
|
||||
if institution_name:
|
||||
filter_clauses.append({
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": institution_name
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if topics:
|
||||
for t in topics:
|
||||
if t:
|
||||
filter_clauses.append({
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {
|
||||
"match_phrase": {
|
||||
"topics.display_name": t
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
query_body = {"bool": {}}
|
||||
if must_clauses:
|
||||
query_body["bool"]["must"] = must_clauses
|
||||
if filter_clauses:
|
||||
query_body["bool"]["filter"] = filter_clauses
|
||||
if not must_clauses and not filter_clauses:
|
||||
query_body["bool"]["must"] = [{"match_all": {}}]
|
||||
|
||||
es_size = page_size
|
||||
es_from = (page - 1) * page_size
|
||||
|
||||
sort_option = [{"cited_by_count": {"order": "desc"}}, {"works_count": {"order": "desc"}}]
|
||||
|
||||
try:
|
||||
response = es_client.search(
|
||||
index="openalex-authors",
|
||||
query=query_body,
|
||||
source=list(include) if include else True,
|
||||
from_=es_from,
|
||||
size=es_size,
|
||||
sort=sort_option if not query else None,
|
||||
s = build_authors_search(
|
||||
using=es_client,
|
||||
index=INDEX_NAME,
|
||||
query=query,
|
||||
institution_name=institution_name,
|
||||
topics=topics,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
include=include,
|
||||
strict=strict,
|
||||
)
|
||||
response = s.execute()
|
||||
except NotFoundError:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[],
|
||||
meta=Meta(
|
||||
count=0,
|
||||
page=page,
|
||||
per_page=page_size
|
||||
)
|
||||
)
|
||||
except RequestError as e:
|
||||
logger.error(f"Elasticsearch request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"Elasticsearch request error: {str(e)}"
|
||||
)
|
||||
except ApiError as e:
|
||||
logger.error(f"Elasticsearch API error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch API error: {str(e)}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Elasticsearch search failed: {str(e)}")
|
||||
@@ -133,8 +107,9 @@ def advanced_search_persons(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
response_dict = response.to_dict()
|
||||
hits = response_dict.get("hits", {}).get("hits", [])
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
results = []
|
||||
for hit in hits:
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from typing import List, Optional, Set, Any
|
||||
from elasticsearch.dsl import Search, query as dsl_query
|
||||
|
||||
def build_authors_search(
|
||||
using: Any = None,
|
||||
index: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
institution_name: Optional[str] = None,
|
||||
topics: Optional[List[str]] = None,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
include: Optional[Set[str]] = None,
|
||||
strict: Optional[bool] = False,
|
||||
) -> Search:
|
||||
"""
|
||||
Builds an Elasticsearch search request for authors using elasticsearch-dsl.
|
||||
"""
|
||||
s = Search(using=using, index=index)
|
||||
|
||||
# 1. Build Query Clauses
|
||||
if query:
|
||||
# Match original query structure with nested bool should
|
||||
# "must_clauses.append({"bool": {"should": [...], "minimum_should_match": 1}})"
|
||||
should_match_phrase = dsl_query.MatchPhrase(display_name={"query": query, "boost": 5})
|
||||
should_match_phrase_prefix = dsl_query.MatchPhrasePrefix(display_name={"query": query, "boost": 3})
|
||||
should_match_fuzziness = dsl_query.Match(display_name={"query": query, "fuzziness": 1})
|
||||
|
||||
query_clause = dsl_query.Bool(
|
||||
should=[
|
||||
should_match_phrase,
|
||||
should_match_phrase_prefix,
|
||||
should_match_fuzziness
|
||||
],
|
||||
minimum_should_match=1
|
||||
)
|
||||
s = s.query(query_clause)
|
||||
|
||||
# 2. Build Filters
|
||||
if institution_name:
|
||||
if strict:
|
||||
from datetime import datetime
|
||||
current_year = datetime.now().year
|
||||
target_year = current_year - 1
|
||||
|
||||
inst_query = dsl_query.MatchPhrase(**{"affiliations.institution.display_name": institution_name})
|
||||
year_query = dsl_query.Range(**{"affiliations.years": {"gte": target_year}})
|
||||
|
||||
s = s.filter(
|
||||
dsl_query.Nested(
|
||||
path="affiliations",
|
||||
query=dsl_query.Bool(filter=[inst_query, year_query])
|
||||
)
|
||||
)
|
||||
else:
|
||||
s = s.filter(
|
||||
dsl_query.Nested(
|
||||
path="affiliations",
|
||||
query=dsl_query.MatchPhrase(
|
||||
**{"affiliations.institution.display_name": institution_name}
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if topics:
|
||||
for t in topics:
|
||||
if t:
|
||||
s = s.filter(
|
||||
dsl_query.Nested(
|
||||
path="topics",
|
||||
query=dsl_query.MatchPhrase(
|
||||
**{"topics.display_name": t}
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# If no query and no filters, default to match_all
|
||||
if not query and not institution_name and not (topics and any(topics)):
|
||||
s = s.query(dsl_query.MatchAll())
|
||||
|
||||
# 3. Source Filtering
|
||||
if include:
|
||||
s = s.source(list(include))
|
||||
else:
|
||||
s = s.source(True)
|
||||
|
||||
# 4. Pagination
|
||||
es_size = page_size
|
||||
es_from = (page - 1) * page_size
|
||||
s = s[es_from:es_from + es_size]
|
||||
|
||||
# 5. Sorting
|
||||
if not query:
|
||||
s = s.sort(
|
||||
{"cited_by_count": {"order": "desc"}},
|
||||
{"works_count": {"order": "desc"}}
|
||||
)
|
||||
|
||||
return s
|
||||
@@ -46,6 +46,9 @@ def search_persons_list(
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
] = None,
|
||||
strict: Annotated[
|
||||
Optional[bool], Query(description="Strict institution search by target year")
|
||||
] = False,
|
||||
):
|
||||
include_set = (
|
||||
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
|
||||
@@ -59,4 +62,5 @@ def search_persons_list(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
include=include_set,
|
||||
strict=strict,
|
||||
)
|
||||
|
||||
@@ -52,10 +52,10 @@ export class PersonsSearchService extends BaseService implements PersonsSearchSe
|
||||
* @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 searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
|
||||
public searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
@@ -74,6 +74,8 @@ export class PersonsSearchService extends BaseService implements PersonsSearchSe
|
||||
<any>pageSize, 'pageSize');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>include, 'include');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>strict, 'strict');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
|
||||
@@ -33,7 +33,8 @@ export interface PersonsSearchServiceInterface {
|
||||
* @param page Page number (1-indexed)
|
||||
* @param pageSize Results per page
|
||||
* @param include Comma-separated include tags
|
||||
* @param strict Strict search parameter
|
||||
*/
|
||||
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
|
||||
searchPersonsList(query?: string, institutionName?: string, topic?: Array<string>, page?: number, pageSize?: number, include?: string, strict?: boolean, extraHttpRequestParams?: any): Observable<CustomAuthorsListResponse>;
|
||||
|
||||
}
|
||||
|
||||
@@ -212,6 +212,12 @@
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="strict-search-wrapper" style="margin-top: 8px;">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" [formControl]="strictControl" (change)="applySidebarFilters()" />
|
||||
<span class="checkbox-text">Letzten 2 Jahre</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sidebar Footer Action showing matches count -->
|
||||
|
||||
@@ -69,6 +69,7 @@ export class PersonListComponent {
|
||||
sortControl = new FormControl('relevance', { nonNullable: true });
|
||||
topicSearchControl = new FormControl('', { nonNullable: true });
|
||||
institutionControl = new FormControl('', { nonNullable: true });
|
||||
strictControl = new FormControl(false, { nonNullable: true });
|
||||
showAllTopics = false;
|
||||
|
||||
// Bookmarking
|
||||
@@ -83,6 +84,7 @@ export class PersonListComponent {
|
||||
const page = params['page'] ? Number.parseInt(params['page'], 10) : 1;
|
||||
const pageSize = params['pageSize'] ? Number.parseInt(params['pageSize'], 10) : 10;
|
||||
const institutionName = params['institutionName'] || '';
|
||||
const strict = params['strict'] === 'true';
|
||||
|
||||
const topics = this.parseQueryParamArray(params['topic']);
|
||||
|
||||
@@ -97,8 +99,11 @@ export class PersonListComponent {
|
||||
if (this.institutionControl.value !== institutionName) {
|
||||
this.institutionControl.setValue(institutionName);
|
||||
}
|
||||
if (this.strictControl.value !== strict) {
|
||||
this.strictControl.setValue(strict);
|
||||
}
|
||||
|
||||
this.load(query, page, pageSize, topics, institutionName);
|
||||
this.load(query, page, pageSize, topics, institutionName, strict);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -107,7 +112,8 @@ export class PersonListComponent {
|
||||
page: number = 1,
|
||||
pageSize: number = 10,
|
||||
topics?: string[],
|
||||
institutionName?: string
|
||||
institutionName?: string,
|
||||
strict: boolean = false
|
||||
): void {
|
||||
this.loadingState.set(true);
|
||||
|
||||
@@ -117,7 +123,8 @@ export class PersonListComponent {
|
||||
topics?.length ? topics : undefined,
|
||||
page,
|
||||
pageSize,
|
||||
this.defaultIncludes
|
||||
this.defaultIncludes,
|
||||
strict || undefined
|
||||
)
|
||||
.pipe(
|
||||
finalize(() => this.loadingState.set(false)),
|
||||
@@ -195,10 +202,11 @@ export class PersonListComponent {
|
||||
list.push({ category: 'topic', value: t, label: t });
|
||||
});
|
||||
if (this.institutionControl.value) {
|
||||
const label = `Institution: ${this.institutionControl.value}${this.strictControl.value ? ' (Strict)' : ''}`;
|
||||
list.push({
|
||||
category: 'institutionName',
|
||||
value: this.institutionControl.value,
|
||||
label: `Institution: ${this.institutionControl.value}`
|
||||
label: label
|
||||
});
|
||||
}
|
||||
return list;
|
||||
@@ -209,6 +217,7 @@ export class PersonListComponent {
|
||||
this.selectedTopics.delete(filter.value);
|
||||
} else if (filter.category === 'institutionName') {
|
||||
this.institutionControl.setValue('');
|
||||
this.strictControl.setValue(false);
|
||||
}
|
||||
this.applySidebarFilters();
|
||||
}
|
||||
@@ -216,6 +225,7 @@ export class PersonListComponent {
|
||||
clearAllFilters(): void {
|
||||
this.selectedTopics.clear();
|
||||
this.institutionControl.setValue('');
|
||||
this.strictControl.setValue(false);
|
||||
this.applySidebarFilters();
|
||||
}
|
||||
|
||||
@@ -224,6 +234,7 @@ export class PersonListComponent {
|
||||
queryParams: {
|
||||
topic: this.selectedTopics.size ? Array.from(this.selectedTopics) : null,
|
||||
institutionName: this.institutionControl.value || null,
|
||||
strict: this.strictControl.value ? 'true' : null,
|
||||
page: 1,
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
|
||||
Reference in New Issue
Block a user