Skip to content
Open
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
4 changes: 3 additions & 1 deletion docs/converter/what-converts.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ The table below summarizes which OpenSearch Benchmark constructs are automatical
| `bool` queries (`must` / `filter` / `should` / `must_not`) | Converted to Solr `bool` query parser |
| Date ranges with `format` parameter | Dates parsed per format and written as ISO 8601 |
| `terms` aggregations | Converted to Solr `terms` facet |
| `date_histogram` aggregations | Converted to Solr `range` facet with calendar gap |
| `date_histogram` aggregations | Converted to Solr `range` facet with calendar gap. `start` and `end` come from the query's range on the same field, a `fixed_interval` starts on the epoch-aligned boundary, and `time_zone` is passed as `TZ` |
| `avg` / `sum` / `min` / `max` aggregations | Converted to Solr function query stats |
| `stats` aggregations | Converted to four function facets, `<name>_min`, `<name>_max`, `<name>_sum` and `<name>_avg` |
| `index-stats` retried until `merges.current` reaches zero | → `wait-for-merges`, with the polling expressed as `retry-wait-period` and `max-wait-seconds` |

## Requires manual review
Expand All @@ -35,6 +36,7 @@ These constructs are flagged in `CONVERTED.md` but not automatically converted:
| Complex nested aggregations (3+ levels) | Auto-translation may be incomplete; verify output |
| Custom analyzers in mapping | Configset `schema.xml` must be created manually |
| `multi_match` queries | Partially converted; review field list for Solr equivalents |
| `date_histogram` without a date range on its field in the query | `start` and `end` are the placeholders `REPLACE_WITH_START` and `REPLACE_WITH_END`; set them to the data's range |

## Skipped (with TODO comment)

Expand Down
280 changes: 243 additions & 37 deletions solrorbit/conversion/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@

import logging
import re
from datetime import datetime, timedelta
from datetime import date, datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo

from .field import normalize_field_name

Expand Down Expand Up @@ -182,27 +183,7 @@ def _translate_query_node(node: dict, fq_list: list = None) -> str:
if "range" in node:
for field, bounds in node["range"].items():
field = normalize_field_name(field)
# gt/lt are exclusive; Solr spells that with a curly bracket.
if "gte" in bounds:
lo, lo_bracket, lo_key = bounds["gte"], "[", "gte"
elif "gt" in bounds:
lo, lo_bracket, lo_key = bounds["gt"], "{", "gt"
else:
lo, lo_bracket, lo_key = "*", "[", None
if "lte" in bounds:
hi, hi_bracket, hi_key = bounds["lte"], "]", "lte"
elif "lt" in bounds:
hi, hi_bracket, hi_key = bounds["lt"], "}", "lt"
else:
hi, hi_bracket, hi_key = "*", "]", None
# Convert dates if format is specified (common for date fields)
os_format = bounds.get("format")
lo, lo_is_date_only = _convert_date_to_solr_format(lo, os_format)
hi, hi_is_date_only = _convert_date_to_solr_format(hi, os_format)
if hi_is_date_only and hi_key == "lte":
hi, hi_bracket = _round_date_only_bound(hi), "}"
if lo_is_date_only and lo_key == "gt":
lo, lo_bracket = _round_date_only_bound(lo), "["
lo, lo_bracket, hi, hi_bracket = _range_bounds(bounds)
return f"{field}:{lo_bracket}{lo} TO {hi}{hi_bracket}"

if "exists" in node:
Expand Down Expand Up @@ -382,14 +363,182 @@ def translate_to_solr_json_dsl(body: dict) -> dict:

aggs = body.get("aggs") or body.get("aggregations")
if aggs and isinstance(aggs, dict):
facets = _convert_aggregations_to_facets(aggs)
zones = _date_histogram_zones(aggs)
if len(zones) > 1:
raise ValueError(
"date_histogram aggregations in one request use different time zones (%s), and Solr applies one TZ "
"to a whole request" % ", ".join(sorted(z or "none" for z in zones)))
facets = _convert_aggregations_to_facets(aggs, body.get("query"))
if facets:
result["facet"] = facets
zone = next(iter(zones), None)
if zone and facets:
result["params"] = {"TZ": zone}

