Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: be able to create scatter plots #189

Merged
merged 20 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 59 additions & 5 deletions app/_types.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from functools import cached_property
from typing import Annotated, Any, Optional, Tuple, cast, get_type_hints
from typing import Annotated, Any, Literal, Optional, Tuple, Union, cast, get_type_hints

import elasticsearch_dsl.query
import luqum.tree
Expand All @@ -8,13 +8,35 @@

from . import config
from .utils import str_utils
from .validations import check_all_values_are_fields_agg, check_index_id_is_defined
from .validations import (
check_all_values_are_fields_agg,
check_fields_are_numeric,
check_index_id_is_defined,
)

#: A precise expectation of what mappings looks like in json.
#: (dict where keys are always of type `str`).
JSONType = dict[str, Any]


class DistributionChartType(BaseModel):
"""Describes an entry for a distribution chart"""

chart_type: Literal["DistributionChartType"] = "DistributionChartType"
field: str


class ScatterChartType(BaseModel):
"""Describes an entry for a scatter plot"""

chart_type: Literal["ScatterChartType"] = "ScatterChartType"
x: str
y: str


ChartType = Union[DistributionChartType, ScatterChartType]


class FacetItem(BaseModel):
"""Describes an entry of a facet"""

Expand Down Expand Up @@ -211,10 +233,10 @@ class SearchParameters(BaseModel):
),
] = None
charts: Annotated[
list[str] | None,
list[ChartType] | None,
Query(
description="""Name of vega representations to return in the response.
If None (default) no charts are returned."""
Can be distribution chart or scatter plot"""
),
] = None
sort_params: Annotated[
Expand Down Expand Up @@ -320,10 +342,42 @@ def check_facets_are_valid(self):
raise ValueError(errors)
return self

def check_field_is_numeric(field):
"""
return error if field is non
"""
Marc-AntoineA marked this conversation as resolved.
Show resolved Hide resolved

@model_validator(mode="after")
def check_charts_are_valid(self):
"""Check that the graph names are valid."""
errors = check_all_values_are_fields_agg(self.index_id, self.charts)
if self.charts is None:
return self

errors = check_all_values_are_fields_agg(
self.index_id,
[
chart.field
for chart in self.charts
if chart.chart_type == "DistributionChartType"
],
)

errors.extend(
check_fields_are_numeric(
self.index_id,
[
chart.x
for chart in self.charts
if chart.chart_type == "ScatterChartType"
]
+ [
chart.y
for chart in self.charts
if chart.chart_type == "ScatterChartType"
],
)
)

if errors:
raise ValueError(errors)
return self
Expand Down
26 changes: 21 additions & 5 deletions app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
from app import config
from app._types import (
INDEX_ID_QUERY_PARAM,
DistributionChartType,
GetSearchParamsTypes,
ScatterChartType,
SearchParameters,
SearchResponse,
SuccessSearchResponse,
Expand Down Expand Up @@ -107,8 +109,21 @@ def search(search_parameters: Annotated[SearchParameters, Body()]):
return app_search.search(search_parameters)


def parse_langs(langs: str | None) -> list[str]:
return langs.split(",") if langs else ["en"]
def parse_charts_get(charts_params: str):
"""
Parse for get params are 'field' or 'xfield:yfield'
separated by ',' for Distribution and Scatter charts.

Directly the dictionnaries in POST request
"""
charts = []
for c in charts_params.split(","):
if ":" in c:
[x, y] = c.split(":")
charts.append(ScatterChartType(x=x, y=y))
else:
charts.append(DistributionChartType(field=c))
return charts


@app.get("/search")
Expand All @@ -120,14 +135,15 @@ def search_get(
fields: GetSearchParamsTypes.fields = None,
sort_by: GetSearchParamsTypes.sort_by = None,
facets: GetSearchParamsTypes.facets = None,
charts: GetSearchParamsTypes.charts = None,
Marc-AntoineA marked this conversation as resolved.
Show resolved Hide resolved
charts: GetSearchParamsTypes.facets = None,
Marc-AntoineA marked this conversation as resolved.
Show resolved Hide resolved
index_id: GetSearchParamsTypes.index_id = None,
) -> SearchResponse:
# str to lists
langs_list = langs.split(",") if langs else ["en"]
fields_list = fields.split(",") if fields else None
facets_list = facets.split(",") if facets else None
charts_list = charts.split(",") if charts else None
charts = parse_charts_get(charts) if charts else None
Marc-AntoineA marked this conversation as resolved.
Show resolved Hide resolved
print(charts)
Marc-AntoineA marked this conversation as resolved.
Show resolved Hide resolved
# create SearchParameters object
try:
search_parameters = SearchParameters(
Expand All @@ -138,8 +154,8 @@ def search_get(
fields=fields_list,
sort_by=sort_by,
facets=facets_list,
charts=charts_list,
index_id=index_id,
charts=charts,
)
return app_search.search(search_parameters)
except ValidationError as e:
Expand Down
Loading