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
42 changes: 42 additions & 0 deletions solrorbit/conversion/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
Native Solr workloads should not go through this translation layer.
"""

import json
import logging
import math
import re
Expand Down Expand Up @@ -375,6 +376,11 @@ def translate_to_solr_json_dsl(body: dict) -> dict:
zone = next(iter(zones), None)
if zone and facets:
result["params"] = {"TZ": zone}
if _RELATEDNESS in json.dumps(facets):
if fq_list:
raise ValueError("significant_text over a query with filters not translated: relatedness() needs the "
"whole foreground as one query")
result["params"] = dict(result.get("params", {}), fore=q, back="*:*")

return result

Expand Down Expand Up @@ -562,6 +568,9 @@ def _date_histogram_zones(aggs):
return zones


_RELATEDNESS = "relatedness($fore,$back)"


def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict:
"""
Convert OpenSearch aggregations to Solr JSON Facet API format.
Expand All @@ -575,6 +584,7 @@ def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict:
- ``min`` → ``"min(field)"`` function expression
- ``max`` → ``"max(field)"`` function expression
- ``value_count`` → ``"countvals(field)"`` function expression
- ``significant_text`` → a terms facet sorted by ``relatedness()`` of the query against the whole collection

Nested aggregations within bucket aggs are recursively converted.
Unsupported aggregation types are skipped with a WARN log.
Expand Down Expand Up @@ -617,6 +627,35 @@ def put(key, value):
return result


def _significant_text_facet(agg_name: str, agg_def: dict) -> dict:
"""
A significant_text aggregation as a terms facet sorted by relatedness() of the query (``$fore``) against the
whole collection (``$back``), which ``translate_to_solr_json_dsl`` supplies as request parameters.

The score is not OpenSearch's JLH and no text is re-analysed; the counts and the order of the terms are what
agree. ``min_doc_count`` and ``size`` are carried when stated; each engine keeps its own defaults otherwise
(OpenSearch 3 and 10, Solr 1 and 10). Any other setting (a background filter, a heuristic, duplicate filtering) or a
sub-aggregation changes the answer in a way that was not compared, so it is refused rather than dropped.
"""
conf = agg_def["significant_text"]
unsupported = sorted(set(conf) - {"field", "size", "min_doc_count"})
if agg_def.get("aggs") or agg_def.get("aggregations"):
unsupported.append("sub-aggregations")
if unsupported:
raise ValueError("significant_text aggregation '%s' not translated: %s" % (agg_name, ", ".join(unsupported)))
field = normalize_field_name(conf.get("field", ""))
if not field:
raise ValueError("significant_text aggregation '%s' has no field" % agg_name)
facet_def = {"type": "terms", "field": field}
if "size" in conf:
facet_def["limit"] = conf["size"]
if "min_doc_count" in conf:
facet_def["mincount"] = conf["min_doc_count"]
facet_def["sort"] = "relatedness desc"
facet_def["facet"] = {"relatedness": _RELATEDNESS}
return facet_def


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 ---
Expand All @@ -637,6 +676,9 @@ def _convert_single_agg(agg_name: str, agg_def: dict, query=None):
facet_def["facet"] = sub
return facet_def

if "significant_text" in agg_def:
return _significant_text_facet(agg_name, agg_def)

if "date_histogram" in agg_def:
dh_conf = agg_def["date_histogram"]
field = normalize_field_name(dh_conf.get("field", ""))
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/solr/test_workload_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,30 @@ def test_a_parameter_spells_a_hyphenated_name_with_underscores(self):
class TestTermsFacetLimit(unittest.TestCase):
"""A terms facet carries a limit only when the aggregation states a size: both engines default to 10."""

def test_significant_text_becomes_a_terms_facet_sorted_by_relatedness(self):
body = translate_to_solr_json_dsl({"size": 0, "query": {"match": {"alternatenames": "street"}},
"aggs": {"sig": {"significant_text": {"field": "alternatenames"}}}})
self.assertEqual({"query": "alternatenames:street", "limit": 0,
"facet": {"sig": {"type": "terms", "field": "alternatenames", "sort": "relatedness desc",
"facet": {"relatedness": "relatedness($fore,$back)"}}},
"params": {"fore": "alternatenames:street", "back": "*:*"}}, body)

def test_significant_text_size_and_min_doc_count_are_carried(self):
body = translate_to_solr_json_dsl({"query": {"match": {"timezone": "America"}}, "aggs": {
"sig": {"significant_text": {"field": "alternatenames", "size": 25, "min_doc_count": 5}}}})
self.assertEqual(25, body["facet"]["sig"]["limit"])
self.assertEqual(5, body["facet"]["sig"]["mincount"])

def test_significant_text_settings_that_change_the_answer_are_refused(self):
for agg in ({"significant_text": {"field": "alternatenames", "background_filter": {"term": {"country_code": "US"}}}},
{"significant_text": {"field": "alternatenames", "filter_duplicate_text": True}},
{"significant_text": {"field": "alternatenames"}, "aggs": {"c": {"terms": {"field": "country_code"}}}}):
with self.assertRaises(ValueError, msg=agg):
translate_to_solr_json_dsl({"query": {"match_all": {}}, "aggs": {"sig": agg}})
with self.assertRaises(ValueError):
translate_to_solr_json_dsl({"query": {"bool": {"must": {"match": {"name": "x"}}, "filter": {"term": {"country_code": "US"}}}},
"aggs": {"sig": {"significant_text": {"field": "alternatenames"}}}})

def test_no_size_no_limit(self):
body = translate_to_solr_json_dsl({"size": 0, "aggs": {"c": {"terms": {"field": "country"}}}})
self.assertEqual({"type": "terms", "field": "country"}, body["facet"]["c"])
Expand Down
Loading