Skip to content

Commit 7bf41c6

Browse files
Wildcard replacement with regex
1 parent 73f6dc4 commit 7bf41c6

File tree

1 file changed

+13
-15
lines changed
  • stac_fastapi/elasticsearch/stac_fastapi/elasticsearch/extensions

1 file changed

+13
-15
lines changed

stac_fastapi/elasticsearch/stac_fastapi/elasticsearch/extensions/filter.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from __future__ import annotations
1414

1515
import datetime
16+
import re
1617
from enum import Enum
1718
from typing import List, Union
1819

@@ -252,20 +253,17 @@ def to_es(arg: Arg):
252253
raise RuntimeError(f"unknown arg {repr(arg)}")
253254

254255

255-
def cql2_like_to_es(input_string):
256-
"""Convert arugument in CQL2 ('_' and '%') to Elasticsearch wildcard operators ('?' and '*', respectively). Handle escape characters and handle Elasticsearch wildcards directly."""
257-
es_string = ""
258-
escape = False
256+
def cql2_like_to_es(string):
257+
"""Convert wildcard characters in CQL2 ('_' and '%') to Elasticsearch wildcard characters ('?' and '*', respectively). Handle escape characters and pass through Elasticsearch wildcards."""
258+
percent_pattern = r"(?<!\\)%"
259+
underscore_pattern = r"(?<!\\)_"
260+
escape_pattern = r"\\(?=[_%])"
259261

260-
for char in input_string:
261-
if char == "\\":
262-
escape = True
263-
elif char == "_" and not escape:
264-
es_string += "?"
265-
elif char == "%" and not escape:
266-
es_string += "*"
267-
else:
268-
es_string += char
269-
escape = False
262+
for pattern in [
263+
(percent_pattern, "*"),
264+
(underscore_pattern, "?"),
265+
(escape_pattern, ""),
266+
]:
267+
string = re.sub(pattern[0], pattern[1], string)
270268

271-
return es_string
269+
return string

0 commit comments

Comments
 (0)