diff --git a/docs/converter/what-converts.md b/docs/converter/what-converts.md index fdaeeed2..0a7978b6 100644 --- a/docs/converter/what-converts.md +++ b/docs/converter/what-converts.md @@ -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, `_min`, `_max`, `_sum` and `_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 @@ -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) diff --git a/solrorbit/conversion/query.py b/solrorbit/conversion/query.py index cf6b16ba..f832fa34 100644 --- a/solrorbit/conversion/query.py +++ b/solrorbit/conversion/query.py @@ -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 @@ -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: @@ -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. @@ -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 @@ -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 _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: _min ... _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: @@ -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 @@ -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: + 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 @@ -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. diff --git a/tests/unit/solr/test_workload_converter.py b/tests/unit/solr/test_workload_converter.py index 6d5755d1..004608c9 100644 --- a/tests/unit/solr/test_workload_converter.py +++ b/tests/unit/solr/test_workload_converter.py @@ -469,6 +469,160 @@ def test_calendar_month_abbreviation_is_not_a_minute(self): self.assertEqual("+1MONTH", gap) +class TestDateHistogramFacetBounds(unittest.TestCase): + def _facet(self, date_histogram, range_clause): + body = { + "query": range_clause, + "aggs": {"dropoffs_over_time": {"date_histogram": date_histogram}}, + } + return translate_to_solr_json_dsl(body)["facet"]["dropoffs_over_time"] + + def _range(self, **bounds): + return {"range": {"dropoff_datetime": bounds}} + + def test_bounds_come_from_the_query_range_on_the_same_field(self): + facet = self._facet( + {"field": "dropoff_datetime", "calendar_interval": "month"}, + self._range(gte="2015-01-01 00:00:00", lt="2016-01-01 00:00:00", format="yyyy-MM-dd HH:mm:ss")) + self.assertEqual("2015-01-01T00:00:00Z", facet["start"]) + self.assertEqual("2016-01-01T00:00:00Z", facet["end"]) + + def test_bounds_are_found_inside_bool_filter(self): + clause = {"bool": {"filter": [self._range(gte="2015-01-01", lte="2015-01-21", format="yyyy-MM-dd")]}} + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "day"}, clause) + self.assertEqual("2015-01-01T00:00:00Z", facet["start"]) + self.assertEqual("2015-01-22T00:00:00Z", facet["end"]) + + def test_fixed_interval_starts_where_the_engine_aligns_it(self): + facet = self._facet( + {"field": "dropoff_datetime", "fixed_interval": "60d"}, + self._range(gte="2015-01-01 00:00:00", lt="2016-01-01 00:00:00", format="yyyy-MM-dd HH:mm:ss")) + self.assertEqual("2014-11-06T00:00:00Z", facet["start"]) + + def test_range_on_another_field_is_not_used(self): + clause = {"range": {"fare_amount": {"gte": 1, "lt": 5}}} + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "month"}, clause) + self.assertEqual("REPLACE_WITH_START", facet["start"]) + + def test_no_range_leaves_a_placeholder_and_says_so(self): + with self.assertLogs("solrorbit.conversion.query", level="WARNING") as log: + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "month"}, {"match_all": {}}) + self.assertEqual("REPLACE_WITH_START", facet["start"]) + self.assertEqual("REPLACE_WITH_END", facet["end"]) + self.assertTrue(any("dropoffs_over_time" in msg for msg in log.output)) + + def test_date_math_bounds_are_not_taken_as_dates(self): + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "month"}, + self._range(gte="now-30d", lt="now")) + self.assertEqual("REPLACE_WITH_START", facet["start"]) + + +class TestDateHistogramTimeZoneAndStats(unittest.TestCase): + QUERY = {"range": {"dropoff_datetime": {"gte": "2015-01-01 00:00:00", "lt": "2016-01-01 00:00:00", + "format": "yyyy-MM-dd HH:mm:ss"}}} + + def _convert(self, date_histogram, sub_aggs=None): + agg = {"date_histogram": dict({"field": "dropoff_datetime"}, **date_histogram)} + if sub_aggs: + agg["aggs"] = sub_aggs + return translate_to_solr_json_dsl({"query": self.QUERY, "aggs": {"over_time": agg}}) + + def test_calendar_interval_in_a_zone_rounds_in_that_zone(self): + result = self._convert({"calendar_interval": "month", "time_zone": "America/New_York"}) + facet = result["facet"]["over_time"] + self.assertEqual({"TZ": "America/New_York"}, result["params"]) + self.assertEqual("2015-01-01T00:00:00Z/MONTH", facet["start"]) + self.assertEqual("2016-01-01T00:00:00Z/MONTH+1MONTH", facet["end"]) + + def test_fixed_interval_in_a_zone_follows_the_offset_change(self): + facet = self._convert({"fixed_interval": "60d", "time_zone": "America/New_York"})["facet"]["over_time"] + edges = [(r["from"], r["to"]) for r in facet["ranges"]] + self.assertEqual(8, len(edges)) + self.assertEqual(("2014-11-06T05:00:00Z", "2015-01-05T05:00:00Z"), edges[0]) + # 2015-05-05 is after the clocks change: local midnight is 04:00Z, not 05:00Z + self.assertEqual("2015-05-05T04:00:00Z", edges[2][1]) + self.assertEqual("2015-12-31T05:00:00Z", edges[7][0]) + + def test_no_time_zone_adds_no_params(self): + self.assertNotIn("params", self._convert({"calendar_interval": "month"})) + + def test_stats_becomes_four_function_facets(self): + facet = self._convert({"fixed_interval": "60d"}, {"total_amount": {"stats": {"field": "total_amount"}}} + )["facet"]["over_time"]["facet"] + self.assertEqual({"total_amount_min": "min(total_amount)", "total_amount_max": "max(total_amount)", + "total_amount_sum": "sum(total_amount)", "total_amount_avg": "avg(total_amount)"}, facet) + + +class TestDateHistogramReviewCases(unittest.TestCase): + """Edges of the bounds / time_zone / stats conversion that a review reproduced.""" + + def _range(self, lo, hi, op="lt"): + return {"range": {"dropoff_datetime": {"gte": lo, op: hi}}} + + def _convert(self, query, aggs): + return translate_to_solr_json_dsl({"query": query, "aggs": aggs}) + + def _hist(self, **conf): + return {"date_histogram": dict({"field": "dropoff_datetime"}, **conf)} + + def test_two_time_zones_in_one_request_are_refused(self): + aggs = {"ny": self._hist(calendar_interval="month", time_zone="America/New_York"), + "paris": self._hist(calendar_interval="month", time_zone="Europe/Paris")} + with self.assertRaises(ValueError): + self._convert(self._range("2015-01-01T00:00:00Z", "2016-01-01T00:00:00Z"), aggs) + + def test_a_zoned_and_an_unzoned_histogram_in_one_request_are_refused(self): + aggs = {"utc": self._hist(calendar_interval="month"), + "ny": self._hist(calendar_interval="month", time_zone="America/New_York")} + with self.assertRaises(ValueError): + self._convert(self._range("2015-01-01T00:00:00Z", "2016-01-01T00:00:00Z"), aggs) + + def test_inclusive_upper_bound_on_a_bucket_edge_gets_the_bucket_that_starts_there(self): + facet = self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-02T00:00:00Z", "lte"), + {"d": self._hist(fixed_interval="1d")})["facet"]["d"] + self.assertEqual("2015-01-02T00:00:00Z+1DAY", facet["end"]) + + def test_exclusive_upper_bound_keeps_its_end(self): + facet = self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-02T00:00:00Z"), + {"d": self._hist(fixed_interval="1d")})["facet"]["d"] + self.assertEqual("2015-01-02T00:00:00Z", facet["end"]) + + def test_inclusive_end_on_an_edge_opens_one_more_zoned_range(self): + ranges = self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-05T05:00:00Z", "lte"), + {"d": self._hist(fixed_interval="60d", time_zone="America/New_York")})["facet"]["d"]["ranges"] + self.assertEqual("2015-01-05T05:00:00Z", ranges[-1]["from"]) + + def test_millisecond_fixed_intervals_align_in_integer_milliseconds(self): + facet = lambda interval: self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-02T00:00:00Z"), + {"d": self._hist(fixed_interval=interval)})["facet"]["d"]["start"] + self.assertEqual("2015-01-01T00:00:00Z", facet("1ms")) + self.assertEqual("2014-12-31T23:51:14.048Z", facet("2699999ms")) + + def test_stats_does_not_overwrite_a_sibling_aggregation(self): + for aggs in ({"fare": {"stats": {"field": "fare_amount"}}, "fare_avg": {"avg": {"field": "tip_amount"}}}, + {"fare_avg": {"avg": {"field": "tip_amount"}}, "fare": {"stats": {"field": "fare_amount"}}}): + with self.assertRaises(ValueError): + self._convert({"match_all": {}}, aggs) + + def test_calendar_intervals_start_on_their_unit_in_utc(self): + start = lambda lo, interval: self._convert(self._range(lo, "2016-06-01T00:00:00Z"), + {"d": self._hist(calendar_interval=interval)})["facet"]["d"]["start"] + self.assertEqual("2015-01-01T00:00:00Z", start("2015-01-15T12:00:00Z", "month")) + self.assertEqual("2015-01-12T00:00:00Z", start("2015-01-15T12:00:00Z", "week")) # a Monday + self.assertEqual("2015-01-01T00:00:00Z", start("2015-02-10T00:00:00Z", "quarter")) + self.assertEqual("2015-01-01T00:00:00Z", start("2015-05-17T08:30:00Z", "year")) + self.assertEqual("2015-01-01T00:00:00Z", start("2015-01-01T00:00:00Z", "month")) # already on the edge + + def test_fractional_second_bounds_are_accepted(self): + facet = self._convert(self._range("2015-01-01T00:00:00.000Z", "2016-01-01T00:00:00.000Z"), + {"d": self._hist(calendar_interval="month")})["facet"]["d"] + self.assertEqual("2015-01-01T00:00:00Z", facet["start"]) + self.assertNotIn("REPLACE", facet["end"]) + ranges = self._convert(self._range("2015-01-01T00:00:00.500Z", "2016-01-01T00:00:00.000Z"), + {"d": self._hist(fixed_interval="60d", time_zone="America/New_York")})["facet"]["d"]["ranges"] + self.assertEqual("2014-11-06T05:00:00Z", ranges[0]["from"]) + + class TestSearchBodiesWithoutAQuery(unittest.TestCase): def _convert(self, body): op = {"name": "country_agg", "operation-type": "search", "body": body}