From 041b9497bc86abb329826d353f579be88bfde95a Mon Sep 17 00:00:00 2001 From: Serhiy Bzhezytskyy Date: Mon, 30 Nov 2026 19:57:23 +0200 Subject: [PATCH] Translate function_score with one function over match_all into a Solr function query A converted function_score became q=*:*, so the operation matched every document with a constant score and measured none of the scoring. A function_score whose query is match_all, or absent, and that has a single field_value_factor (any modifier) or a gauss, exp or linear decay on a geo point now becomes {!func} with the same function. Each form was compared with OpenSearch document by document. Anything else (several functions, weight, missing, numeric or date decays, a scoring inner query) stays untranslated with the warning. --- solrorbit/conversion/query.py | 90 +++++++++++++++++++++- tests/unit/solr/test_workload_converter.py | 48 ++++++++++++ 2 files changed, 137 insertions(+), 1 deletion(-) diff --git a/solrorbit/conversion/query.py b/solrorbit/conversion/query.py index 32a97f4e..c21df087 100644 --- a/solrorbit/conversion/query.py +++ b/solrorbit/conversion/query.py @@ -319,6 +319,90 @@ def _escape_solr_phrase(value) -> str: return str(value).replace('\\', '\\\\').replace('"', '\\"') +_FVF_MODIFIERS = { + "none": "{x}", "log": "log({x})", "log1p": "log(sum({x},1))", "log2p": "log(sum({x},2))", + "ln": "ln({x})", "ln1p": "ln(sum({x},1))", "ln2p": "ln(sum({x},2))", + "square": "pow({x},2)", "sqrt": "sqrt({x})", "reciprocal": "recip({x},1,1,0)", +} +_DISTANCE_TO_KM = {"km": 1.0, "m": 0.001, "mi": 1.609344} + + +def _num(value) -> str: + """A number as Solr reads it: an integral value without a fraction, otherwise Python's shortest repr.""" + value = float(value) + return str(int(value)) if value.is_integer() else repr(value) + + +def _distance_km(value): + m = re.fullmatch(r"\s*([0-9.]+)\s*(km|mi|m)?\s*", str(value)) + if not m: + return None + return float(m.group(1)) * _DISTANCE_TO_KM[m.group(2) or "m"] + + +def _geo_origin(origin): + """lat,lon of an OpenSearch geo origin given as "lat, lon", {"lat": .., "lon": ..} or [lon, lat]; None otherwise.""" + if isinstance(origin, str): + parts = [p.strip() for p in origin.split(",")] + if len(parts) == 2 and all(re.fullmatch(r"-?[0-9.]+", p) for p in parts): + return "%s,%s" % tuple(parts) + return None + if isinstance(origin, dict) and {"lat", "lon"} <= set(origin): + return "%s,%s" % (_num(origin["lat"]), _num(origin["lon"])) + if isinstance(origin, list) and len(origin) == 2: + return "%s,%s" % (_num(origin[1]), _num(origin[0])) + return None + + +def _function_score_to_func(fs: dict): + """ + The Solr function query of an OpenSearch ``function_score`` with one function over ``match_all``, or None. + + Translated (each row measured per document against OpenSearch): ``field_value_factor`` with any modifier, and + ``gauss`` / ``exp`` / ``linear`` decays on a geo point. With ``match_all`` as the query every document scores 1, + so ``boost_mode`` does not change the result. Anything else (several functions, ``weight``, ``missing``, numeric + or date decays, a scoring inner query) returns None and is reported as untranslated. + """ + inner = fs.get("query", {"match_all": {}}) + if set(fs) - {"query", "field_value_factor", "gauss", "exp", "linear", "boost_mode"} or \ + not (isinstance(inner, dict) and set(inner) == {"match_all"}): + return None + functions = [k for k in ("field_value_factor", "gauss", "exp", "linear") if k in fs] + if len(functions) != 1: + return None + name, conf = functions[0], fs[functions[0]] + if name == "field_value_factor": + if set(conf) - {"field", "factor", "modifier"} or "field" not in conf: + return None + modifier = _FVF_MODIFIERS.get(conf.get("modifier", "none")) + if modifier is None: + return None + field = normalize_field_name(conf["field"]) + factor = conf.get("factor", 1) + x = field if float(factor) == 1.0 else "product(%s,%s)" % (field, _num(factor)) + return modifier.format(x=x) + if not isinstance(conf, dict) or len(conf) != 1: + return None + (field, params), = conf.items() + if not isinstance(params, dict) or set(params) - {"origin", "scale", "offset", "decay"}: + return None + origin = _geo_origin(params.get("origin")) + scale = _distance_km(params.get("scale")) + offset = _distance_km(params.get("offset", "0km")) + decay = float(params.get("decay", 0.5)) + if origin is None or not scale or offset is None or not 0 < decay < 1: + return None + d = "geodist(%s,%s)" % (normalize_field_name(field), origin) + if offset: + d = "max(sub(%s,%s),0)" % (d, _num(offset)) + if name == "gauss": + return "exp(div(product(-1,pow(%s,2)),%r))" % (d, -scale * scale / math.log(decay)) + if name == "exp": + return "exp(product(%r,%s))" % (math.log(decay) / scale, d) + s_lin = scale / (1.0 - decay) + return "max(div(sub(%r,%s),%r),0)" % (s_lin, d, s_lin) + + def translate_to_solr_json_dsl(body: dict) -> dict: """ Translate an OpenSearch query body to Solr JSON Query DSL format. @@ -343,7 +427,11 @@ def translate_to_solr_json_dsl(body: dict) -> dict: fq_list = [] query_val = body.get("query") - if isinstance(query_val, dict): + func = (_function_score_to_func(query_val["function_score"]) + if isinstance(query_val, dict) and set(query_val) == {"function_score"} else None) + if func: + q = "{!func}" + func + elif isinstance(query_val, dict): translated = translate_opensearch_query(body) q = translated["q"] fq_list = translated["fq"] diff --git a/tests/unit/solr/test_workload_converter.py b/tests/unit/solr/test_workload_converter.py index db47c5ee..0eeb0051 100644 --- a/tests/unit/solr/test_workload_converter.py +++ b/tests/unit/solr/test_workload_converter.py @@ -18,6 +18,7 @@ """Unit tests for solrorbit/conversion/workload_converter.py""" import json +import math import os import tempfile import unittest @@ -959,3 +960,50 @@ def test_conversion_end_to_end(self): if __name__ == "__main__": unittest.main() + + +class TestFunctionScore(unittest.TestCase): + """function_score with one function over match_all becomes a Solr function query; each row was compared per document.""" + + @staticmethod + def _q(fs): + return translate_to_solr_json_dsl({"query": {"function_score": fs}})["query"] + + def test_field_value_factor_modifiers(self): + x = "product(population,1.2)" + expected = {"none": x, "log": f"log({x})", "log1p": f"log(sum({x},1))", "log2p": f"log(sum({x},2))", + "ln": f"ln({x})", "ln1p": f"ln(sum({x},1))", "ln2p": f"ln(sum({x},2))", + "square": f"pow({x},2)", "sqrt": f"sqrt({x})", "reciprocal": f"recip({x},1,1,0)"} + for modifier, expr in expected.items(): + fvf = {"field": "population", "factor": 1.2, "modifier": modifier} + self.assertEqual("{!func}" + expr, self._q({"query": {"match_all": {}}, "field_value_factor": fvf}), modifier) + + def test_a_factor_of_one_is_the_field(self): + self.assertEqual("{!func}ln(population)", self._q({"field_value_factor": {"field": "population", "modifier": "ln"}})) + + def test_geo_gauss_without_offset(self): + self.assertEqual("{!func}exp(div(product(-1,pow(geodist(location,52.37,4.8951),2)),108573.62047581296))", + self._q({"query": {"match_all": {}}, + "gauss": {"location": {"origin": "52.37, 4.8951", "scale": "500km", "offset": "0km", "decay": 0.1}}})) + + def test_geo_decays_with_offset(self): + params = {"location": {"origin": {"lat": 52.37, "lon": 4.8951}, "scale": "500km", "offset": "50km", "decay": 0.1}} + d = "max(sub(geodist(location,52.37,4.8951),50),0)" + self.assertEqual("{!func}exp(div(product(-1,pow(%s,2)),%r))" % (d, -250000 / math.log(0.1)), self._q({"gauss": params})) + self.assertEqual("{!func}exp(product(%r,%s))" % (math.log(0.1) / 500, d), self._q({"exp": params})) + self.assertEqual("{!func}max(div(sub(%r,%s),%r),0)" % (500 / 0.9, d, 500 / 0.9), self._q({"linear": params})) + + def test_distance_units_and_a_lon_lat_array(self): + q = self._q({"gauss": {"location": {"origin": [4.8951, 52.37], "scale": "500000m", "decay": 0.5}}}) + self.assertIn("geodist(location,52.37,4.8951)", q) + self.assertIn(repr(-250000 / math.log(0.5)), q) + self.assertIn(repr(-(1.609344 ** 2) / math.log(0.5)), self._q({"gauss": {"location": {"origin": "1, 2", "scale": "1mi", "decay": 0.5}}})) + + def test_what_was_not_measured_is_not_translated(self): + for fs in ({"query": {"match": {"name": "x"}}, "field_value_factor": {"field": "f"}}, + {"functions": [{"field_value_factor": {"field": "f"}}]}, + {"field_value_factor": {"field": "f", "missing": 1}}, + {"field_value_factor": {"field": "f"}, "weight": 2}, + {"gauss": {"price": {"origin": 10, "scale": 5}}}): + self.assertEqual("*:*", self._q(fs), fs) +