diff --git a/elasticsearch_dsl/interfaces.py b/elasticsearch_dsl/interfaces.py index 67a6eafe..16b4b097 100644 --- a/elasticsearch_dsl/interfaces.py +++ b/elasticsearch_dsl/interfaces.py @@ -15,476 +15,1995 @@ # specific language governing permissions and limitations # under the License. -from typing import Any, List, Literal, Mapping, TypedDict, Union +from typing import Any, Dict, List, Literal, Mapping, Union from elasticsearch_dsl import Query, analysis, function from elasticsearch_dsl import interfaces as i -from elasticsearch_dsl.search_base import InstrumentedField +from elasticsearch_dsl.document_base import InstrumentedField +from elasticsearch_dsl.utils import NOT_SET, AttrDict, NotSet PipeSeparatedFlags = str -class QueryBase(TypedDict): - boost: float - _name: str - - -class MatchPhrasePrefixQuery(QueryBase): - analyzer: str - max_expansions: int - query: str - slop: int - zero_terms_query: Literal["all", "none"] +class QueryBase(AttrDict[Any]): + """ + :arg boost: Floating point number used to decrease or increase the + relevance scores of the query. Boost values are relative to the + default value of 1.0. A boost value between 0 and 1.0 decreases + the relevance score. A value greater than 1.0 increases the + relevance score. + :arg _name: No documentation available. + """ + + def __init__( + self, + *, + boost: Union[float, "NotSet"] = NOT_SET, + _name: Union[str, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if boost != NOT_SET: + kwargs["boost"] = boost + if _name != NOT_SET: + kwargs["_name"] = _name + super().__init__(kwargs) + + +class DistanceFeatureQueryBase(QueryBase): + """ + :arg origin: (required)Date or point of origin used to calculate + distances. If the `field` value is a `date` or `date_nanos` field, + the `origin` value must be a date. Date Math, such as `now-1h`, is + supported. If the field value is a `geo_point` field, the `origin` + value must be a geopoint. + :arg pivot: (required)Distance from the `origin` at which relevance + scores receive half of the `boost` value. If the `field` value is + a `date` or `date_nanos` field, the `pivot` value must be a time + unit, such as `1h` or `10d`. If the `field` value is a `geo_point` + field, the `pivot` value must be a distance unit, such as `1km` or + `12m`. + :arg field: (required)Name of the field used to calculate distances. + This field must meet the following criteria: be a `date`, + `date_nanos` or `geo_point` field; have an `index` mapping + parameter value of `true`, which is the default; have an + `doc_values` mapping parameter value of `true`, which is the + default. + """ + + def __init__( + self, + *, + origin: Any, + pivot: Any, + field: Union[str, "InstrumentedField", "NotSet"], + **kwargs: Any, + ): + if origin != NOT_SET: + kwargs["origin"] = origin + if pivot != NOT_SET: + kwargs["pivot"] = pivot + if field != NOT_SET: + kwargs["field"] = str(field) + super().__init__(**kwargs) + + +class DateDistanceFeatureQuery(DistanceFeatureQueryBase): + pass -class MatchPhraseQuery(QueryBase): - analyzer: str - query: str - slop: int - zero_terms_query: Literal["all", "none"] +class PrefixQuery(QueryBase): + """ + :arg rewrite: Method used to rewrite the query. + :arg value: (required)Beginning characters of terms you wish to find + in the provided field. + :arg case_insensitive: Allows ASCII case insensitive matching of the + value with the indexed field values when set to `true`. Default is + `false` which means the case sensitivity of matching depends on + the underlying field’s mapping. + """ + + def __init__( + self, + *, + rewrite: Union[str, "NotSet"] = NOT_SET, + value: Union[str, "NotSet"], + case_insensitive: Union[bool, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if rewrite != NOT_SET: + kwargs["rewrite"] = rewrite + if value != NOT_SET: + kwargs["value"] = value + if case_insensitive != NOT_SET: + kwargs["case_insensitive"] = case_insensitive + super().__init__(**kwargs) + + +class QueryVectorBuilder(AttrDict[Any]): + """ + :arg text_embedding: No documentation available. + """ + + def __init__( + self, + *, + text_embedding: Union["i.TextEmbedding", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if text_embedding != NOT_SET: + kwargs["text_embedding"] = text_embedding + super().__init__(kwargs) + + +class TokenPruningConfig(AttrDict[Any]): + """ + :arg tokens_freq_ratio_threshold: Tokens whose frequency is more than + this threshold times the average frequency of all tokens in the + specified field are considered outliers and pruned. + :arg tokens_weight_threshold: Tokens whose weight is less than this + threshold are considered nonsignificant and pruned. + :arg only_score_pruned_tokens: Whether to only score pruned tokens, vs + only scoring kept tokens. + """ + + def __init__( + self, + *, + tokens_freq_ratio_threshold: Union[int, "NotSet"] = NOT_SET, + tokens_weight_threshold: Union[float, "NotSet"] = NOT_SET, + only_score_pruned_tokens: Union[bool, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if tokens_freq_ratio_threshold != NOT_SET: + kwargs["tokens_freq_ratio_threshold"] = tokens_freq_ratio_threshold + if tokens_weight_threshold != NOT_SET: + kwargs["tokens_weight_threshold"] = tokens_weight_threshold + if only_score_pruned_tokens != NOT_SET: + kwargs["only_score_pruned_tokens"] = only_score_pruned_tokens + super().__init__(kwargs) -class WeightedTokensQuery(QueryBase): - tokens: Mapping[str, float] - pruning_config: "i.TokenPruningConfig" +class SpanTermQuery(QueryBase): + """ + :arg value: (required)No documentation available. + """ + def __init__(self, *, value: Union[str, "NotSet"], **kwargs: Any): + if value != NOT_SET: + kwargs["value"] = value + super().__init__(**kwargs) -class IntervalsQuery(QueryBase): - all_of: "i.IntervalsAllOf" - any_of: "i.IntervalsAnyOf" - fuzzy: "i.IntervalsFuzzy" - match: "i.IntervalsMatch" - prefix: "i.IntervalsPrefix" - wildcard: "i.IntervalsWildcard" +class PinnedDoc(AttrDict[Any]): + """ + :arg _id: (required)The unique document ID. + :arg _index: (required)The index that contains the document. + """ -class PinnedDoc(TypedDict): - _id: str - _index: str + def __init__( + self, *, _id: Union[str, "NotSet"], _index: Union[str, "NotSet"], **kwargs: Any + ): + if _id != NOT_SET: + kwargs["_id"] = _id + if _index != NOT_SET: + kwargs["_index"] = _index + super().__init__(kwargs) -class FuzzyQuery(QueryBase): - max_expansions: int - prefix_length: int - rewrite: str - transpositions: bool - fuzziness: Union[str, int] - value: Union[str, float, bool] +class MatchQuery(QueryBase): + """ + :arg analyzer: Analyzer used to convert the text in the query value + into tokens. + :arg auto_generate_synonyms_phrase_query: If `true`, match phrase + queries are automatically created for multi-term synonyms. + :arg cutoff_frequency: No documentation available. + :arg fuzziness: Maximum edit distance allowed for matching. + :arg fuzzy_rewrite: Method used to rewrite the query. + :arg fuzzy_transpositions: If `true`, edits for fuzzy matching include + transpositions of two adjacent characters (for example, `ab` to + `ba`). + :arg lenient: If `true`, format-based errors, such as providing a text + query value for a numeric field, are ignored. + :arg max_expansions: Maximum number of terms to which the query will + expand. + :arg minimum_should_match: Minimum number of clauses that must match + for a document to be returned. + :arg operator: Boolean logic used to interpret text in the query + value. + :arg prefix_length: Number of beginning characters left unchanged for + fuzzy matching. + :arg query: (required)Text, number, boolean value or date you wish to + find in the provided field. + :arg zero_terms_query: Indicates whether no documents are returned if + the `analyzer` removes all tokens, such as when using a `stop` + filter. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + auto_generate_synonyms_phrase_query: Union[bool, "NotSet"] = NOT_SET, + cutoff_frequency: Union[float, "NotSet"] = NOT_SET, + fuzziness: Union[str, int, "NotSet"] = NOT_SET, + fuzzy_rewrite: Union[str, "NotSet"] = NOT_SET, + fuzzy_transpositions: Union[bool, "NotSet"] = NOT_SET, + lenient: Union[bool, "NotSet"] = NOT_SET, + max_expansions: Union[int, "NotSet"] = NOT_SET, + minimum_should_match: Union[int, str, "NotSet"] = NOT_SET, + operator: Union[Literal["and", "or"], "NotSet"] = NOT_SET, + prefix_length: Union[int, "NotSet"] = NOT_SET, + query: Union[str, float, bool, "NotSet"], + zero_terms_query: Union[Literal["all", "none"], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if auto_generate_synonyms_phrase_query != NOT_SET: + kwargs["auto_generate_synonyms_phrase_query"] = ( + auto_generate_synonyms_phrase_query + ) + if cutoff_frequency != NOT_SET: + kwargs["cutoff_frequency"] = cutoff_frequency + if fuzziness != NOT_SET: + kwargs["fuzziness"] = fuzziness + if fuzzy_rewrite != NOT_SET: + kwargs["fuzzy_rewrite"] = fuzzy_rewrite + if fuzzy_transpositions != NOT_SET: + kwargs["fuzzy_transpositions"] = fuzzy_transpositions + if lenient != NOT_SET: + kwargs["lenient"] = lenient + if max_expansions != NOT_SET: + kwargs["max_expansions"] = max_expansions + if minimum_should_match != NOT_SET: + kwargs["minimum_should_match"] = minimum_should_match + if operator != NOT_SET: + kwargs["operator"] = operator + if prefix_length != NOT_SET: + kwargs["prefix_length"] = prefix_length + if query != NOT_SET: + kwargs["query"] = query + if zero_terms_query != NOT_SET: + kwargs["zero_terms_query"] = zero_terms_query + super().__init__(**kwargs) -class RankFeatureFunction(TypedDict): +class CommonTermsQuery(QueryBase): + """ + :arg analyzer: No documentation available. + :arg cutoff_frequency: No documentation available. + :arg high_freq_operator: No documentation available. + :arg low_freq_operator: No documentation available. + :arg minimum_should_match: No documentation available. + :arg query: (required)No documentation available. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + cutoff_frequency: Union[float, "NotSet"] = NOT_SET, + high_freq_operator: Union[Literal["and", "or"], "NotSet"] = NOT_SET, + low_freq_operator: Union[Literal["and", "or"], "NotSet"] = NOT_SET, + minimum_should_match: Union[int, str, "NotSet"] = NOT_SET, + query: Union[str, "NotSet"], + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if cutoff_frequency != NOT_SET: + kwargs["cutoff_frequency"] = cutoff_frequency + if high_freq_operator != NOT_SET: + kwargs["high_freq_operator"] = high_freq_operator + if low_freq_operator != NOT_SET: + kwargs["low_freq_operator"] = low_freq_operator + if minimum_should_match != NOT_SET: + kwargs["minimum_should_match"] = minimum_should_match + if query != NOT_SET: + kwargs["query"] = query + super().__init__(**kwargs) + + +class RankFeatureFunction(AttrDict[Any]): pass class RankFeatureFunctionLogarithm(RankFeatureFunction): - scaling_factor: float + """ + :arg scaling_factor: (required)Configurable scaling factor. + """ + def __init__(self, *, scaling_factor: Union[float, "NotSet"], **kwargs: Any): + if scaling_factor != NOT_SET: + kwargs["scaling_factor"] = scaling_factor + super().__init__(**kwargs) -class TextExpansionQuery(QueryBase): - model_id: str - model_text: str - pruning_config: "i.TokenPruningConfig" - -class PrefixQuery(QueryBase): - rewrite: str - value: str - case_insensitive: bool +class IntervalsQuery(QueryBase): + """ + :arg all_of: Returns matches that span a combination of other rules. + :arg any_of: Returns intervals produced by any of its sub-rules. + :arg fuzzy: Matches terms that are similar to the provided term, + within an edit distance defined by `fuzziness`. + :arg match: Matches analyzed text. + :arg prefix: Matches terms that start with a specified set of + characters. + :arg wildcard: Matches terms using a wildcard pattern. + """ + + def __init__( + self, + *, + all_of: Union["i.IntervalsAllOf", Dict[str, Any], "NotSet"] = NOT_SET, + any_of: Union["i.IntervalsAnyOf", Dict[str, Any], "NotSet"] = NOT_SET, + fuzzy: Union["i.IntervalsFuzzy", Dict[str, Any], "NotSet"] = NOT_SET, + match: Union["i.IntervalsMatch", Dict[str, Any], "NotSet"] = NOT_SET, + prefix: Union["i.IntervalsPrefix", Dict[str, Any], "NotSet"] = NOT_SET, + wildcard: Union["i.IntervalsWildcard", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if all_of != NOT_SET: + kwargs["all_of"] = all_of + if any_of != NOT_SET: + kwargs["any_of"] = any_of + if fuzzy != NOT_SET: + kwargs["fuzzy"] = fuzzy + if match != NOT_SET: + kwargs["match"] = match + if prefix != NOT_SET: + kwargs["prefix"] = prefix + if wildcard != NOT_SET: + kwargs["wildcard"] = wildcard + super().__init__(**kwargs) + + +class LikeDocument(AttrDict[Any]): + """ + :arg doc: A document not present in the index. + :arg fields: No documentation available. + :arg _id: ID of a document. + :arg _index: Index of a document. + :arg per_field_analyzer: Overrides the default analyzer. + :arg routing: No documentation available. + :arg version: No documentation available. + :arg version_type: No documentation available. + """ + + def __init__( + self, + *, + doc: Any = NOT_SET, + fields: Union[List[Union[str, "InstrumentedField"]], "NotSet"] = NOT_SET, + _id: Union[str, "NotSet"] = NOT_SET, + _index: Union[str, "NotSet"] = NOT_SET, + per_field_analyzer: Union[ + Mapping[Union[str, "InstrumentedField"], str], "NotSet" + ] = NOT_SET, + routing: Union[str, "NotSet"] = NOT_SET, + version: Union[int, "NotSet"] = NOT_SET, + version_type: Union[ + Literal["internal", "external", "external_gte", "force"], "NotSet" + ] = NOT_SET, + **kwargs: Any, + ): + if doc != NOT_SET: + kwargs["doc"] = doc + if fields != NOT_SET: + kwargs["fields"] = str(fields) + if _id != NOT_SET: + kwargs["_id"] = _id + if _index != NOT_SET: + kwargs["_index"] = _index + if per_field_analyzer != NOT_SET: + kwargs["per_field_analyzer"] = str(per_field_analyzer) + if routing != NOT_SET: + kwargs["routing"] = routing + if version != NOT_SET: + kwargs["version"] = version + if version_type != NOT_SET: + kwargs["version_type"] = version_type + super().__init__(kwargs) -class TokenPruningConfig(TypedDict): - tokens_freq_ratio_threshold: int - tokens_weight_threshold: float - only_score_pruned_tokens: bool +class MatchPhrasePrefixQuery(QueryBase): + """ + :arg analyzer: Analyzer used to convert text in the query value into + tokens. + :arg max_expansions: Maximum number of terms to which the last + provided term of the query value will expand. + :arg query: (required)Text you wish to find in the provided field. + :arg slop: Maximum number of positions allowed between matching + tokens. + :arg zero_terms_query: Indicates whether no documents are returned if + the analyzer removes all tokens, such as when using a `stop` + filter. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + max_expansions: Union[int, "NotSet"] = NOT_SET, + query: Union[str, "NotSet"], + slop: Union[int, "NotSet"] = NOT_SET, + zero_terms_query: Union[Literal["all", "none"], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if max_expansions != NOT_SET: + kwargs["max_expansions"] = max_expansions + if query != NOT_SET: + kwargs["query"] = query + if slop != NOT_SET: + kwargs["slop"] = slop + if zero_terms_query != NOT_SET: + kwargs["zero_terms_query"] = zero_terms_query + super().__init__(**kwargs) class TermQuery(QueryBase): - value: Union[int, float, str, bool, None, Any] - case_insensitive: bool - - -class SpanQuery(TypedDict): - span_containing: "i.SpanContainingQuery" - span_field_masking: "i.SpanFieldMaskingQuery" - span_first: "i.SpanFirstQuery" - span_gap: Mapping[Union[str, "InstrumentedField"], int] - span_multi: "i.SpanMultiTermQuery" - span_near: "i.SpanNearQuery" - span_not: "i.SpanNotQuery" - span_or: "i.SpanOrQuery" - span_term: Mapping[Union[str, "InstrumentedField"], "i.SpanTermQuery"] - span_within: "i.SpanWithinQuery" - - -class RankFeatureFunctionSaturation(RankFeatureFunction): - pivot: float + """ + :arg value: (required)Term you wish to find in the provided field. + :arg case_insensitive: Allows ASCII case insensitive matching of the + value with the indexed field values when set to `true`. When + `false`, the case sensitivity of matching depends on the + underlying field’s mapping. + """ + + def __init__( + self, + *, + value: Union[int, float, str, bool, None, Any, "NotSet"], + case_insensitive: Union[bool, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if value != NOT_SET: + kwargs["value"] = value + if case_insensitive != NOT_SET: + kwargs["case_insensitive"] = case_insensitive + super().__init__(**kwargs) + + +class UntypedDistanceFeatureQuery(DistanceFeatureQueryBase): + pass class WildcardQuery(QueryBase): - case_insensitive: bool - rewrite: str - value: str - wildcard: str - - -class SpanTermQuery(QueryBase): - value: str - - -class QueryVectorBuilder(TypedDict): - text_embedding: "i.TextEmbedding" + """ + :arg case_insensitive: Allows case insensitive matching of the pattern + with the indexed field values when set to true. Default is false + which means the case sensitivity of matching depends on the + underlying field’s mapping. + :arg rewrite: Method used to rewrite the query. + :arg value: Wildcard pattern for terms you wish to find in the + provided field. Required, when wildcard is not set. + :arg wildcard: Wildcard pattern for terms you wish to find in the + provided field. Required, when value is not set. + """ + + def __init__( + self, + *, + case_insensitive: Union[bool, "NotSet"] = NOT_SET, + rewrite: Union[str, "NotSet"] = NOT_SET, + value: Union[str, "NotSet"] = NOT_SET, + wildcard: Union[str, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if case_insensitive != NOT_SET: + kwargs["case_insensitive"] = case_insensitive + if rewrite != NOT_SET: + kwargs["rewrite"] = rewrite + if value != NOT_SET: + kwargs["value"] = value + if wildcard != NOT_SET: + kwargs["wildcard"] = wildcard + super().__init__(**kwargs) -class Script(TypedDict): - source: str - id: str - params: Mapping[str, Any] - lang: Literal["painless", "expression", "mustache", "java"] - options: Mapping[str, str] - - -class CommonTermsQuery(QueryBase): - analyzer: str - cutoff_frequency: float - high_freq_operator: Literal["and", "or"] - low_freq_operator: Literal["and", "or"] - minimum_should_match: Union[int, str] - query: str - - -class InnerHits(TypedDict): - name: str - size: int - from_: int - collapse: "i.FieldCollapse" - docvalue_fields: List["i.FieldAndFormat"] - explain: bool - highlight: "i.Highlight" - ignore_unmapped: bool - script_fields: Mapping[Union[str, "InstrumentedField"], "i.ScriptField"] - seq_no_primary_term: bool - fields: Union[ - Union[str, "InstrumentedField"], List[Union[str, "InstrumentedField"]] - ] - sort: Union[ - Union[Union[str, "InstrumentedField"], "i.SortOptions"], - List[Union[Union[str, "InstrumentedField"], "i.SortOptions"]], - ] - _source: Union[bool, "i.SourceFilter"] - stored_fields: Union[ - Union[str, "InstrumentedField"], List[Union[str, "InstrumentedField"]] - ] - track_scores: bool - version: bool - - -class MatchBoolPrefixQuery(QueryBase): - analyzer: str - fuzziness: Union[str, int] - fuzzy_rewrite: str - fuzzy_transpositions: bool - max_expansions: int - minimum_should_match: Union[int, str] - operator: Literal["and", "or"] - prefix_length: int - query: str - - -class FunctionScoreContainer(TypedDict): - exp: Union[ - "function.UntypedDecayFunction", - "function.DateDecayFunction", - "function.NumericDecayFunction", - "function.GeoDecayFunction", - ] - gauss: Union[ - "function.UntypedDecayFunction", - "function.DateDecayFunction", - "function.NumericDecayFunction", - "function.GeoDecayFunction", - ] - linear: Union[ - "function.UntypedDecayFunction", - "function.DateDecayFunction", - "function.NumericDecayFunction", - "function.GeoDecayFunction", - ] - field_value_factor: "function.FieldValueFactorScoreFunction" - random_score: "function.RandomScoreFunction" - script_score: "function.ScriptScoreFunction" - filter: Query - weight: float - - -class RankFeatureFunctionLinear(RankFeatureFunction): - pass +class RegexpQuery(QueryBase): + """ + :arg case_insensitive: Allows case insensitive matching of the regular + expression value with the indexed field values when set to `true`. + When `false`, case sensitivity of matching depends on the + underlying field’s mapping. + :arg flags: Enables optional operators for the regular expression. + :arg max_determinized_states: Maximum number of automaton states + required for the query. + :arg rewrite: Method used to rewrite the query. + :arg value: (required)Regular expression for terms you wish to find in + the provided field. + """ + + def __init__( + self, + *, + case_insensitive: Union[bool, "NotSet"] = NOT_SET, + flags: Union[str, "NotSet"] = NOT_SET, + max_determinized_states: Union[int, "NotSet"] = NOT_SET, + rewrite: Union[str, "NotSet"] = NOT_SET, + value: Union[str, "NotSet"], + **kwargs: Any, + ): + if case_insensitive != NOT_SET: + kwargs["case_insensitive"] = case_insensitive + if flags != NOT_SET: + kwargs["flags"] = flags + if max_determinized_states != NOT_SET: + kwargs["max_determinized_states"] = max_determinized_states + if rewrite != NOT_SET: + kwargs["rewrite"] = rewrite + if value != NOT_SET: + kwargs["value"] = value + super().__init__(**kwargs) class TermsSetQuery(QueryBase): - minimum_should_match_field: Union[str, "InstrumentedField"] - minimum_should_match_script: "i.Script" - terms: List[str] + """ + :arg minimum_should_match_field: Numeric field containing the number + of matching terms required to return a document. + :arg minimum_should_match_script: Custom script containing the number + of matching terms required to return a document. + :arg terms: (required)Array of terms you wish to find in the provided + field. + """ + + def __init__( + self, + *, + minimum_should_match_field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + minimum_should_match_script: Union[ + "i.Script", Dict[str, Any], "NotSet" + ] = NOT_SET, + terms: Union[List[str], "NotSet"], + **kwargs: Any, + ): + if minimum_should_match_field != NOT_SET: + kwargs["minimum_should_match_field"] = str(minimum_should_match_field) + if minimum_should_match_script != NOT_SET: + kwargs["minimum_should_match_script"] = minimum_should_match_script + if terms != NOT_SET: + kwargs["terms"] = terms + super().__init__(**kwargs) -class LikeDocument(TypedDict): - doc: Any - fields: List[Union[str, "InstrumentedField"]] - _id: str - _index: str - per_field_analyzer: Mapping[Union[str, "InstrumentedField"], str] - routing: str - version: int - version_type: Literal["internal", "external", "external_gte", "force"] +class MatchPhraseQuery(QueryBase): + """ + :arg analyzer: Analyzer used to convert the text in the query value + into tokens. + :arg query: (required)Query terms that are analyzed and turned into a + phrase query. + :arg slop: Maximum number of positions allowed between matching + tokens. + :arg zero_terms_query: Indicates whether no documents are returned if + the `analyzer` removes all tokens, such as when using a `stop` + filter. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + query: Union[str, "NotSet"], + slop: Union[int, "NotSet"] = NOT_SET, + zero_terms_query: Union[Literal["all", "none"], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if query != NOT_SET: + kwargs["query"] = query + if slop != NOT_SET: + kwargs["slop"] = slop + if zero_terms_query != NOT_SET: + kwargs["zero_terms_query"] = zero_terms_query + super().__init__(**kwargs) + + +class FunctionScoreContainer(AttrDict[Any]): + """ + :arg exp: Function that scores a document with a exponential decay, + depending on the distance of a numeric field value of the document + from an origin. + :arg gauss: Function that scores a document with a normal decay, + depending on the distance of a numeric field value of the document + from an origin. + :arg linear: Function that scores a document with a linear decay, + depending on the distance of a numeric field value of the document + from an origin. + :arg field_value_factor: Function allows you to use a field from a + document to influence the score. It’s similar to using the + script_score function, however, it avoids the overhead of + scripting. + :arg random_score: Generates scores that are uniformly distributed + from 0 up to but not including 1. In case you want scores to be + reproducible, it is possible to provide a `seed` and `field`. + :arg script_score: Enables you to wrap another query and customize the + scoring of it optionally with a computation derived from other + numeric field values in the doc using a script expression. + :arg filter: No documentation available. + :arg weight: No documentation available. + """ + + def __init__( + self, + *, + exp: Union[ + "function.UntypedDecayFunction", + "function.DateDecayFunction", + "function.NumericDecayFunction", + "function.GeoDecayFunction", + "NotSet", + ] = NOT_SET, + gauss: Union[ + "function.UntypedDecayFunction", + "function.DateDecayFunction", + "function.NumericDecayFunction", + "function.GeoDecayFunction", + "NotSet", + ] = NOT_SET, + linear: Union[ + "function.UntypedDecayFunction", + "function.DateDecayFunction", + "function.NumericDecayFunction", + "function.GeoDecayFunction", + "NotSet", + ] = NOT_SET, + field_value_factor: Union[ + "function.FieldValueFactorScoreFunction", "NotSet" + ] = NOT_SET, + random_score: Union["function.RandomScoreFunction", "NotSet"] = NOT_SET, + script_score: Union["function.ScriptScoreFunction", "NotSet"] = NOT_SET, + filter: Union[Query, "NotSet"] = NOT_SET, + weight: Union[float, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if exp != NOT_SET: + kwargs["exp"] = exp + if gauss != NOT_SET: + kwargs["gauss"] = gauss + if linear != NOT_SET: + kwargs["linear"] = linear + if field_value_factor != NOT_SET: + kwargs["field_value_factor"] = field_value_factor + if random_score != NOT_SET: + kwargs["random_score"] = random_score + if script_score != NOT_SET: + kwargs["script_score"] = script_score + if filter != NOT_SET: + kwargs["filter"] = filter + if weight != NOT_SET: + kwargs["weight"] = weight + super().__init__(kwargs) + + +class GeoDistanceFeatureQuery(DistanceFeatureQueryBase): + pass -class RegexpQuery(QueryBase): - case_insensitive: bool - flags: str - max_determinized_states: int - rewrite: str - value: str +class Script(AttrDict[Any]): + """ + :arg source: The script source. + :arg id: The `id` for a stored script. + :arg params: Specifies any named parameters that are passed into the + script as variables. Use parameters instead of hard-coded values + to decrease compile time. + :arg lang: Specifies the language the script is written in. + :arg options: No documentation available. + """ + + def __init__( + self, + *, + source: Union[str, "NotSet"] = NOT_SET, + id: Union[str, "NotSet"] = NOT_SET, + params: Union[Mapping[str, Any], "NotSet"] = NOT_SET, + lang: Union[ + Literal["painless", "expression", "mustache", "java"], "NotSet" + ] = NOT_SET, + options: Union[Mapping[str, str], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if source != NOT_SET: + kwargs["source"] = source + if id != NOT_SET: + kwargs["id"] = id + if params != NOT_SET: + kwargs["params"] = params + if lang != NOT_SET: + kwargs["lang"] = lang + if options != NOT_SET: + kwargs["options"] = options + super().__init__(kwargs) + + +class SpanQuery(AttrDict[Any]): + """ + :arg span_containing: Accepts a list of span queries, but only returns + those spans which also match a second span query. + :arg span_field_masking: Allows queries like `span_near` or `span_or` + across different fields. + :arg span_first: Accepts another span query whose matches must appear + within the first N positions of the field. + :arg span_gap: No documentation available. + :arg span_multi: Wraps a `term`, `range`, `prefix`, `wildcard`, + `regexp`, or `fuzzy` query. + :arg span_near: Accepts multiple span queries whose matches must be + within the specified distance of each other, and possibly in the + same order. + :arg span_not: Wraps another span query, and excludes any documents + which match that query. + :arg span_or: Combines multiple span queries and returns documents + which match any of the specified queries. + :arg span_term: The equivalent of the `term` query but for use with + other span queries. + :arg span_within: The result from a single span query is returned as + long is its span falls within the spans returned by a list of + other span queries. + """ + + def __init__( + self, + *, + span_containing: Union[ + "i.SpanContainingQuery", Dict[str, Any], "NotSet" + ] = NOT_SET, + span_field_masking: Union[ + "i.SpanFieldMaskingQuery", Dict[str, Any], "NotSet" + ] = NOT_SET, + span_first: Union["i.SpanFirstQuery", Dict[str, Any], "NotSet"] = NOT_SET, + span_gap: Union[ + Mapping[Union[str, "InstrumentedField"], int], "NotSet" + ] = NOT_SET, + span_multi: Union["i.SpanMultiTermQuery", Dict[str, Any], "NotSet"] = NOT_SET, + span_near: Union["i.SpanNearQuery", Dict[str, Any], "NotSet"] = NOT_SET, + span_not: Union["i.SpanNotQuery", Dict[str, Any], "NotSet"] = NOT_SET, + span_or: Union["i.SpanOrQuery", Dict[str, Any], "NotSet"] = NOT_SET, + span_term: Union[ + Mapping[Union[str, "InstrumentedField"], "i.SpanTermQuery"], + Dict[str, Any], + "NotSet", + ] = NOT_SET, + span_within: Union["i.SpanWithinQuery", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if span_containing != NOT_SET: + kwargs["span_containing"] = span_containing + if span_field_masking != NOT_SET: + kwargs["span_field_masking"] = span_field_masking + if span_first != NOT_SET: + kwargs["span_first"] = span_first + if span_gap != NOT_SET: + kwargs["span_gap"] = str(span_gap) + if span_multi != NOT_SET: + kwargs["span_multi"] = span_multi + if span_near != NOT_SET: + kwargs["span_near"] = span_near + if span_not != NOT_SET: + kwargs["span_not"] = span_not + if span_or != NOT_SET: + kwargs["span_or"] = span_or + if span_term != NOT_SET: + kwargs["span_term"] = str(span_term) + if span_within != NOT_SET: + kwargs["span_within"] = span_within + super().__init__(kwargs) -class MatchQuery(QueryBase): - analyzer: str - auto_generate_synonyms_phrase_query: bool - cutoff_frequency: float - fuzziness: Union[str, int] - fuzzy_rewrite: str - fuzzy_transpositions: bool - lenient: bool - max_expansions: int - minimum_should_match: Union[int, str] - operator: Literal["and", "or"] - prefix_length: int - query: Union[str, float, bool] - zero_terms_query: Literal["all", "none"] - +class RankFeatureFunctionSaturation(RankFeatureFunction): + """ + :arg pivot: Configurable pivot value so that the result will be less + than 0.5. + """ -class RankFeatureFunctionSigmoid(RankFeatureFunction): - pivot: float - exponent: float + def __init__(self, *, pivot: Union[float, "NotSet"] = NOT_SET, **kwargs: Any): + if pivot != NOT_SET: + kwargs["pivot"] = pivot + super().__init__(**kwargs) -class IntervalsAllOf(TypedDict): - intervals: List["i.IntervalsContainer"] - max_gaps: int - ordered: bool - filter: "i.IntervalsFilter" +class MatchBoolPrefixQuery(QueryBase): + """ + :arg analyzer: Analyzer used to convert the text in the query value + into tokens. + :arg fuzziness: Maximum edit distance allowed for matching. Can be + applied to the term subqueries constructed for all terms but the + final term. + :arg fuzzy_rewrite: Method used to rewrite the query. Can be applied + to the term subqueries constructed for all terms but the final + term. + :arg fuzzy_transpositions: If `true`, edits for fuzzy matching include + transpositions of two adjacent characters (for example, `ab` to + `ba`). Can be applied to the term subqueries constructed for all + terms but the final term. + :arg max_expansions: Maximum number of terms to which the query will + expand. Can be applied to the term subqueries constructed for all + terms but the final term. + :arg minimum_should_match: Minimum number of clauses that must match + for a document to be returned. Applied to the constructed bool + query. + :arg operator: Boolean logic used to interpret text in the query + value. Applied to the constructed bool query. + :arg prefix_length: Number of beginning characters left unchanged for + fuzzy matching. Can be applied to the term subqueries constructed + for all terms but the final term. + :arg query: (required)Terms you wish to find in the provided field. + The last term is used in a prefix query. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + fuzziness: Union[str, int, "NotSet"] = NOT_SET, + fuzzy_rewrite: Union[str, "NotSet"] = NOT_SET, + fuzzy_transpositions: Union[bool, "NotSet"] = NOT_SET, + max_expansions: Union[int, "NotSet"] = NOT_SET, + minimum_should_match: Union[int, str, "NotSet"] = NOT_SET, + operator: Union[Literal["and", "or"], "NotSet"] = NOT_SET, + prefix_length: Union[int, "NotSet"] = NOT_SET, + query: Union[str, "NotSet"], + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if fuzziness != NOT_SET: + kwargs["fuzziness"] = fuzziness + if fuzzy_rewrite != NOT_SET: + kwargs["fuzzy_rewrite"] = fuzzy_rewrite + if fuzzy_transpositions != NOT_SET: + kwargs["fuzzy_transpositions"] = fuzzy_transpositions + if max_expansions != NOT_SET: + kwargs["max_expansions"] = max_expansions + if minimum_should_match != NOT_SET: + kwargs["minimum_should_match"] = minimum_should_match + if operator != NOT_SET: + kwargs["operator"] = operator + if prefix_length != NOT_SET: + kwargs["prefix_length"] = prefix_length + if query != NOT_SET: + kwargs["query"] = query + super().__init__(**kwargs) -class IntervalsAnyOf(TypedDict): - intervals: List["i.IntervalsContainer"] - filter: "i.IntervalsFilter" +class FuzzyQuery(QueryBase): + """ + :arg max_expansions: Maximum number of variations created. + :arg prefix_length: Number of beginning characters left unchanged when + creating expansions. + :arg rewrite: Number of beginning characters left unchanged when + creating expansions. + :arg transpositions: Indicates whether edits include transpositions of + two adjacent characters (for example `ab` to `ba`). + :arg fuzziness: Maximum edit distance allowed for matching. + :arg value: (required)Term you wish to find in the provided field. + """ + + def __init__( + self, + *, + max_expansions: Union[int, "NotSet"] = NOT_SET, + prefix_length: Union[int, "NotSet"] = NOT_SET, + rewrite: Union[str, "NotSet"] = NOT_SET, + transpositions: Union[bool, "NotSet"] = NOT_SET, + fuzziness: Union[str, int, "NotSet"] = NOT_SET, + value: Union[str, float, bool, "NotSet"], + **kwargs: Any, + ): + if max_expansions != NOT_SET: + kwargs["max_expansions"] = max_expansions + if prefix_length != NOT_SET: + kwargs["prefix_length"] = prefix_length + if rewrite != NOT_SET: + kwargs["rewrite"] = rewrite + if transpositions != NOT_SET: + kwargs["transpositions"] = transpositions + if fuzziness != NOT_SET: + kwargs["fuzziness"] = fuzziness + if value != NOT_SET: + kwargs["value"] = value + super().__init__(**kwargs) + + +class InnerHits(AttrDict[Any]): + """ + :arg name: The name for the particular inner hit definition in the + response. Useful when a search request contains multiple inner + hits. + :arg size: The maximum number of hits to return per `inner_hits`. + :arg from: Inner hit starting document offset. + :arg collapse: No documentation available. + :arg docvalue_fields: No documentation available. + :arg explain: No documentation available. + :arg highlight: No documentation available. + :arg ignore_unmapped: No documentation available. + :arg script_fields: No documentation available. + :arg seq_no_primary_term: No documentation available. + :arg fields: No documentation available. + :arg sort: How the inner hits should be sorted per `inner_hits`. By + default, inner hits are sorted by score. + :arg _source: No documentation available. + :arg stored_fields: No documentation available. + :arg track_scores: No documentation available. + :arg version: No documentation available. + """ + + def __init__( + self, + *, + name: Union[str, "NotSet"] = NOT_SET, + size: Union[int, "NotSet"] = NOT_SET, + from_: Union[int, "NotSet"] = NOT_SET, + collapse: Union["i.FieldCollapse", Dict[str, Any], "NotSet"] = NOT_SET, + docvalue_fields: Union[ + List["i.FieldAndFormat"], Dict[str, Any], "NotSet" + ] = NOT_SET, + explain: Union[bool, "NotSet"] = NOT_SET, + highlight: Union["i.Highlight", Dict[str, Any], "NotSet"] = NOT_SET, + ignore_unmapped: Union[bool, "NotSet"] = NOT_SET, + script_fields: Union[ + Mapping[Union[str, "InstrumentedField"], "i.ScriptField"], + Dict[str, Any], + "NotSet", + ] = NOT_SET, + seq_no_primary_term: Union[bool, "NotSet"] = NOT_SET, + fields: Union[ + Union[str, "InstrumentedField"], + List[Union[str, "InstrumentedField"]], + "NotSet", + ] = NOT_SET, + sort: Union[ + Union[Union[str, "InstrumentedField"], "i.SortOptions"], + List[Union[Union[str, "InstrumentedField"], "i.SortOptions"]], + Dict[str, Any], + "NotSet", + ] = NOT_SET, + _source: Union[bool, "i.SourceFilter", Dict[str, Any], "NotSet"] = NOT_SET, + stored_fields: Union[ + Union[str, "InstrumentedField"], + List[Union[str, "InstrumentedField"]], + "NotSet", + ] = NOT_SET, + track_scores: Union[bool, "NotSet"] = NOT_SET, + version: Union[bool, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if name != NOT_SET: + kwargs["name"] = name + if size != NOT_SET: + kwargs["size"] = size + if from_ != NOT_SET: + kwargs["from_"] = from_ + if collapse != NOT_SET: + kwargs["collapse"] = collapse + if docvalue_fields != NOT_SET: + kwargs["docvalue_fields"] = docvalue_fields + if explain != NOT_SET: + kwargs["explain"] = explain + if highlight != NOT_SET: + kwargs["highlight"] = highlight + if ignore_unmapped != NOT_SET: + kwargs["ignore_unmapped"] = ignore_unmapped + if script_fields != NOT_SET: + kwargs["script_fields"] = str(script_fields) + if seq_no_primary_term != NOT_SET: + kwargs["seq_no_primary_term"] = seq_no_primary_term + if fields != NOT_SET: + kwargs["fields"] = str(fields) + if sort != NOT_SET: + kwargs["sort"] = str(sort) + if _source != NOT_SET: + kwargs["_source"] = _source + if stored_fields != NOT_SET: + kwargs["stored_fields"] = str(stored_fields) + if track_scores != NOT_SET: + kwargs["track_scores"] = track_scores + if version != NOT_SET: + kwargs["version"] = version + super().__init__(kwargs) -class IntervalsFuzzy(TypedDict): - analyzer: str - fuzziness: Union[str, int] - prefix_length: int - term: str - transpositions: bool - use_field: Union[str, "InstrumentedField"] +class WeightedTokensQuery(QueryBase): + """ + :arg tokens: (required)The tokens representing this query + :arg pruning_config: Token pruning configurations + """ + + def __init__( + self, + *, + tokens: Union[Mapping[str, float], "NotSet"], + pruning_config: Union[ + "i.TokenPruningConfig", Dict[str, Any], "NotSet" + ] = NOT_SET, + **kwargs: Any, + ): + if tokens != NOT_SET: + kwargs["tokens"] = tokens + if pruning_config != NOT_SET: + kwargs["pruning_config"] = pruning_config + super().__init__(**kwargs) -class IntervalsPrefix(TypedDict): - analyzer: str - prefix: str - use_field: Union[str, "InstrumentedField"] +class RankFeatureFunctionSigmoid(RankFeatureFunction): + """ + :arg pivot: (required)Configurable pivot value so that the result will + be less than 0.5. + :arg exponent: (required)Configurable Exponent. + """ + + def __init__( + self, + *, + pivot: Union[float, "NotSet"], + exponent: Union[float, "NotSet"], + **kwargs: Any, + ): + if pivot != NOT_SET: + kwargs["pivot"] = pivot + if exponent != NOT_SET: + kwargs["exponent"] = exponent + super().__init__(**kwargs) -class IntervalsMatch(TypedDict): - analyzer: str - max_gaps: int - ordered: bool - query: str - use_field: Union[str, "InstrumentedField"] - filter: "i.IntervalsFilter" +class TextExpansionQuery(QueryBase): + """ + :arg model_id: (required)The text expansion NLP model to use + :arg model_text: (required)The query text + :arg pruning_config: Token pruning configurations + """ + + def __init__( + self, + *, + model_id: Union[str, "NotSet"], + model_text: Union[str, "NotSet"], + pruning_config: Union[ + "i.TokenPruningConfig", Dict[str, Any], "NotSet" + ] = NOT_SET, + **kwargs: Any, + ): + if model_id != NOT_SET: + kwargs["model_id"] = model_id + if model_text != NOT_SET: + kwargs["model_text"] = model_text + if pruning_config != NOT_SET: + kwargs["pruning_config"] = pruning_config + super().__init__(**kwargs) -class IntervalsWildcard(TypedDict): - analyzer: str - pattern: str - use_field: Union[str, "InstrumentedField"] +class RankFeatureFunctionLinear(RankFeatureFunction): + pass -class SpanFieldMaskingQuery(QueryBase): - field: Union[str, "InstrumentedField"] - query: "i.SpanQuery" +class TextEmbedding(AttrDict[Any]): + """ + :arg model_id: (required)No documentation available. + :arg model_text: (required)No documentation available. + """ + + def __init__( + self, + *, + model_id: Union[str, "NotSet"], + model_text: Union[str, "NotSet"], + **kwargs: Any, + ): + if model_id != NOT_SET: + kwargs["model_id"] = model_id + if model_text != NOT_SET: + kwargs["model_text"] = model_text + super().__init__(kwargs) + + +class IntervalsAllOf(AttrDict[Any]): + """ + :arg intervals: (required)An array of rules to combine. All rules must + produce a match in a document for the overall source to match. + :arg max_gaps: Maximum number of positions between the matching terms. + Intervals produced by the rules further apart than this are not + considered matches. + :arg ordered: If `true`, intervals produced by the rules should appear + in the order in which they are specified. + :arg filter: Rule used to filter returned intervals. + """ + + def __init__( + self, + *, + intervals: Union[List["i.IntervalsContainer"], Dict[str, Any], "NotSet"], + max_gaps: Union[int, "NotSet"] = NOT_SET, + ordered: Union[bool, "NotSet"] = NOT_SET, + filter: Union["i.IntervalsFilter", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if intervals != NOT_SET: + kwargs["intervals"] = intervals + if max_gaps != NOT_SET: + kwargs["max_gaps"] = max_gaps + if ordered != NOT_SET: + kwargs["ordered"] = ordered + if filter != NOT_SET: + kwargs["filter"] = filter + super().__init__(kwargs) + + +class IntervalsWildcard(AttrDict[Any]): + """ + :arg analyzer: Analyzer used to analyze the `pattern`. Defaults to the + top-level field's analyzer. + :arg pattern: (required)Wildcard pattern used to find matching terms. + :arg use_field: If specified, match intervals from this field rather + than the top-level field. The `pattern` is normalized using the + search analyzer from this field, unless `analyzer` is specified + separately. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + pattern: Union[str, "NotSet"], + use_field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if pattern != NOT_SET: + kwargs["pattern"] = pattern + if use_field != NOT_SET: + kwargs["use_field"] = str(use_field) + super().__init__(kwargs) + + +class IntervalsMatch(AttrDict[Any]): + """ + :arg analyzer: Analyzer used to analyze terms in the query. + :arg max_gaps: Maximum number of positions between the matching terms. + Terms further apart than this are not considered matches. + :arg ordered: If `true`, matching terms must appear in their specified + order. + :arg query: (required)Text you wish to find in the provided field. + :arg use_field: If specified, match intervals from this field rather + than the top-level field. The `term` is normalized using the + search analyzer from this field, unless `analyzer` is specified + separately. + :arg filter: An optional interval filter. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + max_gaps: Union[int, "NotSet"] = NOT_SET, + ordered: Union[bool, "NotSet"] = NOT_SET, + query: Union[str, "NotSet"], + use_field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + filter: Union["i.IntervalsFilter", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if max_gaps != NOT_SET: + kwargs["max_gaps"] = max_gaps + if ordered != NOT_SET: + kwargs["ordered"] = ordered + if query != NOT_SET: + kwargs["query"] = query + if use_field != NOT_SET: + kwargs["use_field"] = str(use_field) + if filter != NOT_SET: + kwargs["filter"] = filter + super().__init__(kwargs) + + +class IntervalsPrefix(AttrDict[Any]): + """ + :arg analyzer: Analyzer used to analyze the `prefix`. + :arg prefix: (required)Beginning characters of terms you wish to find + in the top-level field. + :arg use_field: If specified, match intervals from this field rather + than the top-level field. The `prefix` is normalized using the + search analyzer from this field, unless `analyzer` is specified + separately. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + prefix: Union[str, "NotSet"], + use_field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if prefix != NOT_SET: + kwargs["prefix"] = prefix + if use_field != NOT_SET: + kwargs["use_field"] = str(use_field) + super().__init__(kwargs) + + +class IntervalsAnyOf(AttrDict[Any]): + """ + :arg intervals: (required)An array of rules to match. + :arg filter: Rule used to filter returned intervals. + """ + + def __init__( + self, + *, + intervals: Union[List["i.IntervalsContainer"], Dict[str, Any], "NotSet"], + filter: Union["i.IntervalsFilter", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if intervals != NOT_SET: + kwargs["intervals"] = intervals + if filter != NOT_SET: + kwargs["filter"] = filter + super().__init__(kwargs) + + +class IntervalsFuzzy(AttrDict[Any]): + """ + :arg analyzer: Analyzer used to normalize the term. + :arg fuzziness: Maximum edit distance allowed for matching. + :arg prefix_length: Number of beginning characters left unchanged when + creating expansions. + :arg term: (required)The term to match. + :arg transpositions: Indicates whether edits include transpositions of + two adjacent characters (for example, `ab` to `ba`). + :arg use_field: If specified, match intervals from this field rather + than the top-level field. The `term` is normalized using the + search analyzer from this field, unless `analyzer` is specified + separately. + """ + + def __init__( + self, + *, + analyzer: Union[str, "NotSet"] = NOT_SET, + fuzziness: Union[str, int, "NotSet"] = NOT_SET, + prefix_length: Union[int, "NotSet"] = NOT_SET, + term: Union[str, "NotSet"], + transpositions: Union[bool, "NotSet"] = NOT_SET, + use_field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + if fuzziness != NOT_SET: + kwargs["fuzziness"] = fuzziness + if prefix_length != NOT_SET: + kwargs["prefix_length"] = prefix_length + if term != NOT_SET: + kwargs["term"] = term + if transpositions != NOT_SET: + kwargs["transpositions"] = transpositions + if use_field != NOT_SET: + kwargs["use_field"] = str(use_field) + super().__init__(kwargs) class SpanNearQuery(QueryBase): - clauses: List["i.SpanQuery"] - in_order: bool - slop: int - - -class SpanContainingQuery(QueryBase): - big: "i.SpanQuery" - little: "i.SpanQuery" + """ + :arg clauses: (required)Array of one or more other span type queries. + :arg in_order: Controls whether matches are required to be in-order. + :arg slop: Controls the maximum number of intervening unmatched + positions permitted. + """ + + def __init__( + self, + *, + clauses: Union[List["i.SpanQuery"], Dict[str, Any], "NotSet"], + in_order: Union[bool, "NotSet"] = NOT_SET, + slop: Union[int, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if clauses != NOT_SET: + kwargs["clauses"] = clauses + if in_order != NOT_SET: + kwargs["in_order"] = in_order + if slop != NOT_SET: + kwargs["slop"] = slop + super().__init__(**kwargs) class SpanOrQuery(QueryBase): - clauses: List["i.SpanQuery"] + """ + :arg clauses: (required)Array of one or more other span type queries. + """ + def __init__( + self, + *, + clauses: Union[List["i.SpanQuery"], Dict[str, Any], "NotSet"], + **kwargs: Any, + ): + if clauses != NOT_SET: + kwargs["clauses"] = clauses + super().__init__(**kwargs) -class SpanNotQuery(QueryBase): - dist: int - exclude: "i.SpanQuery" - include: "i.SpanQuery" - post: int - pre: int - -class SpanFirstQuery(QueryBase): - end: int - match: "i.SpanQuery" +class SpanNotQuery(QueryBase): + """ + :arg dist: The number of tokens from within the include span that + can’t have overlap with the exclude span. Equivalent to setting + both `pre` and `post`. + :arg exclude: (required)Span query whose matches must not overlap + those returned. + :arg include: (required)Span query whose matches are filtered. + :arg post: The number of tokens after the include span that can’t have + overlap with the exclude span. + :arg pre: The number of tokens before the include span that can’t have + overlap with the exclude span. + """ + + def __init__( + self, + *, + dist: Union[int, "NotSet"] = NOT_SET, + exclude: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + include: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + post: Union[int, "NotSet"] = NOT_SET, + pre: Union[int, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if dist != NOT_SET: + kwargs["dist"] = dist + if exclude != NOT_SET: + kwargs["exclude"] = exclude + if include != NOT_SET: + kwargs["include"] = include + if post != NOT_SET: + kwargs["post"] = post + if pre != NOT_SET: + kwargs["pre"] = pre + super().__init__(**kwargs) class SpanMultiTermQuery(QueryBase): - match: Query - - -class SpanWithinQuery(QueryBase): - big: "i.SpanQuery" - little: "i.SpanQuery" - - -class TextEmbedding(TypedDict): - model_id: str - model_text: str - - -class FieldAndFormat(TypedDict): - field: Union[str, "InstrumentedField"] - format: str - include_unmapped: bool - - -class HighlightBase(TypedDict): - type: Literal["plain", "fvh", "unified"] - boundary_chars: str - boundary_max_scan: int - boundary_scanner: Literal["chars", "sentence", "word"] - boundary_scanner_locale: str - force_source: bool - fragmenter: Literal["simple", "span"] - fragment_size: int - highlight_filter: bool - highlight_query: Query - max_fragment_length: int - max_analyzed_offset: int - no_match_size: int - number_of_fragments: int - options: Mapping[str, Any] - order: Literal["score"] - phrase_limit: int - post_tags: List[str] - pre_tags: List[str] - require_field_match: bool - tags_schema: Literal["styled"] + """ + :arg match: (required)Should be a multi term query (one of `wildcard`, + `fuzzy`, `prefix`, `range`, or `regexp` query). + """ + def __init__(self, *, match: Union[Query, "NotSet"], **kwargs: Any): + if match != NOT_SET: + kwargs["match"] = match + super().__init__(**kwargs) -class Highlight(HighlightBase): - encoder: Literal["default", "html"] - fields: Mapping[Union[str, "InstrumentedField"], "i.HighlightField"] - - -class SourceFilter(TypedDict): - excludes: Union[ - Union[str, "InstrumentedField"], List[Union[str, "InstrumentedField"]] - ] - includes: Union[ - Union[str, "InstrumentedField"], List[Union[str, "InstrumentedField"]] - ] - -class SortOptions(TypedDict): - _score: "i.ScoreSort" - _doc: "i.ScoreSort" - _geo_distance: "i.GeoDistanceSort" - _script: "i.ScriptSort" +class SpanFieldMaskingQuery(QueryBase): + """ + :arg field: (required)No documentation available. + :arg query: (required)No documentation available. + """ + + def __init__( + self, + *, + field: Union[str, "InstrumentedField", "NotSet"], + query: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + **kwargs: Any, + ): + if field != NOT_SET: + kwargs["field"] = str(field) + if query != NOT_SET: + kwargs["query"] = query + super().__init__(**kwargs) -class FieldCollapse(TypedDict): - field: Union[str, "InstrumentedField"] - inner_hits: Union["i.InnerHits", List["i.InnerHits"]] - max_concurrent_group_searches: int - collapse: "i.FieldCollapse" +class SpanFirstQuery(QueryBase): + """ + :arg end: (required)Controls the maximum end position permitted in a + match. + :arg match: (required)Can be any other span type query. + """ + + def __init__( + self, + *, + end: Union[int, "NotSet"], + match: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + **kwargs: Any, + ): + if end != NOT_SET: + kwargs["end"] = end + if match != NOT_SET: + kwargs["match"] = match + super().__init__(**kwargs) -class ScriptField(TypedDict): - script: "i.Script" - ignore_failure: bool +class SpanContainingQuery(QueryBase): + """ + :arg big: (required)Can be any span query. Matching spans from `big` + that contain matches from `little` are returned. + :arg little: (required)Can be any span query. Matching spans from + `big` that contain matches from `little` are returned. + """ + + def __init__( + self, + *, + big: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + little: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + **kwargs: Any, + ): + if big != NOT_SET: + kwargs["big"] = big + if little != NOT_SET: + kwargs["little"] = little + super().__init__(**kwargs) -class IntervalsContainer(TypedDict): - all_of: "i.IntervalsAllOf" - any_of: "i.IntervalsAnyOf" - fuzzy: "i.IntervalsFuzzy" - match: "i.IntervalsMatch" - prefix: "i.IntervalsPrefix" - wildcard: "i.IntervalsWildcard" +class SpanWithinQuery(QueryBase): + """ + :arg big: (required)Can be any span query. Matching spans from + `little` that are enclosed within `big` are returned. + :arg little: (required)Can be any span query. Matching spans from + `little` that are enclosed within `big` are returned. + """ + + def __init__( + self, + *, + big: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + little: Union["i.SpanQuery", Dict[str, Any], "NotSet"], + **kwargs: Any, + ): + if big != NOT_SET: + kwargs["big"] = big + if little != NOT_SET: + kwargs["little"] = little + super().__init__(**kwargs) + + +class FieldAndFormat(AttrDict[Any]): + """ + :arg field: (required)Wildcard pattern. The request returns values for + field names matching this pattern. + :arg format: Format in which the values are returned. + :arg include_unmapped: No documentation available. + """ + + def __init__( + self, + *, + field: Union[str, "InstrumentedField", "NotSet"], + format: Union[str, "NotSet"] = NOT_SET, + include_unmapped: Union[bool, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if field != NOT_SET: + kwargs["field"] = str(field) + if format != NOT_SET: + kwargs["format"] = format + if include_unmapped != NOT_SET: + kwargs["include_unmapped"] = include_unmapped + super().__init__(kwargs) + + +class FieldCollapse(AttrDict[Any]): + """ + :arg field: (required)The field to collapse the result set on + :arg inner_hits: The number of inner hits and their sort order + :arg max_concurrent_group_searches: The number of concurrent requests + allowed to retrieve the inner_hits per group + :arg collapse: No documentation available. + """ + + def __init__( + self, + *, + field: Union[str, "InstrumentedField", "NotSet"], + inner_hits: Union[ + "i.InnerHits", List["i.InnerHits"], Dict[str, Any], "NotSet" + ] = NOT_SET, + max_concurrent_group_searches: Union[int, "NotSet"] = NOT_SET, + collapse: Union["i.FieldCollapse", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if field != NOT_SET: + kwargs["field"] = str(field) + if inner_hits != NOT_SET: + kwargs["inner_hits"] = inner_hits + if max_concurrent_group_searches != NOT_SET: + kwargs["max_concurrent_group_searches"] = max_concurrent_group_searches + if collapse != NOT_SET: + kwargs["collapse"] = collapse + super().__init__(kwargs) + + +class ScriptField(AttrDict[Any]): + """ + :arg script: (required)No documentation available. + :arg ignore_failure: No documentation available. + """ + + def __init__( + self, + *, + script: Union["i.Script", Dict[str, Any], "NotSet"], + ignore_failure: Union[bool, "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if script != NOT_SET: + kwargs["script"] = script + if ignore_failure != NOT_SET: + kwargs["ignore_failure"] = ignore_failure + super().__init__(kwargs) + + +class HighlightBase(AttrDict[Any]): + """ + :arg type: No documentation available. + :arg boundary_chars: A string that contains each boundary character. + :arg boundary_max_scan: How far to scan for boundary characters. + :arg boundary_scanner: Specifies how to break the highlighted + fragments: chars, sentence, or word. Only valid for the unified + and fvh highlighters. Defaults to `sentence` for the `unified` + highlighter. Defaults to `chars` for the `fvh` highlighter. + :arg boundary_scanner_locale: Controls which locale is used to search + for sentence and word boundaries. This parameter takes a form of a + language tag, for example: `"en-US"`, `"fr-FR"`, `"ja-JP"`. + :arg force_source: No documentation available. + :arg fragmenter: Specifies how text should be broken up in highlight + snippets: `simple` or `span`. Only valid for the `plain` + highlighter. + :arg fragment_size: The size of the highlighted fragment in + characters. + :arg highlight_filter: No documentation available. + :arg highlight_query: Highlight matches for a query other than the + search query. This is especially useful if you use a rescore query + because those are not taken into account by highlighting by + default. + :arg max_fragment_length: No documentation available. + :arg max_analyzed_offset: If set to a non-negative value, highlighting + stops at this defined maximum limit. The rest of the text is not + processed, thus not highlighted and no error is returned The + `max_analyzed_offset` query setting does not override the + `index.highlight.max_analyzed_offset` setting, which prevails when + it’s set to lower value than the query setting. + :arg no_match_size: The amount of text you want to return from the + beginning of the field if there are no matching fragments to + highlight. + :arg number_of_fragments: The maximum number of fragments to return. + If the number of fragments is set to `0`, no fragments are + returned. Instead, the entire field contents are highlighted and + returned. This can be handy when you need to highlight short texts + such as a title or address, but fragmentation is not required. If + `number_of_fragments` is `0`, `fragment_size` is ignored. + :arg options: No documentation available. + :arg order: Sorts highlighted fragments by score when set to `score`. + By default, fragments will be output in the order they appear in + the field (order: `none`). Setting this option to `score` will + output the most relevant fragments first. Each highlighter applies + its own logic to compute relevancy scores. + :arg phrase_limit: Controls the number of matching phrases in a + document that are considered. Prevents the `fvh` highlighter from + analyzing too many phrases and consuming too much memory. When + using `matched_fields`, `phrase_limit` phrases per matched field + are considered. Raising the limit increases query time and + consumes more memory. Only supported by the `fvh` highlighter. + :arg post_tags: Use in conjunction with `pre_tags` to define the HTML + tags to use for the highlighted text. By default, highlighted text + is wrapped in `` and `` tags. + :arg pre_tags: Use in conjunction with `post_tags` to define the HTML + tags to use for the highlighted text. By default, highlighted text + is wrapped in `` and `` tags. + :arg require_field_match: By default, only fields that contains a + query match are highlighted. Set to `false` to highlight all + fields. + :arg tags_schema: Set to `styled` to use the built-in tag schema. + """ + + def __init__( + self, + *, + type: Union[Literal["plain", "fvh", "unified"], "NotSet"] = NOT_SET, + boundary_chars: Union[str, "NotSet"] = NOT_SET, + boundary_max_scan: Union[int, "NotSet"] = NOT_SET, + boundary_scanner: Union[ + Literal["chars", "sentence", "word"], "NotSet" + ] = NOT_SET, + boundary_scanner_locale: Union[str, "NotSet"] = NOT_SET, + force_source: Union[bool, "NotSet"] = NOT_SET, + fragmenter: Union[Literal["simple", "span"], "NotSet"] = NOT_SET, + fragment_size: Union[int, "NotSet"] = NOT_SET, + highlight_filter: Union[bool, "NotSet"] = NOT_SET, + highlight_query: Union[Query, "NotSet"] = NOT_SET, + max_fragment_length: Union[int, "NotSet"] = NOT_SET, + max_analyzed_offset: Union[int, "NotSet"] = NOT_SET, + no_match_size: Union[int, "NotSet"] = NOT_SET, + number_of_fragments: Union[int, "NotSet"] = NOT_SET, + options: Union[Mapping[str, Any], "NotSet"] = NOT_SET, + order: Union[Literal["score"], "NotSet"] = NOT_SET, + phrase_limit: Union[int, "NotSet"] = NOT_SET, + post_tags: Union[List[str], "NotSet"] = NOT_SET, + pre_tags: Union[List[str], "NotSet"] = NOT_SET, + require_field_match: Union[bool, "NotSet"] = NOT_SET, + tags_schema: Union[Literal["styled"], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if type != NOT_SET: + kwargs["type"] = type + if boundary_chars != NOT_SET: + kwargs["boundary_chars"] = boundary_chars + if boundary_max_scan != NOT_SET: + kwargs["boundary_max_scan"] = boundary_max_scan + if boundary_scanner != NOT_SET: + kwargs["boundary_scanner"] = boundary_scanner + if boundary_scanner_locale != NOT_SET: + kwargs["boundary_scanner_locale"] = boundary_scanner_locale + if force_source != NOT_SET: + kwargs["force_source"] = force_source + if fragmenter != NOT_SET: + kwargs["fragmenter"] = fragmenter + if fragment_size != NOT_SET: + kwargs["fragment_size"] = fragment_size + if highlight_filter != NOT_SET: + kwargs["highlight_filter"] = highlight_filter + if highlight_query != NOT_SET: + kwargs["highlight_query"] = highlight_query + if max_fragment_length != NOT_SET: + kwargs["max_fragment_length"] = max_fragment_length + if max_analyzed_offset != NOT_SET: + kwargs["max_analyzed_offset"] = max_analyzed_offset + if no_match_size != NOT_SET: + kwargs["no_match_size"] = no_match_size + if number_of_fragments != NOT_SET: + kwargs["number_of_fragments"] = number_of_fragments + if options != NOT_SET: + kwargs["options"] = options + if order != NOT_SET: + kwargs["order"] = order + if phrase_limit != NOT_SET: + kwargs["phrase_limit"] = phrase_limit + if post_tags != NOT_SET: + kwargs["post_tags"] = post_tags + if pre_tags != NOT_SET: + kwargs["pre_tags"] = pre_tags + if require_field_match != NOT_SET: + kwargs["require_field_match"] = require_field_match + if tags_schema != NOT_SET: + kwargs["tags_schema"] = tags_schema + super().__init__(kwargs) -class IntervalsFilter(TypedDict): - after: "i.IntervalsContainer" - before: "i.IntervalsContainer" - contained_by: "i.IntervalsContainer" - containing: "i.IntervalsContainer" - not_contained_by: "i.IntervalsContainer" - not_containing: "i.IntervalsContainer" - not_overlapping: "i.IntervalsContainer" - overlapping: "i.IntervalsContainer" - script: "i.Script" +class Highlight(HighlightBase): + """ + :arg encoder: No documentation available. + :arg fields: (required)No documentation available. + """ + + def __init__( + self, + *, + encoder: Union[Literal["default", "html"], "NotSet"] = NOT_SET, + fields: Union[ + Mapping[Union[str, "InstrumentedField"], "i.HighlightField"], + Dict[str, Any], + "NotSet", + ], + **kwargs: Any, + ): + if encoder != NOT_SET: + kwargs["encoder"] = encoder + if fields != NOT_SET: + kwargs["fields"] = str(fields) + super().__init__(**kwargs) + + +class SourceFilter(AttrDict[Any]): + """ + :arg excludes: No documentation available. + :arg includes: No documentation available. + """ + + def __init__( + self, + *, + excludes: Union[ + Union[str, "InstrumentedField"], + List[Union[str, "InstrumentedField"]], + "NotSet", + ] = NOT_SET, + includes: Union[ + Union[str, "InstrumentedField"], + List[Union[str, "InstrumentedField"]], + "NotSet", + ] = NOT_SET, + **kwargs: Any, + ): + if excludes != NOT_SET: + kwargs["excludes"] = str(excludes) + if includes != NOT_SET: + kwargs["includes"] = str(includes) + super().__init__(kwargs) + + +class SortOptions(AttrDict[Any]): + """ + :arg _score: No documentation available. + :arg _doc: No documentation available. + :arg _geo_distance: No documentation available. + :arg _script: No documentation available. + """ + + def __init__( + self, + *, + _score: Union["i.ScoreSort", Dict[str, Any], "NotSet"] = NOT_SET, + _doc: Union["i.ScoreSort", Dict[str, Any], "NotSet"] = NOT_SET, + _geo_distance: Union["i.GeoDistanceSort", Dict[str, Any], "NotSet"] = NOT_SET, + _script: Union["i.ScriptSort", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if _score != NOT_SET: + kwargs["_score"] = _score + if _doc != NOT_SET: + kwargs["_doc"] = _doc + if _geo_distance != NOT_SET: + kwargs["_geo_distance"] = _geo_distance + if _script != NOT_SET: + kwargs["_script"] = _script + super().__init__(kwargs) + + +class IntervalsContainer(AttrDict[Any]): + """ + :arg all_of: Returns matches that span a combination of other rules. + :arg any_of: Returns intervals produced by any of its sub-rules. + :arg fuzzy: Matches analyzed text. + :arg match: Matches analyzed text. + :arg prefix: Matches terms that start with a specified set of + characters. + :arg wildcard: Matches terms using a wildcard pattern. + """ + + def __init__( + self, + *, + all_of: Union["i.IntervalsAllOf", Dict[str, Any], "NotSet"] = NOT_SET, + any_of: Union["i.IntervalsAnyOf", Dict[str, Any], "NotSet"] = NOT_SET, + fuzzy: Union["i.IntervalsFuzzy", Dict[str, Any], "NotSet"] = NOT_SET, + match: Union["i.IntervalsMatch", Dict[str, Any], "NotSet"] = NOT_SET, + prefix: Union["i.IntervalsPrefix", Dict[str, Any], "NotSet"] = NOT_SET, + wildcard: Union["i.IntervalsWildcard", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if all_of != NOT_SET: + kwargs["all_of"] = all_of + if any_of != NOT_SET: + kwargs["any_of"] = any_of + if fuzzy != NOT_SET: + kwargs["fuzzy"] = fuzzy + if match != NOT_SET: + kwargs["match"] = match + if prefix != NOT_SET: + kwargs["prefix"] = prefix + if wildcard != NOT_SET: + kwargs["wildcard"] = wildcard + super().__init__(kwargs) + + +class IntervalsFilter(AttrDict[Any]): + """ + :arg after: Query used to return intervals that follow an interval + from the `filter` rule. + :arg before: Query used to return intervals that occur before an + interval from the `filter` rule. + :arg contained_by: Query used to return intervals contained by an + interval from the `filter` rule. + :arg containing: Query used to return intervals that contain an + interval from the `filter` rule. + :arg not_contained_by: Query used to return intervals that are **not** + contained by an interval from the `filter` rule. + :arg not_containing: Query used to return intervals that do **not** + contain an interval from the `filter` rule. + :arg not_overlapping: Query used to return intervals that do **not** + overlap with an interval from the `filter` rule. + :arg overlapping: Query used to return intervals that overlap with an + interval from the `filter` rule. + :arg script: Script used to return matching documents. This script + must return a boolean value: `true` or `false`. + """ + + def __init__( + self, + *, + after: Union["i.IntervalsContainer", Dict[str, Any], "NotSet"] = NOT_SET, + before: Union["i.IntervalsContainer", Dict[str, Any], "NotSet"] = NOT_SET, + contained_by: Union["i.IntervalsContainer", Dict[str, Any], "NotSet"] = NOT_SET, + containing: Union["i.IntervalsContainer", Dict[str, Any], "NotSet"] = NOT_SET, + not_contained_by: Union[ + "i.IntervalsContainer", Dict[str, Any], "NotSet" + ] = NOT_SET, + not_containing: Union[ + "i.IntervalsContainer", Dict[str, Any], "NotSet" + ] = NOT_SET, + not_overlapping: Union[ + "i.IntervalsContainer", Dict[str, Any], "NotSet" + ] = NOT_SET, + overlapping: Union["i.IntervalsContainer", Dict[str, Any], "NotSet"] = NOT_SET, + script: Union["i.Script", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if after != NOT_SET: + kwargs["after"] = after + if before != NOT_SET: + kwargs["before"] = before + if contained_by != NOT_SET: + kwargs["contained_by"] = contained_by + if containing != NOT_SET: + kwargs["containing"] = containing + if not_contained_by != NOT_SET: + kwargs["not_contained_by"] = not_contained_by + if not_containing != NOT_SET: + kwargs["not_containing"] = not_containing + if not_overlapping != NOT_SET: + kwargs["not_overlapping"] = not_overlapping + if overlapping != NOT_SET: + kwargs["overlapping"] = overlapping + if script != NOT_SET: + kwargs["script"] = script + super().__init__(kwargs) class HighlightField(HighlightBase): - fragment_offset: int - matched_fields: Union[ - Union[str, "InstrumentedField"], List[Union[str, "InstrumentedField"]] - ] - analyzer: Union[ - "analysis.CustomAnalyzer", - "analysis.FingerprintAnalyzer", - "analysis.KeywordAnalyzer", - "analysis.LanguageAnalyzer", - "analysis.NoriAnalyzer", - "analysis.PatternAnalyzer", - "analysis.SimpleAnalyzer", - "analysis.StandardAnalyzer", - "analysis.StopAnalyzer", - "analysis.WhitespaceAnalyzer", - "analysis.IcuAnalyzer", - "analysis.KuromojiAnalyzer", - "analysis.SnowballAnalyzer", - "analysis.DutchAnalyzer", - ] - - -class GeoDistanceSort(TypedDict): - mode: Literal["min", "max", "sum", "avg", "median"] - distance_type: Literal["arc", "plane"] - ignore_unmapped: bool - order: Literal["asc", "desc"] - unit: Literal["in", "ft", "yd", "mi", "nmi", "km", "m", "cm", "mm"] - nested: "i.NestedSortValue" - - -class ScoreSort(TypedDict): - order: Literal["asc", "desc"] - - -class ScriptSort(TypedDict): - order: Literal["asc", "desc"] - script: "i.Script" - type: Literal["string", "number", "version"] - mode: Literal["min", "max", "sum", "avg", "median"] - nested: "i.NestedSortValue" - - -class NestedSortValue(TypedDict): - filter: Query - max_children: int - nested: "i.NestedSortValue" - path: Union[str, "InstrumentedField"] + """ + :arg fragment_offset: No documentation available. + :arg matched_fields: No documentation available. + :arg analyzer: No documentation available. + """ + + def __init__( + self, + *, + fragment_offset: Union[int, "NotSet"] = NOT_SET, + matched_fields: Union[ + Union[str, "InstrumentedField"], + List[Union[str, "InstrumentedField"]], + "NotSet", + ] = NOT_SET, + analyzer: Union[ + "analysis.CustomAnalyzer", + "analysis.FingerprintAnalyzer", + "analysis.KeywordAnalyzer", + "analysis.LanguageAnalyzer", + "analysis.NoriAnalyzer", + "analysis.PatternAnalyzer", + "analysis.SimpleAnalyzer", + "analysis.StandardAnalyzer", + "analysis.StopAnalyzer", + "analysis.WhitespaceAnalyzer", + "analysis.IcuAnalyzer", + "analysis.KuromojiAnalyzer", + "analysis.SnowballAnalyzer", + "analysis.DutchAnalyzer", + "NotSet", + ] = NOT_SET, + **kwargs: Any, + ): + if fragment_offset != NOT_SET: + kwargs["fragment_offset"] = fragment_offset + if matched_fields != NOT_SET: + kwargs["matched_fields"] = str(matched_fields) + if analyzer != NOT_SET: + kwargs["analyzer"] = analyzer + super().__init__(**kwargs) + + +class GeoDistanceSort(AttrDict[Any]): + """ + :arg mode: No documentation available. + :arg distance_type: No documentation available. + :arg ignore_unmapped: No documentation available. + :arg order: No documentation available. + :arg unit: No documentation available. + :arg nested: No documentation available. + """ + + def __init__( + self, + *, + mode: Union[Literal["min", "max", "sum", "avg", "median"], "NotSet"] = NOT_SET, + distance_type: Union[Literal["arc", "plane"], "NotSet"] = NOT_SET, + ignore_unmapped: Union[bool, "NotSet"] = NOT_SET, + order: Union[Literal["asc", "desc"], "NotSet"] = NOT_SET, + unit: Union[ + Literal["in", "ft", "yd", "mi", "nmi", "km", "m", "cm", "mm"], "NotSet" + ] = NOT_SET, + nested: Union["i.NestedSortValue", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if mode != NOT_SET: + kwargs["mode"] = mode + if distance_type != NOT_SET: + kwargs["distance_type"] = distance_type + if ignore_unmapped != NOT_SET: + kwargs["ignore_unmapped"] = ignore_unmapped + if order != NOT_SET: + kwargs["order"] = order + if unit != NOT_SET: + kwargs["unit"] = unit + if nested != NOT_SET: + kwargs["nested"] = nested + super().__init__(kwargs) + + +class ScoreSort(AttrDict[Any]): + """ + :arg order: No documentation available. + """ + + def __init__( + self, *, order: Union[Literal["asc", "desc"], "NotSet"] = NOT_SET, **kwargs: Any + ): + if order != NOT_SET: + kwargs["order"] = order + super().__init__(kwargs) + + +class ScriptSort(AttrDict[Any]): + """ + :arg order: No documentation available. + :arg script: (required)No documentation available. + :arg type: No documentation available. + :arg mode: No documentation available. + :arg nested: No documentation available. + """ + + def __init__( + self, + *, + order: Union[Literal["asc", "desc"], "NotSet"] = NOT_SET, + script: Union["i.Script", Dict[str, Any], "NotSet"], + type: Union[Literal["string", "number", "version"], "NotSet"] = NOT_SET, + mode: Union[Literal["min", "max", "sum", "avg", "median"], "NotSet"] = NOT_SET, + nested: Union["i.NestedSortValue", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if order != NOT_SET: + kwargs["order"] = order + if script != NOT_SET: + kwargs["script"] = script + if type != NOT_SET: + kwargs["type"] = type + if mode != NOT_SET: + kwargs["mode"] = mode + if nested != NOT_SET: + kwargs["nested"] = nested + super().__init__(kwargs) + + +class NestedSortValue(AttrDict[Any]): + """ + :arg filter: No documentation available. + :arg max_children: No documentation available. + :arg nested: No documentation available. + :arg path: (required)No documentation available. + """ + + def __init__( + self, + *, + filter: Union[Query, "NotSet"] = NOT_SET, + max_children: Union[int, "NotSet"] = NOT_SET, + nested: Union["i.NestedSortValue", Dict[str, Any], "NotSet"] = NOT_SET, + path: Union[str, "InstrumentedField", "NotSet"], + **kwargs: Any, + ): + if filter != NOT_SET: + kwargs["filter"] = filter + if max_children != NOT_SET: + kwargs["max_children"] = max_children + if nested != NOT_SET: + kwargs["nested"] = nested + if path != NOT_SET: + kwargs["path"] = str(path) + super().__init__(kwargs) diff --git a/elasticsearch_dsl/query.py b/elasticsearch_dsl/query.py index 965cda1c..5909ddc1 100644 --- a/elasticsearch_dsl/query.py +++ b/elasticsearch_dsl/query.py @@ -23,6 +23,7 @@ Any, Callable, ClassVar, + Dict, List, Literal, Mapping, @@ -302,12 +303,12 @@ class Boosting(Query): Returns documents matching a `positive` query while reducing the relevance score of documents that also match a `negative` query. - :arg negative: Query used to decrease the relevance score of matching - documents. - :arg positive: Any returned documents must match this query. - :arg negative_boost: Floating point number between 0 and 1.0 used to - decrease the relevance scores of documents matching the `negative` - query. + :arg negative: (required)Query used to decrease the relevance score of + matching documents. + :arg positive: (required)Any returned documents must match this query. + :arg negative_boost: (required)Floating point number between 0 and 1.0 + used to decrease the relevance scores of documents matching the + `negative` query. """ name = "boosting" @@ -317,7 +318,12 @@ class Boosting(Query): } def __init__( - self, *, negative: Query, positive: Query, negative_boost: float, **kwargs: Any + self, + *, + negative: Union[Query, "NotSet"] = NOT_SET, + positive: Union[Query, "NotSet"] = NOT_SET, + negative_boost: Union[float, "NotSet"] = NOT_SET, + **kwargs: Any, ): super().__init__( negative=negative, @@ -353,12 +359,12 @@ class CombinedFields(Query): The `combined_fields` query supports searching multiple text fields as if their contents had been indexed into one combined field. - :arg query: Text to search for in the provided `fields`. The + :arg query: (required)Text to search for in the provided `fields`. The `combined_fields` query analyzes the provided text before performing a search. - :arg fields: List of fields to search. Field wildcard patterns are - allowed. Only `text` fields are supported, and they must all have - the same search `analyzer`. + :arg fields: (required)List of fields to search. Field wildcard + patterns are allowed. Only `text` fields are supported, and they + must all have the same search `analyzer`. :arg auto_generate_synonyms_phrase_query: If true, match phrase queries are automatically created for multi-term synonyms. :arg operator: Boolean logic used to interpret text in the query @@ -375,8 +381,8 @@ class CombinedFields(Query): def __init__( self, *, - query: str, - fields: List[Union[str, "InstrumentedField"]], + query: Union[str, "NotSet"] = NOT_SET, + fields: Union[List[Union[str, "InstrumentedField"]], "NotSet"] = NOT_SET, auto_generate_synonyms_phrase_query: Union[bool, "NotSet"] = NOT_SET, operator: Union[Literal["or", "and"], "NotSet"] = NOT_SET, minimum_should_match: Union[int, str, "NotSet"] = NOT_SET, @@ -399,10 +405,10 @@ class ConstantScore(Query): Wraps a filter query and returns every matching document with a relevance score equal to the `boost` parameter value. - :arg filter: Filter query you wish to run. Any returned documents must - match this query. Filter queries do not calculate relevance - scores. To speed up performance, Elasticsearch automatically - caches frequently used filter queries. + :arg filter: (required)Filter query you wish to run. Any returned + documents must match this query. Filter queries do not calculate + relevance scores. To speed up performance, Elasticsearch + automatically caches frequently used filter queries. """ name = "constant_score" @@ -410,7 +416,7 @@ class ConstantScore(Query): "filter": {"type": "query"}, } - def __init__(self, *, filter: Query, **kwargs: Any): + def __init__(self, *, filter: Union[Query, "NotSet"] = NOT_SET, **kwargs: Any): super().__init__(filter=filter, **kwargs) @@ -422,20 +428,23 @@ class DisMax(Query): relevance score from any matching clause, plus a tie breaking increment for any additional matching subqueries. - :arg queries: One or more query clauses. Returned documents must match - one or more of these queries. If a document matches multiple - queries, Elasticsearch uses the highest relevance score. + :arg queries: (required)One or more query clauses. Returned documents + must match one or more of these queries. If a document matches + multiple queries, Elasticsearch uses the highest relevance score. :arg tie_breaker: Floating point number between 0 and 1.0 used to increase the relevance scores of documents matching multiple query clauses. """ name = "dis_max" + _param_defs = { + "queries": {"type": "query", "multi": True}, + } def __init__( self, *, - queries: List[Query], + queries: Union[List[Query], "NotSet"] = NOT_SET, tie_breaker: Union[float, "NotSet"] = NOT_SET, **kwargs: Any, ): @@ -447,11 +456,28 @@ class DistanceFeature(Query): Boosts the relevance score of documents closer to a provided origin date or point. For example, you can use this query to give more weight to documents closer to a certain date or location. + + :arg untyped: An instance of ``UntypedDistanceFeatureQuery``. + :arg geo: An instance of ``GeoDistanceFeatureQuery``. + :arg date: An instance of ``DateDistanceFeatureQuery``. """ name = "distance_feature" - def __init__(self, **kwargs: Any): + def __init__( + self, + *, + untyped: Union["i.UntypedDistanceFeatureQuery", "NotSet"] = NOT_SET, + geo: Union["i.GeoDistanceFeatureQuery", "NotSet"] = NOT_SET, + date: Union["i.DateDistanceFeatureQuery", "NotSet"] = NOT_SET, + **kwargs: Any, + ): + if untyped != NOT_SET: + kwargs = untyped + elif geo != NOT_SET: + kwargs = geo + elif date != NOT_SET: + kwargs = date super().__init__(**kwargs) @@ -459,12 +485,17 @@ class Exists(Query): """ Returns documents that contain an indexed value for a field. - :arg field: Name of the field you wish to search. + :arg field: (required)Name of the field you wish to search. """ name = "exists" - def __init__(self, *, field: Union[str, "InstrumentedField"], **kwargs: Any): + def __init__( + self, + *, + field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(field=field, **kwargs) @@ -489,6 +520,8 @@ class FunctionScore(Query): name = "function_score" _param_defs = { "query": {"type": "query"}, + "filter": {"type": "query"}, + "functions": {"type": "score_function", "multi": True}, } def __init__( @@ -497,7 +530,9 @@ def __init__( boost_mode: Union[ Literal["multiply", "replace", "sum", "avg", "max", "min"], "NotSet" ] = NOT_SET, - functions: Union[List["i.FunctionScoreContainer"], "NotSet"] = NOT_SET, + functions: Union[ + List["i.FunctionScoreContainer"], Dict[str, Any], "NotSet" + ] = NOT_SET, max_boost: Union[float, "NotSet"] = NOT_SET, min_score: Union[float, "NotSet"] = NOT_SET, query: Union[Query, "NotSet"] = NOT_SET, @@ -506,7 +541,7 @@ def __init__( ] = NOT_SET, **kwargs: Any, ): - if functions is None: + if functions == NOT_SET: functions = [] for name in ScoreFunction._classes: if name in kwargs: @@ -548,7 +583,7 @@ class GeoBoundingBox(Query): """ Matches geo_point and geo_shape values that intersect a bounding box. - :arg type: None + :arg type: No documentation available. :arg validation_method: Set to `IGNORE_MALFORMED` to accept geo points with invalid latitude or longitude. Set to `COERCE` to also try to infer correct latitude or longitude. @@ -582,9 +617,9 @@ class GeoDistance(Query): Matches `geo_point` and `geo_shape` values within a given distance of a geopoint. - :arg distance: The radius of the circle centred on the specified - location. Points which fall into this circle are considered to be - matches. + :arg distance: (required)The radius of the circle centred on the + specified location. Points which fall into this circle are + considered to be matches. :arg distance_type: How to compute the distance. Set to `plane` for a faster calculation that's inaccurate on long distances and close to the poles. @@ -601,7 +636,7 @@ class GeoDistance(Query): def __init__( self, *, - distance: str, + distance: Union[str, "NotSet"] = NOT_SET, distance_type: Union[Literal["arc", "plane"], "NotSet"] = NOT_SET, validation_method: Union[ Literal["coerce", "ignore_malformed", "strict"], "NotSet" @@ -622,8 +657,8 @@ class GeoPolygon(Query): """ No documentation available. - :arg validation_method: None - :arg ignore_unmapped: None + :arg validation_method: No documentation available. + :arg ignore_unmapped: No documentation available. """ name = "geo_polygon" @@ -667,10 +702,11 @@ class HasChild(Query): Returns parent documents whose joined child documents match a provided query. - :arg query: Query you wish to run on child documents of the `type` - field. If a child document matches the search, the query returns - the parent document. - :arg type: Name of the child relationship mapped for the `join` field. + :arg query: (required)Query you wish to run on child documents of the + `type` field. If a child document matches the search, the query + returns the parent document. + :arg type: (required)Name of the child relationship mapped for the + `join` field. :arg ignore_unmapped: Indicates whether to ignore an unmapped `type` and not return any documents instead of an error. :arg inner_hits: If defined, each search hit will contain inner hits. @@ -694,10 +730,10 @@ class HasChild(Query): def __init__( self, *, - query: Query, - type: str, + query: Union[Query, "NotSet"] = NOT_SET, + type: Union[str, "NotSet"] = NOT_SET, ignore_unmapped: Union[bool, "NotSet"] = NOT_SET, - inner_hits: Union["i.InnerHits", "NotSet"] = NOT_SET, + inner_hits: Union["i.InnerHits", Dict[str, Any], "NotSet"] = NOT_SET, max_children: Union[int, "NotSet"] = NOT_SET, min_children: Union[int, "NotSet"] = NOT_SET, score_mode: Union[ @@ -722,9 +758,9 @@ class HasParent(Query): Returns child documents whose joined parent document matches a provided query. - :arg parent_type: Name of the parent relationship mapped for the - `join` field. - :arg query: Query you wish to run on parent documents of the + :arg parent_type: (required)Name of the parent relationship mapped for + the `join` field. + :arg query: (required)Query you wish to run on parent documents of the `parent_type` field. If a parent document matches the search, the query returns its child documents. :arg ignore_unmapped: Indicates whether to ignore an unmapped @@ -744,10 +780,10 @@ class HasParent(Query): def __init__( self, *, - parent_type: str, - query: Query, + parent_type: Union[str, "NotSet"] = NOT_SET, + query: Union[Query, "NotSet"] = NOT_SET, ignore_unmapped: Union[bool, "NotSet"] = NOT_SET, - inner_hits: Union["i.InnerHits", "NotSet"] = NOT_SET, + inner_hits: Union["i.InnerHits", Dict[str, Any], "NotSet"] = NOT_SET, score: Union[bool, "NotSet"] = NOT_SET, **kwargs: Any, ): @@ -804,7 +840,7 @@ class Knn(Query): similarity metric. knn query finds nearest vectors through approximate search on indexed dense_vectors. - :arg field: The name of the vector field to search against + :arg field: (required)The name of the vector field to search against :arg query_vector: The query vector :arg query_vector_builder: The query vector builder. You must provide a query_vector_builder or query_vector, but not both. @@ -824,9 +860,11 @@ class Knn(Query): def __init__( self, *, - field: Union[str, "InstrumentedField"], + field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, query_vector: Union[List[float], "NotSet"] = NOT_SET, - query_vector_builder: Union["i.QueryVectorBuilder", "NotSet"] = NOT_SET, + query_vector_builder: Union[ + "i.QueryVectorBuilder", Dict[str, Any], "NotSet" + ] = NOT_SET, num_candidates: Union[int, "NotSet"] = NOT_SET, k: Union[int, "NotSet"] = NOT_SET, filter: Union[Query, List[Query], "NotSet"] = NOT_SET, @@ -989,8 +1027,8 @@ class MoreLikeThis(Query): """ Returns documents that are "like" a given set of documents. - :arg like: Specifies free form text and/or a single or multiple - documents for which you want to find similar documents. + :arg like: (required)Specifies free form text and/or a single or + multiple documents for which you want to find similar documents. :arg analyzer: The analyzer that is used to analyze the free form text. Defaults to the analyzer associated with the first field in fields. @@ -1020,13 +1058,13 @@ class MoreLikeThis(Query): are ignored from the input document. :arg min_word_length: The minimum word length below which the terms are ignored. - :arg routing: None + :arg routing: No documentation available. :arg stop_words: An array of stop words. Any word in this set is ignored. :arg unlike: Used in combination with `like` to exclude documents that match a set of terms. - :arg version: None - :arg version_type: None + :arg version: No documentation available. + :arg version_type: No documentation available. """ name = "more_like_this" @@ -1034,7 +1072,12 @@ class MoreLikeThis(Query): def __init__( self, *, - like: Union[Union[str, "i.LikeDocument"], List[Union[str, "i.LikeDocument"]]], + like: Union[ + Union[str, "i.LikeDocument"], + List[Union[str, "i.LikeDocument"]], + Dict[str, Any], + "NotSet", + ] = NOT_SET, analyzer: Union[str, "NotSet"] = NOT_SET, boost_terms: Union[float, "NotSet"] = NOT_SET, fail_on_unsupported_field: Union[bool, "NotSet"] = NOT_SET, @@ -1050,7 +1093,10 @@ def __init__( routing: Union[str, "NotSet"] = NOT_SET, stop_words: Union[str, List[str], "NotSet"] = NOT_SET, unlike: Union[ - Union[str, "i.LikeDocument"], List[Union[str, "i.LikeDocument"]], "NotSet" + Union[str, "i.LikeDocument"], + List[Union[str, "i.LikeDocument"]], + Dict[str, Any], + "NotSet", ] = NOT_SET, version: Union[int, "NotSet"] = NOT_SET, version_type: Union[ @@ -1087,13 +1133,13 @@ class MultiMatch(Query): value across multiple fields. The provided text is analyzed before matching. - :arg query: Text, number, boolean value or date you wish to find in - the provided field. + :arg query: (required)Text, number, boolean value or date you wish to + find in the provided field. :arg analyzer: Analyzer used to convert the text in the query value into tokens. :arg auto_generate_synonyms_phrase_query: If `true`, match phrase queries are automatically created for multi-term synonyms. - :arg cutoff_frequency: None + :arg cutoff_frequency: No documentation available. :arg fields: The fields to be queried. Defaults to the `index.query.default_field` index settings, which in turn defaults to `*`. @@ -1128,7 +1174,7 @@ class MultiMatch(Query): def __init__( self, *, - query: str, + query: Union[str, "NotSet"] = NOT_SET, analyzer: Union[str, "NotSet"] = NOT_SET, auto_generate_synonyms_phrase_query: Union[bool, "NotSet"] = NOT_SET, cutoff_frequency: Union[float, "NotSet"] = NOT_SET, @@ -1188,8 +1234,9 @@ class Nested(Query): Wraps another query to search nested fields. If an object matches the search, the nested query returns the root parent document. - :arg path: Path to the nested object you wish to search. - :arg query: Query you wish to run on nested objects in the path. + :arg path: (required)Path to the nested object you wish to search. + :arg query: (required)Query you wish to run on nested objects in the + path. :arg ignore_unmapped: Indicates whether to ignore an unmapped path and not return any documents instead of an error. :arg inner_hits: If defined, each search hit will contain inner hits. @@ -1205,10 +1252,10 @@ class Nested(Query): def __init__( self, *, - path: Union[str, "InstrumentedField"], - query: Query, + path: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + query: Union[Query, "NotSet"] = NOT_SET, ignore_unmapped: Union[bool, "NotSet"] = NOT_SET, - inner_hits: Union["i.InnerHits", "NotSet"] = NOT_SET, + inner_hits: Union["i.InnerHits", Dict[str, Any], "NotSet"] = NOT_SET, score_mode: Union[ Literal["none", "avg", "sum", "max", "min"], "NotSet" ] = NOT_SET, @@ -1251,8 +1298,8 @@ class Percolate(Query): """ Matches queries stored in an index. - :arg field: Field that holds the indexed queries. The field must use - the `percolator` mapping type. + :arg field: (required)Field that holds the indexed queries. The field + must use the `percolator` mapping type. :arg document: The source of the document being percolated. :arg documents: An array of sources of the documents being percolated. :arg id: The ID of a stored document to percolate. @@ -1269,7 +1316,7 @@ class Percolate(Query): def __init__( self, *, - field: Union[str, "InstrumentedField"], + field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, document: Any = NOT_SET, documents: Union[List[Any], "NotSet"] = NOT_SET, id: Union[str, "NotSet"] = NOT_SET, @@ -1299,8 +1346,8 @@ class Pinned(Query): Promotes selected documents to rank higher than those matching a given query. - :arg organic: Any choice of query used to rank documents which will be - ranked below the "pinned" documents. + :arg organic: (required)Any choice of query used to rank documents + which will be ranked below the "pinned" documents. :arg ids: Document IDs listed in the order they are to appear in results. Required if `docs` is not specified. :arg docs: Documents listed in the order they are to appear in @@ -1315,9 +1362,9 @@ class Pinned(Query): def __init__( self, *, - organic: Query, + organic: Union[Query, "NotSet"] = NOT_SET, ids: Union[List[str], "NotSet"] = NOT_SET, - docs: Union[List["i.PinnedDoc"], "NotSet"] = NOT_SET, + docs: Union[List["i.PinnedDoc"], Dict[str, Any], "NotSet"] = NOT_SET, **kwargs: Any, ): super().__init__(organic=organic, ids=ids, docs=docs, **kwargs) @@ -1349,7 +1396,8 @@ class QueryString(Query): Returns documents based on a provided query string, using a parser with a strict syntax. - :arg query: Query string you wish to parse and use for search. + :arg query: (required)Query string you wish to parse and use for + search. :arg allow_leading_wildcard: If `true`, the wildcard characters `*` and `?` are allowed as the first character of the query string. :arg analyzer: Analyzer used to convert text in the query string into @@ -1366,7 +1414,7 @@ class QueryString(Query): the query string if no operators are specified. :arg enable_position_increments: If `true`, enable position increments in queries constructed from a `query_string` search. - :arg escape: None + :arg escape: No documentation available. :arg fields: Array of fields to search. Supports wildcards (`*`). :arg fuzziness: Maximum edit distance allowed for fuzzy matching. :arg fuzzy_max_expansions: Maximum number of terms to which the query @@ -1404,7 +1452,7 @@ class QueryString(Query): def __init__( self, *, - query: str, + query: Union[str, "NotSet"] = NOT_SET, allow_leading_wildcard: Union[bool, "NotSet"] = NOT_SET, analyzer: Union[str, "NotSet"] = NOT_SET, analyze_wildcard: Union[bool, "NotSet"] = NOT_SET, @@ -1503,8 +1551,8 @@ class RankFeature(Query): Boosts the relevance score of documents based on the numeric value of a `rank_feature` or `rank_features` field. - :arg field: `rank_feature` or `rank_features` field used to boost - relevance scores. + :arg field: (required)`rank_feature` or `rank_features` field used to + boost relevance scores. :arg saturation: Saturation function used to boost relevance scores based on the value of the rank feature `field`. :arg log: Logarithmic function used to boost relevance scores based on @@ -1520,11 +1568,19 @@ class RankFeature(Query): def __init__( self, *, - field: Union[str, "InstrumentedField"], - saturation: Union["i.RankFeatureFunctionSaturation", "NotSet"] = NOT_SET, - log: Union["i.RankFeatureFunctionLogarithm", "NotSet"] = NOT_SET, - linear: Union["i.RankFeatureFunctionLinear", "NotSet"] = NOT_SET, - sigmoid: Union["i.RankFeatureFunctionSigmoid", "NotSet"] = NOT_SET, + field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, + saturation: Union[ + "i.RankFeatureFunctionSaturation", Dict[str, Any], "NotSet" + ] = NOT_SET, + log: Union[ + "i.RankFeatureFunctionLogarithm", Dict[str, Any], "NotSet" + ] = NOT_SET, + linear: Union[ + "i.RankFeatureFunctionLinear", Dict[str, Any], "NotSet" + ] = NOT_SET, + sigmoid: Union[ + "i.RankFeatureFunctionSigmoid", Dict[str, Any], "NotSet" + ] = NOT_SET, **kwargs: Any, ): super().__init__( @@ -1562,9 +1618,9 @@ class Rule(Query): """ No documentation available. - :arg ruleset_ids: None - :arg match_criteria: None - :arg organic: None + :arg ruleset_ids: (required)No documentation available. + :arg match_criteria: (required)No documentation available. + :arg organic: (required)No documentation available. """ name = "rule" @@ -1575,9 +1631,9 @@ class Rule(Query): def __init__( self, *, - ruleset_ids: List[str], - match_criteria: Any, - organic: Query, + ruleset_ids: Union[List[str], "NotSet"] = NOT_SET, + match_criteria: Any = NOT_SET, + organic: Union[Query, "NotSet"] = NOT_SET, **kwargs: Any, ): super().__init__( @@ -1593,13 +1649,18 @@ class Script(Query): Filters documents based on a provided script. The script query is typically used in a filter context. - :arg script: Contains a script to run as a query. This script must - return a boolean value, `true` or `false`. + :arg script: (required)Contains a script to run as a query. This + script must return a boolean value, `true` or `false`. """ name = "script" - def __init__(self, *, script: "i.Script", **kwargs: Any): + def __init__( + self, + *, + script: Union["i.Script", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(script=script, **kwargs) @@ -1607,9 +1668,9 @@ class ScriptScore(Query): """ Uses a script to provide a custom score for returned documents. - :arg query: Query used to return documents. - :arg script: Script used to compute the score of documents returned by - the query. Important: final relevance scores from the + :arg query: (required)Query used to return documents. + :arg script: (required)Script used to compute the score of documents + returned by the query. Important: final relevance scores from the `script_score` query cannot be negative. :arg min_score: Documents with a score lower than this floating point number are excluded from the search results. @@ -1623,8 +1684,8 @@ class ScriptScore(Query): def __init__( self, *, - query: Query, - script: "i.Script", + query: Union[Query, "NotSet"] = NOT_SET, + script: Union["i.Script", Dict[str, Any], "NotSet"] = NOT_SET, min_score: Union[float, "NotSet"] = NOT_SET, **kwargs: Any, ): @@ -1635,14 +1696,20 @@ class Semantic(Query): """ A semantic query to semantic_text field types - :arg query: The query text - :arg field: The field to query, which must be a semantic_text field - type + :arg query: (required)The query text + :arg field: (required)The field to query, which must be a + semantic_text field type """ name = "semantic" - def __init__(self, *, query: str, field: str, **kwargs: Any): + def __init__( + self, + *, + query: Union[str, "NotSet"] = NOT_SET, + field: Union[str, "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(query=query, field=field, **kwargs) @@ -1667,8 +1734,8 @@ class SimpleQueryString(Query): Returns documents based on a provided query string, using a parser with a limited but fault-tolerant syntax. - :arg query: Query string in the simple query string syntax you wish to - parse and use for search. + :arg query: (required)Query string in the simple query string syntax + you wish to parse and use for search. :arg analyzer: Analyzer used to convert text in the query string into tokens. :arg analyze_wildcard: If `true`, the query attempts to analyze @@ -1704,13 +1771,13 @@ class SimpleQueryString(Query): def __init__( self, *, - query: str, + query: Union[str, "NotSet"] = NOT_SET, analyzer: Union[str, "NotSet"] = NOT_SET, analyze_wildcard: Union[bool, "NotSet"] = NOT_SET, auto_generate_synonyms_phrase_query: Union[bool, "NotSet"] = NOT_SET, default_operator: Union[Literal["and", "or"], "NotSet"] = NOT_SET, fields: Union[List[Union[str, "InstrumentedField"]], "NotSet"] = NOT_SET, - flags: Union["i.PipeSeparatedFlags", "NotSet"] = NOT_SET, + flags: Union["i.PipeSeparatedFlags", Dict[str, Any], "NotSet"] = NOT_SET, fuzzy_max_expansions: Union[int, "NotSet"] = NOT_SET, fuzzy_prefix_length: Union[int, "NotSet"] = NOT_SET, fuzzy_transpositions: Union[bool, "NotSet"] = NOT_SET, @@ -1741,15 +1808,21 @@ class SpanContaining(Query): """ Returns matches which enclose another span query. - :arg little: Can be any span query. Matching spans from `big` that - contain matches from `little` are returned. - :arg big: Can be any span query. Matching spans from `big` that - contain matches from `little` are returned. + :arg little: (required)Can be any span query. Matching spans from + `big` that contain matches from `little` are returned. + :arg big: (required)Can be any span query. Matching spans from `big` + that contain matches from `little` are returned. """ name = "span_containing" - def __init__(self, *, little: "i.SpanQuery", big: "i.SpanQuery", **kwargs: Any): + def __init__( + self, + *, + little: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + big: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(little=little, big=big, **kwargs) @@ -1758,8 +1831,8 @@ class SpanFieldMasking(Query): Wrapper to allow span queries to participate in composite single-field span queries by _lying_ about their search field. - :arg query: None - :arg field: None + :arg query: (required)No documentation available. + :arg field: (required)No documentation available. """ name = "span_field_masking" @@ -1767,8 +1840,8 @@ class SpanFieldMasking(Query): def __init__( self, *, - query: "i.SpanQuery", - field: Union[str, "InstrumentedField"], + query: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, **kwargs: Any, ): super().__init__(query=query, field=field, **kwargs) @@ -1778,13 +1851,20 @@ class SpanFirst(Query): """ Matches spans near the beginning of a field. - :arg match: Can be any other span type query. - :arg end: Controls the maximum end position permitted in a match. + :arg match: (required)Can be any other span type query. + :arg end: (required)Controls the maximum end position permitted in a + match. """ name = "span_first" - def __init__(self, *, match: "i.SpanQuery", end: int, **kwargs: Any): + def __init__( + self, + *, + match: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + end: Union[int, "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(match=match, end=end, **kwargs) @@ -1794,8 +1874,8 @@ class SpanMulti(Query): `prefix`, `range`, or `regexp` query) as a `span` query, so it can be nested. - :arg match: Should be a multi term query (one of `wildcard`, `fuzzy`, - `prefix`, `range`, or `regexp` query). + :arg match: (required)Should be a multi term query (one of `wildcard`, + `fuzzy`, `prefix`, `range`, or `regexp` query). """ name = "span_multi" @@ -1803,7 +1883,7 @@ class SpanMulti(Query): "match": {"type": "query"}, } - def __init__(self, *, match: Query, **kwargs: Any): + def __init__(self, *, match: Union[Query, "NotSet"] = NOT_SET, **kwargs: Any): super().__init__(match=match, **kwargs) @@ -1813,7 +1893,7 @@ class SpanNear(Query): maximum number of intervening unmatched positions, as well as whether matches are required to be in-order. - :arg clauses: Array of one or more other span type queries. + :arg clauses: (required)Array of one or more other span type queries. :arg in_order: Controls whether matches are required to be in-order. :arg slop: Controls the maximum number of intervening unmatched positions permitted. @@ -1824,7 +1904,7 @@ class SpanNear(Query): def __init__( self, *, - clauses: List["i.SpanQuery"], + clauses: Union[List["i.SpanQuery"], Dict[str, Any], "NotSet"] = NOT_SET, in_order: Union[bool, "NotSet"] = NOT_SET, slop: Union[int, "NotSet"] = NOT_SET, **kwargs: Any, @@ -1838,9 +1918,9 @@ class SpanNot(Query): within x tokens before (controlled by the parameter `pre`) or y tokens after (controlled by the parameter `post`) another span query. - :arg exclude: Span query whose matches must not overlap those - returned. - :arg include: Span query whose matches are filtered. + :arg exclude: (required)Span query whose matches must not overlap + those returned. + :arg include: (required)Span query whose matches are filtered. :arg dist: The number of tokens from within the include span that can’t have overlap with the exclude span. Equivalent to setting both `pre` and `post`. @@ -1855,8 +1935,8 @@ class SpanNot(Query): def __init__( self, *, - exclude: "i.SpanQuery", - include: "i.SpanQuery", + exclude: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + include: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, dist: Union[int, "NotSet"] = NOT_SET, post: Union[int, "NotSet"] = NOT_SET, pre: Union[int, "NotSet"] = NOT_SET, @@ -1871,12 +1951,17 @@ class SpanOr(Query): """ Matches the union of its span clauses. - :arg clauses: Array of one or more other span type queries. + :arg clauses: (required)Array of one or more other span type queries. """ name = "span_or" - def __init__(self, *, clauses: List["i.SpanQuery"], **kwargs: Any): + def __init__( + self, + *, + clauses: Union[List["i.SpanQuery"], Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(clauses=clauses, **kwargs) @@ -1905,15 +1990,21 @@ class SpanWithin(Query): """ Returns matches which are enclosed inside another span query. - :arg little: Can be any span query. Matching spans from `little` that - are enclosed within `big` are returned. - :arg big: Can be any span query. Matching spans from `little` that are - enclosed within `big` are returned. + :arg little: (required)Can be any span query. Matching spans from + `little` that are enclosed within `big` are returned. + :arg big: (required)Can be any span query. Matching spans from + `little` that are enclosed within `big` are returned. """ name = "span_within" - def __init__(self, *, little: "i.SpanQuery", big: "i.SpanQuery", **kwargs: Any): + def __init__( + self, + *, + little: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + big: Union["i.SpanQuery", Dict[str, Any], "NotSet"] = NOT_SET, + **kwargs: Any, + ): super().__init__(little=little, big=big, **kwargs) @@ -1923,9 +2014,9 @@ class SparseVector(Query): convert a query into a list of token-weight pairs, queries against a sparse vector field. - :arg field: The name of the field that contains the token-weight pairs - to be searched against. This field must be a mapped sparse_vector - field. + :arg field: (required)The name of the field that contains the token- + weight pairs to be searched against. This field must be a mapped + sparse_vector field. :arg query_vector: Dictionary of precomputed sparse vectors and their associated weights. Only one of inference_id or query_vector may be supplied in a request. @@ -1953,12 +2044,14 @@ class SparseVector(Query): def __init__( self, *, - field: Union[str, "InstrumentedField"], + field: Union[str, "InstrumentedField", "NotSet"] = NOT_SET, query_vector: Union[Mapping[str, float], "NotSet"] = NOT_SET, inference_id: Union[str, "NotSet"] = NOT_SET, query: Union[str, "NotSet"] = NOT_SET, prune: Union[bool, "NotSet"] = NOT_SET, - pruning_config: Union["i.TokenPruningConfig", "NotSet"] = NOT_SET, + pruning_config: Union[ + "i.TokenPruningConfig", Dict[str, Any], "NotSet" + ] = NOT_SET, **kwargs: Any, ): super().__init__( @@ -2105,13 +2198,13 @@ class Wrapper(Query): """ A query that accepts any other query as base64 encoded string. - :arg query: A base64 encoded query. The binary data format can be any - of JSON, YAML, CBOR or SMILE encodings + :arg query: (required)A base64 encoded query. The binary data format + can be any of JSON, YAML, CBOR or SMILE encodings """ name = "wrapper" - def __init__(self, *, query: str, **kwargs: Any): + def __init__(self, *, query: Union[str, "NotSet"] = NOT_SET, **kwargs: Any): super().__init__(query=query, **kwargs) @@ -2119,10 +2212,10 @@ class Type(Query): """ No documentation available. - :arg value: None + :arg value: (required)No documentation available. """ name = "type" - def __init__(self, *, value: str, **kwargs: Any): + def __init__(self, *, value: Union[str, "NotSet"] = NOT_SET, **kwargs: Any): super().__init__(value=value, **kwargs) diff --git a/utils/generator.py b/utils/generator.py index 98439a6e..c5c5e97b 100644 --- a/utils/generator.py +++ b/utils/generator.py @@ -46,6 +46,15 @@ def wrapped_doc(text, width=70, initial_indent="", subsequent_indent=""): ) +def add_dict_type(type_): + """Add Dict[str, Any] to a Python type hint.""" + if type_.startswith("Union["): + type_ = f"{type_[:-1]}, Dict[str, Any]]" + else: + type_ = f"Union[{type_}, Dict[str, Any]]" + return type_ + + def add_not_set(type_): """Add NotSet to a Python type hint.""" if type_.startswith("Union["): @@ -118,7 +127,7 @@ def get_python_type(self, schema_type): elif schema_type["kind"] == "array_of": type_, param = self.get_python_type(schema_type["value"]) - return f"List[{type_}]", None + return f"List[{type_}]", {**param, "multi": True} if param else None elif schema_type["kind"] == "dictionary_of": key_type, key_param = self.get_python_type(schema_type["key"]) @@ -176,108 +185,129 @@ def get_python_type(self, schema_type): raise RuntimeError(f"Cannot find Python type for {schema_type}") - -def generate_query_classes(schema, filename): - classes = [] - query_container = schema.find_type("QueryContainer", "_types.query_dsl") - for p in query_container["properties"]: - k = {"schema": p, "name": "".join([w.title() for w in p["name"].split("_")])} - k["docstring"] = wrapped_doc(p.get("description")) - kind = p["type"]["kind"] - if kind == "instance_of": - instance = schema.find_type( - p["type"]["type"]["name"], p["type"]["type"]["namespace"] - ) - if instance["kind"] == "interface": - k["kwargs"] = [] - k["params"] = [] - for arg in instance["properties"]: - type_, param = schema.get_python_type(arg["type"]) - if arg["required"] is False and type_ != "Any": - type_ = add_not_set(type_) - doc = wrapped_doc( - f":arg {arg['name']}: {arg.get('description')}", - subsequent_indent=" ", - ) - if arg["required"] is False: - k["kwargs"].append( - { - "name": RESERVED.get(arg["name"], arg["name"]), - "type": type_, - "doc": doc, - "required": False, - } - ) - else: - i = 0 - for i in range(len(k["kwargs"])): - if k["kwargs"][i]["required"] is False: - break - k["kwargs"].insert( - i, - { - "name": RESERVED.get(arg["name"], arg["name"]), - "type": type_, - "doc": doc, - "required": True, - }, - ) - if param is not None: - k["params"].append({"name": arg["name"], "param": param}) - - elif kind == "dictionary_of": - key_type, _ = schema.get_python_type(p["type"]["key"]) - if "InstrumentedField" in key_type: - value_type, _ = schema.get_python_type(p["type"]["value"]) - if p["type"]["singleKey"]: - k["kwargs"] = [ - { - "name": "_field", - "type": add_not_set(key_type), - "doc": [":arg _field: The field to use in this query."], - "required": False, - }, - { - "name": "_value", - "type": add_not_set(value_type), - "doc": [":arg _value: The query value for the field."], - "required": False, - }, - ] - k["has_field"] = True + def argument_to_python_type(self, arg): + try: + type_, param = schema.get_python_type(arg["type"]) + except RuntimeError: + type_ = "Any" + param = None + if type_ != "Any": + if "i." in type_: + type_ = add_dict_type(type_) + type_ = add_not_set(type_) + required = "(required)" if arg["required"] else "" + doc = wrapped_doc( + f":arg {arg['name']}: {required}{arg.get('description', 'No documentation available.')}", + subsequent_indent=" ", + ) + kwarg = { + "name": RESERVED.get(arg["name"], arg["name"]), + "type": type_, + "doc": doc, + "required": arg["required"], + } + if param is not None: + param = {"name": arg["name"], "param": param} + return kwarg, param + + def instance_of_to_python_class(self, p, k): + instance = schema.find_type( + p["type"]["type"]["name"], p["type"]["type"]["namespace"] + ) + if instance["kind"] == "interface": + k["kwargs"] = [] + k["params"] = [] + for p in instance["properties"]: + kwarg, param = self.argument_to_python_type(p) + if kwarg["required"]: + i = 0 + for i in range(len(k["kwargs"])): + if k["kwargs"][i]["required"] is False: + break + k["kwargs"].insert(i, kwarg) else: - k["kwargs"] = [ + k["kwargs"].append(kwarg) + if param: + k["params"].append(param) + elif instance["kind"] == "type_alias": + if ( + "codegenNames" in instance + and instance["type"]["kind"] == "union_of" + and len(instance["type"]["items"]) == len(instance["codegenNames"]) + ): + k["kwargs"] = [] + for name, type_ in zip( + instance["codegenNames"], instance["type"]["items"] + ): + python_type, _ = self.get_python_type(type_) + k["kwargs"].append( { - "name": "_fields", - "type": f"Optional[Mapping[{key_type}, {value_type}]]", + "name": name, + "type": f'Union[{python_type}, "NotSet"]', "doc": [ - ":arg _fields: A dictionary of fields with their values." + f":arg {name}: An instance of ``{python_type[3:-1]}``." ], "required": False, - }, - ] - k["has_fields"] = True + } + ) + k["has_type_alias"] = True else: - raise RuntimeError(f"Cannot generate code for type {p['type']}") - + raise RuntimeError("Cannot generate code for non-enum type aliases") else: - raise RuntimeError(f"Cannot generate code for type {p['type']}") - classes.append(k) - - with open(filename, "wt") as f: - f.write( - query_py.render( - classes=classes, parent="Query", interfaces=sorted(schema.interfaces) + raise RuntimeError( + f"Cannot generate code for instances of kind '{instance['kind']}'" ) - ) - print(f"Generated {filename}.") + return k + + def dictionary_of_to_python_class(self, p, k): + key_type, _ = schema.get_python_type(p["type"]["key"]) + if "InstrumentedField" in key_type: + value_type, _ = schema.get_python_type(p["type"]["value"]) + if p["type"]["singleKey"]: + k["kwargs"] = [ + { + "name": "_field", + "type": add_not_set(key_type), + "doc": [":arg _field: The field to use in this query."], + "required": False, + }, + { + "name": "_value", + "type": add_not_set(value_type), + "doc": [":arg _value: The query value for the field."], + "required": False, + }, + ] + k["has_field"] = True + else: + k["kwargs"] = [ + { + "name": "_fields", + "type": f"Optional[Mapping[{key_type}, {value_type}]]", + "doc": [ + ":arg _fields: A dictionary of fields with their values." + ], + "required": False, + }, + ] + k["has_fields"] = True + else: + raise RuntimeError(f"Cannot generate code for type {p['type']}") + return k + def property_to_python_class(self, p): + k = {"schema": p, "name": "".join([w.title() for w in p["name"].split("_")])} + k["docstring"] = wrapped_doc(p.get("description")) + kind = p["type"]["kind"] + if kind == "instance_of": + k = self.instance_of_to_python_class(p, k) + elif kind == "dictionary_of": + k = self.dictionary_of_to_python_class(p, k) + else: + raise RuntimeError(f"Cannot generate code for type {p['type']}") + return k -def generate_interfaces(schema, interfaces, filename): - classes = {} - for interface in interfaces: - if interface == "PipeSeparatedFlags": - continue # handled as a special case + def interface_to_python_class(self, interface, interfaces): type_ = schema.find_type(interface) if type_["kind"] != "interface": raise RuntimeError(f"Type {interface} is not an interface") @@ -294,12 +324,35 @@ def generate_interfaces(schema, interfaces, filename): else: parent = None k = {"name": interface, "parent": parent, "properties": []} - schema.reset_interfaces() - for p in type_["properties"]: - type_, param = schema.get_python_type(p["type"]) - k["properties"].append( - {"name": RESERVED.get(p["name"], p["name"]), "type": type_} + for arg in type_["properties"]: + arg_type, _ = schema.argument_to_python_type(arg) + k["properties"].append(arg_type) + return k + + +def generate_query_classes(schema, filename): + classes = [] + query_container = schema.find_type("QueryContainer", "_types.query_dsl") + for p in query_container["properties"]: + k = schema.property_to_python_class(p) + classes.append(k) + + with open(filename, "wt") as f: + f.write( + query_py.render( + classes=classes, parent="Query", interfaces=sorted(schema.interfaces) ) + ) + print(f"Generated {filename}.") + + +def generate_interfaces(schema, interfaces, filename): + classes = {} + for interface in interfaces: + if interface == "PipeSeparatedFlags": + continue # handled as a special case + schema.reset_interfaces() + k = schema.interface_to_python_class(interface, interfaces) for new_interface in schema.interfaces: if new_interface not in interfaces: interfaces.append(new_interface) diff --git a/utils/templates/dsl_classes.tpl b/utils/templates/dsl_classes.tpl index 44af7c4a..7339e471 100644 --- a/utils/templates/dsl_classes.tpl +++ b/utils/templates/dsl_classes.tpl @@ -19,6 +19,10 @@ class {{ k.name }}({{ parent }}): {% for param in k.params %} "{{ param.name }}": {{ param.param }}, {% endfor %} + {% if k.name == "FunctionScore" %} + "filter": {"type": "query"}, + "functions": {"type": "score_function", "multi": True}, + {% endif %} } {% endif %} @@ -28,12 +32,12 @@ class {{ k.name }}({{ parent }}): *, {% endif %} {% for kwarg in k.kwargs %} - {{ kwarg.name }}: {{ kwarg.type }}{% if not kwarg.required %} = NOT_SET{% endif %}, + {{ kwarg.name }}: {{ kwarg.type }} = NOT_SET, {% endfor %} **kwargs: Any ): {% if k.name == "FunctionScore" %} - if functions is None: + if functions == NOT_SET: functions = [] for name in ScoreFunction._classes: if name in kwargs: @@ -45,9 +49,18 @@ class {{ k.name }}({{ parent }}): if fields != NOT_SET: for field, value in _fields.items(): kwargs[str(field)] = value + {% elif k.has_type_alias %} + {% for kwarg in k.kwargs %} + {% if loop.index == 1 %} + if {{ kwarg.name }} != NOT_SET: + {% else %} + elif {{ kwarg.name }} != NOT_SET: + {% endif %} + kwargs = {{ kwarg.name }} + {% endfor %} {% endif %} super().__init__( - {% if not k.has_field and not k.has_fields %} + {% if not k.has_field and not k.has_fields and not k.has_type_alias %} {% for kwarg in k.kwargs %} {{ kwarg.name }}={{ kwarg.name }}, {% endfor %} diff --git a/utils/templates/interfaces.py.tpl b/utils/templates/interfaces.py.tpl index c68a594d..b0c3364f 100644 --- a/utils/templates/interfaces.py.tpl +++ b/utils/templates/interfaces.py.tpl @@ -1,16 +1,42 @@ -from typing import Any, List, Literal, Mapping, TypedDict, Union -from elasticsearch_dsl.search_base import InstrumentedField +from typing import Any, Dict, List, Literal, Mapping, Union +from elasticsearch_dsl.document_base import InstrumentedField from elasticsearch_dsl import analysis, function, interfaces as i, Query +from elasticsearch_dsl.utils import AttrDict, NotSet, NOT_SET PipeSeparatedFlags = str {% for k in classes %} -class {{ k.name }}({% if k.parent %}{{ k.parent }}{% else %}TypedDict{% endif %}): +class {{ k.name }}({% if k.parent %}{{ k.parent }}{% else %}AttrDict[Any]{% endif %}): {% if k.properties %} + """ {% for p in k.properties %} - {{ p.name }}: {{ p.type }} + {% for line in p.doc %} + {{ line }} {% endfor %} + {% endfor %} + """ + def __init__( + self, + *, + {% for p in k.properties %} + {{ p.name }}: {{ p.type }}{% if not p.required %} = NOT_SET{% endif %}, + {% endfor %} + **kwargs: Any + ): + {% for p in k.properties %} + if {{ p.name }} != NOT_SET: + {% if "InstrumentedField" in p.type %} + kwargs["{{ p.name }}"] = str({{ p.name }}) + {% else %} + kwargs["{{ p.name }}"] = {{ p.name }} + {% endif %} + {% endfor %} + {% if k.parent %} + super().__init__(**kwargs) + {% else %} + super().__init__(kwargs) + {% endif %} {% else %} pass {% endif %} diff --git a/utils/templates/query.py.tpl b/utils/templates/query.py.tpl index 5453db08..92557416 100644 --- a/utils/templates/query.py.tpl +++ b/utils/templates/query.py.tpl @@ -23,6 +23,7 @@ from typing import ( Any, Callable, ClassVar, + Dict, List, Literal, Mapping,