return result


def _convert_aggregations_to_facets(aggs: dict) -> dict:
def _range_bounds(bounds: dict) -> tuple:
"""The (low, low bracket, high, high bracket) Solr spells for an OpenSearch range clause."""
# gt/lt are exclusive; Solr spells that with a curly bracket.
if "gte" in bounds:
lo, lo_bracket, lo_key = bounds["gte"], "[", "gte"
elif "gt" in bounds:
lo, lo_bracket, lo_key = bounds["gt"], "{", "gt"
else:
lo, lo_bracket, lo_key = "*", "[", None
if "lte" in bounds:
hi, hi_bracket, hi_key = bounds["lte"], "]", "lte"
elif "lt" in bounds:
hi, hi_bracket, hi_key = bounds["lt"], "}", "lt"
else:
hi, hi_bracket, hi_key = "*", "]", None
# Convert dates if format is specified (common for date fields)
os_format = bounds.get("format")
lo, lo_is_date_only = _convert_date_to_solr_format(lo, os_format)
hi, hi_is_date_only = _convert_date_to_solr_format(hi, os_format)
if hi_is_date_only and hi_key == "lte":
hi, hi_bracket = _round_date_only_bound(hi), "}"
if lo_is_date_only and lo_key == "gt":
lo, lo_bracket = _round_date_only_bound(lo), "["
return lo, lo_bracket, hi, hi_bracket


def _date_bounds_for_field(query, field: str):
"""
The (start, end, end is inclusive) of the range the query puts on ``field``, or None.

OpenSearch derives a date_histogram's span from the data; a Solr range facet needs it
spelled out. The query's own range on the aggregated field is the span the buckets cover.
"""
if not isinstance(query, dict):
return None
if "range" in query and isinstance(query["range"], dict):
for name, bounds in query["range"].items():
if normalize_field_name(name) == field and isinstance(bounds, dict):
lo, _, hi, hi_bracket = _range_bounds(bounds)
if _SOLR_INSTANT.fullmatch(str(lo)) and _SOLR_INSTANT.fullmatch(str(hi)):
return lo, hi, hi_bracket == "]"
return None
bool_q = query.get("bool")
if isinstance(bool_q, dict):
for key in ("must", "filter"):
clauses = bool_q.get(key) or []
for clause in [clauses] if isinstance(clauses, dict) else clauses:
found = _date_bounds_for_field(clause, field)
if found:
return found
return None


def _parse_instant(value: str) -> datetime:
"""A naive UTC datetime from a Solr instant, with or without fractional seconds."""
text = value[:-1]
return datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f" if "." in text else "%Y-%m-%dT%H:%M:%S")


def _format_instant(moment: datetime) -> str:
"""A Solr instant; milliseconds are written only when there are some."""
base = moment.strftime("%Y-%m-%dT%H:%M:%S")
millis = moment.microsecond // 1000
return "%s.%03dZ" % (base, millis) if millis else base + "Z"


_FIXED_UNIT_MS = {"ms": 1, "s": 1000, "m": 60000, "h": 3600000, "d": 86400000}


