Source code for langchain_community.query_constructors.myscale
importrefromtypingimportAny,Callable,Dict,Tuplefromlangchain_core.structured_queryimport(Comparator,Comparison,Operation,Operator,StructuredQuery,Visitor,)def_DEFAULT_COMPOSER(op_name:str)->Callable:""" Default composer for logical operators. Args: op_name: Name of the operator. Returns: Callable that takes a list of arguments and returns a string. """deff(*args:Any)->str:args_:map[str]=map(str,args)returnf" {op_name} ".join(args_)returnfdef_FUNCTION_COMPOSER(op_name:str)->Callable:""" Composer for functions. Args: op_name: Name of the function. Returns: Callable that takes a list of arguments and returns a string. """deff(*args:Any)->str:args_:map[str]=map(str,args)returnf"{op_name}({','.join(args_)})"returnf
[docs]classMyScaleTranslator(Visitor):"""Translate `MyScale` internal query language elements to valid filters."""allowed_operators=[Operator.AND,Operator.OR,Operator.NOT]"""Subset of allowed logical operators."""allowed_comparators=[Comparator.EQ,Comparator.GT,Comparator.GTE,Comparator.LT,Comparator.LTE,Comparator.CONTAIN,Comparator.LIKE,]map_dict={Operator.AND:_DEFAULT_COMPOSER("AND"),Operator.OR:_DEFAULT_COMPOSER("OR"),Operator.NOT:_DEFAULT_COMPOSER("NOT"),Comparator.EQ:_DEFAULT_COMPOSER("="),Comparator.GT:_DEFAULT_COMPOSER(">"),Comparator.GTE:_DEFAULT_COMPOSER(">="),Comparator.LT:_DEFAULT_COMPOSER("<"),Comparator.LTE:_DEFAULT_COMPOSER("<="),Comparator.CONTAIN:_FUNCTION_COMPOSER("has"),Comparator.LIKE:_DEFAULT_COMPOSER("ILIKE"),}
[docs]defvisit_comparison(self,comparison:Comparison)->Dict:regex=r"\((.*?)\)"matched=re.search(r"\(\w+\)",comparison.attribute)# If arbitrary function is applied to an attributeifmatched:attr=re.sub(regex,f"({self.metadata_key}.{matched.group(0)[1:-1]})",comparison.attribute,)else:attr=f"{self.metadata_key}.{comparison.attribute}"value=comparison.valuecomp=comparison.comparatorvalue=f"'{value}'"ifisinstance(value,str)elsevalue# convert timestamp for datetime objectsifisinstance(value,dict)andvalue.get("type")=="date":attr=f"parseDateTime32BestEffort({attr})"value=f"parseDateTime32BestEffort('{value['date']}')"# string pattern matchifcompisComparator.LIKE:value=f"'%{value[1:-1]}%'"returnself.map_dict[comp](attr,value)