|
4 | 4 | """ |
5 | 5 |
|
6 | 6 | from typing import Any, Dict, List, Optional |
| 7 | +from stac_fastapi.types.rfc3339 import rfc3339_str_to_datetime |
| 8 | +from stac_fastapi.core.datetime_utils import datetime_to_str |
7 | 9 |
|
8 | 10 | from stac_fastapi.sfeos_helpers.mappings import Geometry |
9 | 11 |
|
10 | 12 | ES_MAX_URL_LENGTH = 4096 |
11 | 13 |
|
12 | 14 |
|
| 15 | +def is_numeric(val: str) -> bool: |
| 16 | + try: |
| 17 | + float(val) |
| 18 | + return True |
| 19 | + except ValueError: |
| 20 | + return False |
| 21 | + |
| 22 | + |
| 23 | +def process_ftq(q: str): |
| 24 | + """Process a date, numeric, or text free-text query""" |
| 25 | + q = q.strip() |
| 26 | + if not q: |
| 27 | + return |
| 28 | + try: |
| 29 | + if d := rfc3339_str_to_datetime(q): |
| 30 | + return datetime_to_str(d) |
| 31 | + except ValueError: |
| 32 | + pass |
| 33 | + if is_numeric(q): |
| 34 | + return q |
| 35 | + else: |
| 36 | + return f"({q}* OR {q.lower()}* OR {q.upper()}*)" |
| 37 | + |
| 38 | + |
| 39 | +def apply_free_text_filter_shared( |
| 40 | + search: Any, |
| 41 | + free_text_queries: Optional[List[str]], |
| 42 | + fields: Optional[List[str]] = [], |
| 43 | +) -> Any: |
| 44 | + """Create a free text query for Elasticsearch/OpenSearch. |
| 45 | +
|
| 46 | + Args: |
| 47 | + search (Any): The search object to apply the query to. |
| 48 | + free_text_queries (Optional[List[str]]): A list of text strings to search for in the properties. |
| 49 | + fields: Optional[List[str]]: A list of fields to return |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Any: The search object with the free text query applied, or the original search |
| 53 | + object if no free_text_queries were provided. |
| 54 | +
|
| 55 | + Notes: |
| 56 | + This function creates a query_string query that searches for the specified text strings |
| 57 | + in the entire document. The query strings are joined with OR operators. |
| 58 | + """ |
| 59 | + |
| 60 | + if free_text_queries: |
| 61 | + processed_queries = [ |
| 62 | + process_ftq(q.strip()) for q in free_text_queries if q.strip() |
| 63 | + ] |
| 64 | + |
| 65 | + if processed_queries: |
| 66 | + free_text_query_string = " AND ".join(processed_queries) |
| 67 | + |
| 68 | + search = search.query( |
| 69 | + "query_string", query=free_text_query_string, fields=fields |
| 70 | + ) |
| 71 | + |
| 72 | + return search |
| 73 | + |
| 74 | + |
13 | 75 | def apply_free_text_filter_shared( |
14 | 76 | search: Any, free_text_queries: Optional[List[str]] |
15 | 77 | ) -> Any: |
|
0 commit comments