def _align_to_epoch(start: str, interval: str):
"""
``start`` moved down to a multiple of a fixed interval counted from the epoch.

A fixed_interval's buckets are aligned to 1970-01-01, not to the start of the range, so
``60d`` over 2015 begins at 2014-11-06. A Solr range facet starts where it is told to.
Integer milliseconds throughout: a float step moves exact boundaries.
"""
match = re.fullmatch(r"(\d*)(ms|[smhd])", str(interval).strip())
if not match:
return None
step = int(match.group(1) or 1) * _FIXED_UNIT_MS[match.group(2)]
if step <= 0:
return None
epoch = datetime(1970, 1, 1)
elapsed = (_parse_instant(start) - epoch) // timedelta(milliseconds=1)
return _format_instant(epoch + timedelta(milliseconds=(elapsed // step) * step))


def _floor_calendar(start: str, gap: str):
"""``start`` rounded down to the calendar unit of ``gap`` in UTC (weeks begin on Monday), or None."""
moment = _parse_instant(start)
if gap == "+1MINUTE":
moment = moment.replace(second=0, microsecond=0)
elif gap == "+1HOUR":
moment = moment.replace(minute=0, second=0, microsecond=0)
elif gap == "+1DAY":
moment = moment.replace(hour=0, minute=0, second=0, microsecond=0)
elif gap == "+7DAYS":
moment = (moment - timedelta(days=moment.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
elif gap == "+1MONTH":
moment = moment.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif gap == "+3MONTHS":
moment = moment.replace(month=3 * ((moment.month - 1) // 3) + 1, day=1, hour=0, minute=0, second=0, microsecond=0)
elif gap == "+1YEAR":
moment = moment.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
else:
return None
return _format_instant(moment)


_CALENDAR_ROUNDING = {"+1YEAR": "YEAR", "+1MONTH": "MONTH", "+1DAY": "DAY", "+1HOUR": "HOUR", "+1MINUTE": "MINUTE"}


def _fixed_ranges_in_zone(start: str, end: str, interval: str, zone: str, inclusive: bool = False):
"""
Explicit ranges for a day-based fixed_interval in a named zone, or None.

The UTC offset changes inside the range, so the buckets are N days of local calendar time
(counted from 1970-01-01 local) and no single Solr gap describes them. A range is opened for an
inclusive end that falls exactly on a bucket edge.
"""
match = re.fullmatch(r"(\d*)d", str(interval).strip())
if not match or not int(match.group(1) or 1):
return None
step = int(match.group(1) or 1)
try:
tz = ZoneInfo(zone)
except Exception: # pylint: disable=broad-except
return None
local_start = _parse_instant(start).replace(tzinfo=timezone.utc).astimezone(tz)
last = _parse_instant(end)
epoch = date(1970, 1, 1)
edge = epoch + timedelta(days=((local_start.date() - epoch).days // step) * step)

def utc(day):
return datetime.combine(day, time()).replace(tzinfo=tz).astimezone(timezone.utc).replace(tzinfo=None)

ranges = []
while True:
opens = utc(edge)
if opens > last or (opens == last and not inclusive):
break
ranges.append({"from": _format_instant(opens), "to": _format_instant(utc(edge + timedelta(days=step))),
"inclusive_from": True, "inclusive_to": False})
edge += timedelta(days=step)
return ranges or None


def _date_histogram_zones(aggs):
"""The set of time_zone values (None for a histogram without one) of every date_histogram in ``aggs``."""
zones = set()
for agg in (aggs or {}).values():
if not isinstance(agg, dict):
continue
if "date_histogram" in agg:
zones.add((agg["date_histogram"] or {}).get("time_zone"))
zones |= _date_histogram_zones(agg.get("aggs") or agg.get("aggregations"))
return zones


def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict:
"""
Convert OpenSearch aggregations to Solr JSON Facet API format.

Expand All @@ -408,6 +557,7 @@ def _convert_aggregations_to_facets(aggs: dict) -> dict:

Args:
aggs: OpenSearch aggregations dict (the value of "aggs" or "aggregations")
query: the operation's OpenSearch query, which gives a date_histogram its start and end

Returns:
Solr JSON Facet API dict suitable for the ``"facet"`` key in JSON Query DSL
Expand All @@ -416,17 +566,34 @@ def _convert_aggregations_to_facets(aggs: dict) -> dict:
return {}

result = {}

def put(key, value):
if key in result:
raise ValueError("aggregation name '%s' is used twice in the converted facets (a stats aggregation "
"also produces <name>_min, _max, _sum and _avg)" % key)
result[key] = value

for agg_name, agg_def in aggs.items():
if not isinstance(agg_def, dict):
continue
entry = _convert_single_agg(agg_name, agg_def)
if "stats" in agg_def:
# `stats` is four numbers in OpenSearch and four function facets in Solr: <name>_min ... <name>_avg.
field = normalize_field_name(agg_def["stats"].get("field", ""))
if field:
for stat in ("min", "max", "sum", "avg"):
if f"{agg_name}_{stat}" in aggs:
raise ValueError("stats aggregation '%s' would overwrite the aggregation '%s_%s'"
% (agg_name, agg_name, stat))
put(f"{agg_name}_{stat}", f"{stat}({field})")
continue
entry = _convert_single_agg(agg_name, agg_def, query)
if entry is not None:
result[agg_name] = entry
put(agg_name, entry)

return result


def _convert_single_agg(agg_name: str, agg_def: dict):
def _convert_single_agg(agg_name: str, agg_def: dict, query=None):
"""Convert a single named OpenSearch aggregation to a Solr facet entry."""
# --- bucket aggregations ---
if "terms" in agg_def:
Expand All @@ -442,7 +609,7 @@ def _convert_single_agg(agg_name: str, agg_def: dict):
}
nested = agg_def.get("aggs") or agg_def.get("aggregations")
if nested:
sub = _convert_aggregations_to_facets(nested)
sub = _convert_aggregations_to_facets(nested, query)
if sub:
facet_def["facet"] = sub
return facet_def
Expand All @@ -454,17 +621,53 @@ def _convert_single_agg(agg_name: str, agg_def: dict):
logger.warning("date_histogram agg '%s' has no field — skipping", agg_name)
return None
gap = _date_histogram_gap(dh_conf, agg_name)
facet_def = {
"type": "range",
"field": field,
"gap": gap,
"mincount": 1,
"start": "NOW/YEAR-10YEAR",
"end": "NOW/YEAR+1YEAR",
}
bounds = _date_bounds_for_field(query, field)
zone = dh_conf.get("time_zone")
inclusive = False
if bounds:
start, end, inclusive = bounds
if "fixed_interval" in dh_conf:
start = _align_to_epoch(start, dh_conf["fixed_interval"]) or start
elif not zone:
start = _floor_calendar(start, gap) or start
else:
logger.warning(
"date_histogram agg '%s' has no date range on '%s' in its query: start and end "
"are placeholders that must be set to the data's range before the operation runs.",
agg_name, field)
start, end = "REPLACE_WITH_START", "REPLACE_WITH_END"
ranges, in_zone = None, False
if zone and bounds:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4db7c4b: without a zone the start is rounded down to the unit in UTC; weeks start on Monday, quarters on the quarter. Zoned weeks and quarters still warn.

if "fixed_interval" in dh_conf:
ranges = _fixed_ranges_in_zone(bounds[0], bounds[1], dh_conf["fixed_interval"], zone, inclusive)
in_zone = bool(ranges)
elif gap in _CALENDAR_ROUNDING:
# Solr rounds date math in the request's TZ; the end is rounded first, then one gap added
# (which also covers an inclusive end that falls on a bucket edge).
unit = _CALENDAR_ROUNDING[gap]
start, end = f"{start}/{unit}", f"{end}/{unit}{gap}"
in_zone = True
inclusive = False
if zone and not in_zone:
logger.warning("date_histogram agg '%s': time_zone '%s' could not be applied; buckets are in UTC",
agg_name, zone)
if inclusive and bounds and not ranges:
# An inclusive upper bound that falls on a bucket edge belongs to the bucket that starts there.
end = f"{end}{gap}"
if ranges:
facet_def = {"type": "range", "field": field, "mincount": 1, "ranges": ranges}
else:
facet_def = {
"type": "range",
"field": field,
"gap": gap,
"mincount": 1,
"start": start,
"end": end,
}
nested = agg_def.get("aggs") or agg_def.get("aggregations")
if nested:
sub = _convert_aggregations_to_facets(nested)
sub = _convert_aggregations_to_facets(nested, query)
if sub:
facet_def["facet"] = sub
return facet_def
Expand Down Expand Up @@ -647,6 +850,9 @@ def _convert_date_to_solr_format(date_str, os_format=None) -> tuple:
return date_str, False


_SOLR_INSTANT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z")


def _round_date_only_bound(value: str) -> str:
"""
Advance a whole-day bound to the start of the following day.
Expand Down
Loading
Loading