From edd88af99195faec9a6ac0636f800973555dfe60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jaworski?= Date: Wed, 4 Apr 2018 17:39:09 +0200 Subject: [PATCH] add support for constant score queries with API suggested by @eforestier (refs #6) --- src/solrq/__init__.py | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/solrq/__init__.py b/src/solrq/__init__.py index d3f8c30..e9a2d43 100644 --- a/src/solrq/__init__.py +++ b/src/solrq/__init__.py @@ -337,6 +337,38 @@ def boost(cls, qs_list, factor): return "{qs}^{factor}".format(qs=qs_list[0], factor=factor) + @classmethod + def constant_score(cls, qs_list, score): + """Perform constant score operator routine. + + Args: + qs_list (iterable): single element list with compiled query string + score (float or int): constant score value + + Returns: + str: compiled query string followed with '^=' and score value. + + Note: + this operator routine is not intended to be directly used as + :class:`Q` object argument but rather as a component for actual + operator e.g: + + >>> from functools import partial + >>> Q(children=[Q(a='b')], op=partial(QOperator.constant_score, score=2)) + + """ # noqa + if len(qs_list) != 1: + raise ValueError( + " operator can receive only single Q object" + ) + + if not isinstance(score, (int, float)): + raise TypeError( + "score must be either int or float" + ) + + return "{qs}^={score}".format(qs=qs_list[0], score=score) + class Q(object): """Class for handling Solr queries in a semantic way. @@ -483,6 +515,28 @@ def __xor__(self, other): op=partial(QOperator.boost, factor=other) ) + def constant_score(self, other): + """Build complex query using Solr constant score operator. + + Args: + other (float or int): constant score value. + + Returns: + Q: object representing Solr query with assinged constant score. + + Examples: + + >>> Q(type="animal").constant_score(2) + + >>> (Q(type="animal") | Q(name="cat")).constant_score(1.0) + + + """ + return Q( + children=[self], + op=partial(QOperator.constant_score, score=other) + ) + def compile(self, extra_parenthesis=False): """Compile :class:`Q` object into query string.