Skip to content

Adding dynamic queryables and queryable mappings. #340

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
57 changes: 4 additions & 53 deletions stac_fastapi/core/stac_fastapi/core/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ async def get_item(

@staticmethod
def _return_date(
interval: Optional[Union[DateTimeType, str]]
interval: Optional[Union[DateTimeType, str]],
) -> Dict[str, Optional[str]]:
"""
Convert a date interval.
Expand Down Expand Up @@ -911,6 +911,8 @@ def bulk_item_insert(
class EsAsyncBaseFiltersClient(AsyncBaseFiltersClient):
"""Defines a pattern for implementing the STAC filter extension."""

database: BaseDatabaseLogic = attr.ib()

# todo: use the ES _mapping endpoint to dynamically find what fields exist
async def get_queryables(
self, collection_id: Optional[str] = None, **kwargs
Expand All @@ -932,55 +934,4 @@ async def get_queryables(
Returns:
Dict[str, Any]: A dictionary containing the queryables for the given collection.
"""
return {
"$schema": "https://json-schema.org/draft/2019-09/schema",
"$id": "https://stac-api.example.com/queryables",
"type": "object",
"title": "Queryables for Example STAC API",
"description": "Queryable names for the example STAC API Item Search filter.",
"properties": {
"id": {
"description": "ID",
"$ref": "https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/definitions/core/allOf/2/properties/id",
},
"collection": {
"description": "Collection",
"$ref": "https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/definitions/core/allOf/2/then/properties/collection",
},
"geometry": {
"description": "Geometry",
"$ref": "https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/item.json#/definitions/core/allOf/1/oneOf/0/properties/geometry",
},
"datetime": {
"description": "Acquisition Timestamp",
"$ref": "https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/datetime.json#/properties/datetime",
},
"created": {
"description": "Creation Timestamp",
"$ref": "https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/datetime.json#/properties/created",
},
"updated": {
"description": "Creation Timestamp",
"$ref": "https://schemas.stacspec.org/v1.0.0/item-spec/json-schema/datetime.json#/properties/updated",
},
"cloud_cover": {
"description": "Cloud Cover",
"$ref": "https://stac-extensions.github.io/eo/v1.0.0/schema.json#/definitions/fields/properties/eo:cloud_cover",
},
"cloud_shadow_percentage": {
"description": "Cloud Shadow Percentage",
"title": "Cloud Shadow Percentage",
"type": "number",
"minimum": 0,
"maximum": 100,
},
"nodata_pixel_percentage": {
"description": "No Data Pixel Percentage",
"title": "No Data Pixel Percentage",
"type": "number",
"minimum": 0,
"maximum": 100,
},
},
"additionalProperties": True,
}
return self.database.get_queryables(collection_id=collection_id)
24 changes: 15 additions & 9 deletions stac_fastapi/core/stac_fastapi/core/extensions/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class SpatialIntersectsOp(str, Enum):
}


def to_es_field(field: str) -> str:
def to_es_field(queryables_mapping: Dict[str, Any], field: str) -> str:
"""
Map a given field to its corresponding Elasticsearch field according to a predefined mapping.

Expand All @@ -114,7 +114,7 @@ def to_es_field(field: str) -> str:
return queryables_mapping.get(field, field)


def to_es(query: Dict[str, Any]) -> Dict[str, Any]:
def to_es(queryables_mapping: Dict[str, Any], query: Dict[str, Any]) -> Dict[str, Any]:
"""
Transform a simplified CQL2 query structure to an Elasticsearch compatible query DSL.

Expand All @@ -130,7 +130,13 @@ def to_es(query: Dict[str, Any]) -> Dict[str, Any]:
LogicalOp.OR: "should",
LogicalOp.NOT: "must_not",
}[query["op"]]
return {"bool": {bool_type: [to_es(sub_query) for sub_query in query["args"]]}}
return {
"bool": {
bool_type: [
to_es(queryables_mapping, sub_query) for sub_query in query["args"]
]
}
}

elif query["op"] in [
ComparisonOp.EQ,
Expand All @@ -147,7 +153,7 @@ def to_es(query: Dict[str, Any]) -> Dict[str, Any]:
ComparisonOp.GTE: "gte",
}

field = to_es_field(query["args"][0]["property"])
field = to_es_field(queryables_mapping, query["args"][0]["property"])
value = query["args"][1]
if isinstance(value, dict) and "timestamp" in value:
value = value["timestamp"]
Expand All @@ -170,11 +176,11 @@ def to_es(query: Dict[str, Any]) -> Dict[str, Any]:
return {"range": {field: {range_op[query["op"]]: value}}}

elif query["op"] == ComparisonOp.IS_NULL:
field = to_es_field(query["args"][0]["property"])
field = to_es_field(queryables_mapping, query["args"][0]["property"])
return {"bool": {"must_not": {"exists": {"field": field}}}}

elif query["op"] == AdvancedComparisonOp.BETWEEN:
field = to_es_field(query["args"][0]["property"])
field = to_es_field(queryables_mapping, query["args"][0]["property"])
gte, lte = query["args"][1], query["args"][2]
if isinstance(gte, dict) and "timestamp" in gte:
gte = gte["timestamp"]
Expand All @@ -183,19 +189,19 @@ def to_es(query: Dict[str, Any]) -> Dict[str, Any]:
return {"range": {field: {"gte": gte, "lte": lte}}}

elif query["op"] == AdvancedComparisonOp.IN:
field = to_es_field(query["args"][0]["property"])
field = to_es_field(queryables_mapping, query["args"][0]["property"])
values = query["args"][1]
if not isinstance(values, list):
raise ValueError(f"Arg {values} is not a list")
return {"terms": {field: values}}

elif query["op"] == AdvancedComparisonOp.LIKE:
field = to_es_field(query["args"][0]["property"])
field = to_es_field(queryables_mapping, query["args"][0]["property"])
pattern = cql2_like_to_es(query["args"][1])
return {"wildcard": {field: {"value": pattern, "case_insensitive": True}}}

elif query["op"] == SpatialIntersectsOp.S_INTERSECTS:
field = to_es_field(query["args"][0]["property"])
field = to_es_field(queryables_mapping, query["args"][0]["property"])
geometry = query["args"][1]
return {"geo_shape": {field: {"shape": geometry, "relation": "intersects"}}}

Expand Down
8 changes: 5 additions & 3 deletions stac_fastapi/elasticsearch/stac_fastapi/elasticsearch/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@
settings = ElasticsearchSettings()
session = Session.create_from_settings(settings)

filter_extension = FilterExtension(client=EsAsyncBaseFiltersClient())
database_logic = DatabaseLogic()

filter_extension = FilterExtension(
client=EsAsyncBaseFiltersClient(database=database_logic)
)
filter_extension.conformance_classes.append(
"http://www.opengis.net/spec/cql2/1.0/conf/advanced-comparison-operators"
)

database_logic = DatabaseLogic()

aggregation_extension = AggregationExtension(
client=EsAsyncAggregationClient(
database=database_logic, session=session, settings=settings
Expand Down
Loading
Loading