valkey-glide 1.3.5__pp39-pypy39_pp73-macosx_10_7_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of valkey-glide might be problematic. Click here for more details.

Files changed (37) hide show
  1. glide/__init__.py +330 -0
  2. glide/async_commands/__init__.py +5 -0
  3. glide/async_commands/bitmap.py +311 -0
  4. glide/async_commands/cluster_commands.py +1294 -0
  5. glide/async_commands/command_args.py +102 -0
  6. glide/async_commands/core.py +7040 -0
  7. glide/async_commands/server_modules/ft.py +395 -0
  8. glide/async_commands/server_modules/ft_options/ft_aggregate_options.py +293 -0
  9. glide/async_commands/server_modules/ft_options/ft_constants.py +84 -0
  10. glide/async_commands/server_modules/ft_options/ft_create_options.py +409 -0
  11. glide/async_commands/server_modules/ft_options/ft_profile_options.py +108 -0
  12. glide/async_commands/server_modules/ft_options/ft_search_options.py +131 -0
  13. glide/async_commands/server_modules/glide_json.py +1255 -0
  14. glide/async_commands/server_modules/json_batch.py +790 -0
  15. glide/async_commands/sorted_set.py +402 -0
  16. glide/async_commands/standalone_commands.py +935 -0
  17. glide/async_commands/stream.py +442 -0
  18. glide/async_commands/transaction.py +5175 -0
  19. glide/config.py +590 -0
  20. glide/constants.py +120 -0
  21. glide/exceptions.py +62 -0
  22. glide/glide.pyi +36 -0
  23. glide/glide.pypy39-pp73-darwin.so +0 -0
  24. glide/glide_client.py +604 -0
  25. glide/logger.py +85 -0
  26. glide/protobuf/command_request_pb2.py +54 -0
  27. glide/protobuf/command_request_pb2.pyi +1164 -0
  28. glide/protobuf/connection_request_pb2.py +52 -0
  29. glide/protobuf/connection_request_pb2.pyi +292 -0
  30. glide/protobuf/response_pb2.py +32 -0
  31. glide/protobuf/response_pb2.pyi +101 -0
  32. glide/protobuf_codec.py +109 -0
  33. glide/py.typed +0 -0
  34. glide/routes.py +114 -0
  35. valkey_glide-1.3.5.dist-info/METADATA +125 -0
  36. valkey_glide-1.3.5.dist-info/RECORD +37 -0
  37. valkey_glide-1.3.5.dist-info/WHEEL +4 -0
@@ -0,0 +1,395 @@
1
+ # Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
2
+ """
3
+ module for `vector search` commands.
4
+ """
5
+
6
+ from typing import List, Mapping, Optional, cast
7
+
8
+ from glide.async_commands.server_modules.ft_options.ft_aggregate_options import (
9
+ FtAggregateOptions,
10
+ )
11
+ from glide.async_commands.server_modules.ft_options.ft_constants import (
12
+ CommandNames,
13
+ FtCreateKeywords,
14
+ )
15
+ from glide.async_commands.server_modules.ft_options.ft_create_options import (
16
+ Field,
17
+ FtCreateOptions,
18
+ )
19
+ from glide.async_commands.server_modules.ft_options.ft_profile_options import (
20
+ FtProfileOptions,
21
+ )
22
+ from glide.async_commands.server_modules.ft_options.ft_search_options import (
23
+ FtSearchOptions,
24
+ )
25
+ from glide.constants import (
26
+ TOK,
27
+ FtAggregateResponse,
28
+ FtInfoResponse,
29
+ FtProfileResponse,
30
+ FtSearchResponse,
31
+ TEncodable,
32
+ )
33
+ from glide.glide_client import TGlideClient
34
+
35
+
36
+ async def create(
37
+ client: TGlideClient,
38
+ index_name: TEncodable,
39
+ schema: List[Field],
40
+ options: Optional[FtCreateOptions] = None,
41
+ ) -> TOK:
42
+ """
43
+ Creates an index and initiates a backfill of that index.
44
+
45
+ Args:
46
+ client (TGlideClient): The client to execute the command.
47
+ index_name (TEncodable): The index name.
48
+ schema (List[Field]): Fields to populate into the index. Equivalent to `SCHEMA` block in the module API.
49
+ options (Optional[FtCreateOptions]): Optional arguments for the FT.CREATE command.
50
+
51
+ Returns:
52
+ TOK: A simple "OK" response.
53
+
54
+ Examples:
55
+ >>> from glide import ft
56
+ >>> schema: List[Field] = [TextField("title")]
57
+ >>> prefixes: List[str] = ["blog:post:"]
58
+ >>> await ft.create(glide_client, "my_idx1", schema, FtCreateOptions(DataType.HASH, prefixes))
59
+ 'OK' # Indicates successful creation of index named 'idx'
60
+ """
61
+ args: List[TEncodable] = [CommandNames.FT_CREATE, index_name]
62
+ if options:
63
+ args.extend(options.to_args())
64
+ if schema:
65
+ args.append(FtCreateKeywords.SCHEMA)
66
+ for field in schema:
67
+ args.extend(field.to_args())
68
+ return cast(TOK, await client.custom_command(args))
69
+
70
+
71
+ async def dropindex(client: TGlideClient, index_name: TEncodable) -> TOK:
72
+ """
73
+ Drops an index. The index definition and associated content are deleted. Keys are unaffected.
74
+
75
+ Args:
76
+ client (TGlideClient): The client to execute the command.
77
+ index_name (TEncodable): The index name for the index to be dropped.
78
+
79
+ Returns:
80
+ TOK: A simple "OK" response.
81
+
82
+ Examples:
83
+ For the following example to work, an index named 'idx' must be already created. If not created, you will get an error.
84
+ >>> from glide import ft
85
+ >>> index_name = "idx"
86
+ >>> await ft.dropindex(glide_client, index_name)
87
+ 'OK' # Indicates successful deletion/dropping of index named 'idx'
88
+ """
89
+ args: List[TEncodable] = [CommandNames.FT_DROPINDEX, index_name]
90
+ return cast(TOK, await client.custom_command(args))
91
+
92
+
93
+ async def list(client: TGlideClient) -> List[TEncodable]:
94
+ """
95
+ Lists all indexes.
96
+
97
+ Args:
98
+ client (TGlideClient): The client to execute the command.
99
+
100
+ Returns:
101
+ List[TEncodable]: An array of index names.
102
+
103
+ Examples:
104
+ >>> from glide import ft
105
+ >>> await ft.list(glide_client)
106
+ [b"index1", b"index2"]
107
+ """
108
+ return cast(List[TEncodable], await client.custom_command([CommandNames.FT_LIST]))
109
+
110
+
111
+ async def search(
112
+ client: TGlideClient,
113
+ index_name: TEncodable,
114
+ query: TEncodable,
115
+ options: Optional[FtSearchOptions],
116
+ ) -> FtSearchResponse:
117
+ """
118
+ Uses the provided query expression to locate keys within an index. Once located, the count and/or the content of indexed fields within those keys can be returned.
119
+
120
+ Args:
121
+ client (TGlideClient): The client to execute the command.
122
+ index_name (TEncodable): The index name to search into.
123
+ query (TEncodable): The text query to search.
124
+ options (Optional[FtSearchOptions]): The search options.
125
+
126
+ Returns:
127
+ FtSearchResponse: A two element array, where first element is count of documents in result set, and the second element, which has the format Mapping[TEncodable, Mapping[TEncodable, TEncodable]] is a mapping between document names and map of their attributes.
128
+ If count(option in `FtSearchOptions`) is set to true or limit(option in `FtSearchOptions`) is set to FtSearchLimit(0, 0), the command returns array with only one element - the count of the documents.
129
+
130
+ Examples:
131
+ For the following example to work the following must already exist:
132
+ - An index named "idx", with fields having identifiers as "a" and "b" and prefix as "{json:}"
133
+ - A key named {json:}1 with value {"a":1, "b":2}
134
+
135
+ >>> from glide import ft
136
+ >>> await ft.search(glide_client, "idx", "*", options=FtSeachOptions(return_fields=[ReturnField(field_identifier="first"), ReturnField(field_identifier="second")]))
137
+ [1, { b'json:1': { b'first': b'42', b'second': b'33' } }] # The first element, 1 is the number of keys returned in the search result. The second element is a map of data queried per key.
138
+ """
139
+ args: List[TEncodable] = [CommandNames.FT_SEARCH, index_name, query]
140
+ if options:
141
+ args.extend(options.to_args())
142
+ return cast(FtSearchResponse, await client.custom_command(args))
143
+
144
+
145
+ async def aliasadd(
146
+ client: TGlideClient, alias: TEncodable, index_name: TEncodable
147
+ ) -> TOK:
148
+ """
149
+ Adds an alias for an index. The new alias name can be used anywhere that an index name is required.
150
+
151
+ Args:
152
+ client (TGlideClient): The client to execute the command.
153
+ alias (TEncodable): The alias to be added to an index.
154
+ index_name (TEncodable): The index name for which the alias has to be added.
155
+
156
+ Returns:
157
+ TOK: A simple "OK" response.
158
+
159
+ Examples:
160
+ >>> from glide import ft
161
+ >>> await ft.aliasadd(glide_client, "myalias", "myindex")
162
+ 'OK' # Indicates the successful addition of the alias named "myalias" for the index.
163
+ """
164
+ args: List[TEncodable] = [CommandNames.FT_ALIASADD, alias, index_name]
165
+ return cast(TOK, await client.custom_command(args))
166
+
167
+
168
+ async def aliasdel(client: TGlideClient, alias: TEncodable) -> TOK:
169
+ """
170
+ Deletes an existing alias for an index.
171
+
172
+ Args:
173
+ client (TGlideClient): The client to execute the command.
174
+ alias (TEncodable): The existing alias to be deleted for an index.
175
+
176
+ Returns:
177
+ TOK: A simple "OK" response.
178
+
179
+ Examples:
180
+ >>> from glide import ft
181
+ >>> await ft.aliasdel(glide_client, "myalias")
182
+ 'OK' # Indicates the successful deletion of the alias named "myalias"
183
+ """
184
+ args: List[TEncodable] = [CommandNames.FT_ALIASDEL, alias]
185
+ return cast(TOK, await client.custom_command(args))
186
+
187
+
188
+ async def aliasupdate(
189
+ client: TGlideClient, alias: TEncodable, index_name: TEncodable
190
+ ) -> TOK:
191
+ """
192
+ Updates an existing alias to point to a different physical index. This command only affects future references to the alias.
193
+
194
+ Args:
195
+ client (TGlideClient): The client to execute the command.
196
+ alias (TEncodable): The alias name. This alias will now be pointed to a different index.
197
+ index_name (TEncodable): The index name for which an existing alias has to updated.
198
+
199
+ Returns:
200
+ TOK: A simple "OK" response.
201
+
202
+ Examples:
203
+ >>> from glide import ft
204
+ >>> await ft.aliasupdate(glide_client, "myalias", "myindex")
205
+ 'OK' # Indicates the successful update of the alias to point to the index named "myindex"
206
+ """
207
+ args: List[TEncodable] = [CommandNames.FT_ALIASUPDATE, alias, index_name]
208
+ return cast(TOK, await client.custom_command(args))
209
+
210
+
211
+ async def info(client: TGlideClient, index_name: TEncodable) -> FtInfoResponse:
212
+ """
213
+ Returns information about a given index.
214
+
215
+ Args:
216
+ client (TGlideClient): The client to execute the command.
217
+ index_name (TEncodable): The index name for which the information has to be returned.
218
+
219
+ Returns:
220
+ FtInfoResponse: Nested maps with info about the index. See example for more details.
221
+
222
+ Examples:
223
+ An index with name 'myIndex', 1 text field and 1 vector field is already created for gettting the output of this example.
224
+ >>> from glide import ft
225
+ >>> await ft.info(glide_client, "myIndex")
226
+ [
227
+ b'index_name',
228
+ b'myIndex',
229
+ b'creation_timestamp', 1729531116945240,
230
+ b'key_type', b'JSON',
231
+ b'key_prefixes', [b'key-prefix'],
232
+ b'fields', [
233
+ [
234
+ b'identifier', b'$.vec',
235
+ b'field_name', b'VEC',
236
+ b'type', b'VECTOR',
237
+ b'option', b'',
238
+ b'vector_params', [
239
+ b'algorithm', b'HNSW', b'data_type', b'FLOAT32', b'dimension', 2, b'distance_metric', b'L2', b'initial_capacity', 1000, b'current_capacity', 1000, b'maximum_edges', 16, b'ef_construction', 200, b'ef_runtime', 10, b'epsilon', b'0.01'
240
+ ]
241
+ ],
242
+ [
243
+ b'identifier', b'$.text-field',
244
+ b'field_name', b'text-field',
245
+ b'type', b'TEXT',
246
+ b'option', b''
247
+ ]
248
+ ],
249
+ b'space_usage', 653351,
250
+ b'fulltext_space_usage', 0,
251
+ b'vector_space_usage', 653351,
252
+ b'num_docs', 0,
253
+ b'num_indexed_vectors', 0,
254
+ b'current_lag', 0,
255
+ b'index_status', b'AVAILABLE',
256
+ b'index_degradation_percentage', 0
257
+ ]
258
+ """
259
+ args: List[TEncodable] = [CommandNames.FT_INFO, index_name]
260
+ return cast(FtInfoResponse, await client.custom_command(args))
261
+
262
+
263
+ async def explain(
264
+ client: TGlideClient, index_name: TEncodable, query: TEncodable
265
+ ) -> TEncodable:
266
+ """
267
+ Parse a query and return information about how that query was parsed.
268
+
269
+ Args:
270
+ client (TGlideClient): The client to execute the command.
271
+ index_name (TEncodable): The index name for which the query is written.
272
+ query (TEncodable): The search query, same as the query passed as an argument to FT.SEARCH.
273
+
274
+ Returns:
275
+ TEncodable: A string containing the parsed results representing the execution plan.
276
+
277
+ Examples:
278
+ >>> from glide import ft
279
+ >>> await ft.explain(glide_client, indexName="myIndex", query="@price:[0 10]")
280
+ b'Field {\n price\n 0\n 10\n}\n' # Parsed results.
281
+ """
282
+ args: List[TEncodable] = [CommandNames.FT_EXPLAIN, index_name, query]
283
+ return cast(TEncodable, await client.custom_command(args))
284
+
285
+
286
+ async def explaincli(
287
+ client: TGlideClient, index_name: TEncodable, query: TEncodable
288
+ ) -> List[TEncodable]:
289
+ """
290
+ Same as the FT.EXPLAIN command except that the results are displayed in a different format. More useful with cli.
291
+
292
+ Args:
293
+ client (TGlideClient): The client to execute the command.
294
+ index_name (TEncodable): The index name for which the query is written.
295
+ query (TEncodable): The search query, same as the query passed as an argument to FT.SEARCH.
296
+
297
+ Returns:
298
+ List[TEncodable]: An array containing the execution plan.
299
+
300
+ Examples:
301
+ >>> from glide import ft
302
+ >>> await ft.explaincli(glide_client, indexName="myIndex", query="@price:[0 10]")
303
+ [b'Field {', b' price', b' 0', b' 10', b'}', b''] # Parsed results.
304
+ """
305
+ args: List[TEncodable] = [CommandNames.FT_EXPLAINCLI, index_name, query]
306
+ return cast(List[TEncodable], await client.custom_command(args))
307
+
308
+
309
+ async def aggregate(
310
+ client: TGlideClient,
311
+ index_name: TEncodable,
312
+ query: TEncodable,
313
+ options: Optional[FtAggregateOptions],
314
+ ) -> FtAggregateResponse:
315
+ """
316
+ A superset of the FT.SEARCH command, it allows substantial additional processing of the keys selected by the query expression.
317
+
318
+ Args:
319
+ client (TGlideClient): The client to execute the command.
320
+ index_name (TEncodable): The index name for which the query is written.
321
+ query (TEncodable): The search query, same as the query passed as an argument to FT.SEARCH.
322
+ options (Optional[FtAggregateOptions]): The optional arguments for the command.
323
+
324
+ Returns:
325
+ FtAggregateResponse: An array containing a mapping of field name and associated value as returned after the last stage of the command.
326
+
327
+ Examples:
328
+ >>> from glide import ft
329
+ >>> await ft.aggregate(glide_client, "myIndex", "*", FtAggregateOptions(loadFields=["__key"], clauses=[GroupBy(["@condition"], [Reducer("COUNT", [], "bicycles")])]))
330
+ [{b'condition': b'refurbished', b'bicycles': b'1'}, {b'condition': b'new', b'bicycles': b'5'}, {b'condition': b'used', b'bicycles': b'4'}]
331
+ """
332
+ args: List[TEncodable] = [CommandNames.FT_AGGREGATE, index_name, query]
333
+ if options:
334
+ args.extend(options.to_args())
335
+ return cast(FtAggregateResponse, await client.custom_command(args))
336
+
337
+
338
+ async def profile(
339
+ client: TGlideClient, index_name: TEncodable, options: FtProfileOptions
340
+ ) -> FtProfileResponse:
341
+ """
342
+ Runs a search or aggregation query and collects performance profiling information.
343
+
344
+ Args:
345
+ client (TGlideClient): The client to execute the command.
346
+ index_name (TEncodable): The index name
347
+ options (FtProfileOptions): Options for the command.
348
+
349
+ Returns:
350
+ FtProfileResponse: A two-element array. The first element contains results of query being profiled, the second element stores profiling information.
351
+
352
+ Examples:
353
+ >>> ftSearchOptions = FtSeachOptions(return_fields=[ReturnField(field_identifier="a", alias="a_new"), ReturnField(field_identifier="b", alias="b_new")])
354
+ >>> await ft.profile(glide_client, "myIndex", FtProfileOptions.from_query_options(query="*", queryOptions=ftSearchOptions))
355
+ [
356
+ [
357
+ 2,
358
+ {
359
+ b'key1': {
360
+ b'a': b'11111',
361
+ b'b': b'2'
362
+ },
363
+ b'key2': {
364
+ b'a': b'22222',
365
+ b'b': b'2'
366
+ }
367
+ }
368
+ ],
369
+ {
370
+ b'all.count': 2,
371
+ b'sync.time': 1,
372
+ b'query.time': 7,
373
+ b'result.count': 2,
374
+ b'result.time': 0
375
+ }
376
+ ]
377
+ """
378
+ args: List[TEncodable] = [CommandNames.FT_PROFILE, index_name] + options.to_args()
379
+ return cast(FtProfileResponse, await client.custom_command(args))
380
+
381
+
382
+ async def aliaslist(client: TGlideClient) -> Mapping[TEncodable, TEncodable]:
383
+ """
384
+ List the index aliases.
385
+ Args:
386
+ client (TGlideClient): The client to execute the command.
387
+ Returns:
388
+ Mapping[TEncodable, TEncodable]: A map of index aliases for indices being aliased.
389
+ Examples:
390
+ >>> from glide import ft
391
+ >>> await ft._aliaslist(glide_client)
392
+ {b'alias': b'index1', b'alias-bytes': b'index2'}
393
+ """
394
+ args: List[TEncodable] = [CommandNames.FT_ALIASLIST]
395
+ return cast(Mapping, await client.custom_command(args))
@@ -0,0 +1,293 @@
1
+ # Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
2
+ from abc import ABC, abstractmethod
3
+ from enum import Enum
4
+ from typing import List, Mapping, Optional
5
+
6
+ from glide.async_commands.command_args import OrderBy
7
+ from glide.async_commands.server_modules.ft_options.ft_constants import (
8
+ FtAggregateKeywords,
9
+ )
10
+ from glide.constants import TEncodable
11
+
12
+
13
+ class FtAggregateClause(ABC):
14
+ """
15
+ Abstract base class for the FT.AGGREGATE command clauses.
16
+ """
17
+
18
+ @abstractmethod
19
+ def to_args(self) -> List[TEncodable]:
20
+ """
21
+ Get the arguments for the clause of the FT.AGGREGATE command.
22
+
23
+ Returns:
24
+ List[TEncodable]: A list of arguments for the clause of the FT.AGGREGATE command.
25
+ """
26
+ args: List[TEncodable] = []
27
+ return args
28
+
29
+
30
+ class FtAggregateLimit(FtAggregateClause):
31
+ """
32
+ A clause for limiting the number of retained records.
33
+ """
34
+
35
+ def __init__(self, offset: int, count: int):
36
+ """
37
+ Initialize a new FtAggregateLimit instance.
38
+
39
+ Args:
40
+ offset (int): Starting point from which the records have to be retained.
41
+ count (int): The total number of records to be retained.
42
+ """
43
+ self.offset = offset
44
+ self.count = count
45
+
46
+ def to_args(self) -> List[TEncodable]:
47
+ """
48
+ Get the arguments for the Limit clause.
49
+
50
+ Returns:
51
+ List[TEncodable]: A list of Limit clause arguments.
52
+ """
53
+ return [FtAggregateKeywords.LIMIT, str(self.offset), str(self.count)]
54
+
55
+
56
+ class FtAggregateFilter(FtAggregateClause):
57
+ """
58
+ A clause for filtering the results using predicate expression relating to values in each result. It is applied post query and relate to the current state of the pipeline.
59
+ """
60
+
61
+ def __init__(self, expression: TEncodable):
62
+ """
63
+ Initialize a new FtAggregateFilter instance.
64
+
65
+ Args:
66
+ expression (TEncodable): The expression to filter the results.
67
+ """
68
+ self.expression = expression
69
+
70
+ def to_args(self) -> List[TEncodable]:
71
+ """
72
+ Get the arguments for the Filter clause.
73
+
74
+ Returns:
75
+ List[TEncodable]: A list arguments for the filter clause.
76
+ """
77
+ return [FtAggregateKeywords.FILTER, self.expression]
78
+
79
+
80
+ class FtAggregateReducer:
81
+ """
82
+ A clause for reducing the matching results in each group using a reduction function. The matching results are reduced into a single record.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ function: TEncodable,
88
+ args: List[TEncodable],
89
+ name: Optional[TEncodable] = None,
90
+ ):
91
+ """
92
+ Initialize a new FtAggregateReducer instance.
93
+
94
+ Args:
95
+ function (TEncodable): The reduction function names for the respective group.
96
+ args (List[TEncodable]): The list of arguments for the reducer.
97
+ name (Optional[TEncodable]): User defined property name for the reducer.
98
+ """
99
+ self.function = function
100
+ self.args = args
101
+ self.name = name
102
+
103
+ def to_args(self) -> List[TEncodable]:
104
+ """
105
+ Get the arguments for the Reducer.
106
+
107
+ Returns:
108
+ List[TEncodable]: A list of arguments for the reducer.
109
+ """
110
+ args: List[TEncodable] = [
111
+ FtAggregateKeywords.REDUCE,
112
+ self.function,
113
+ str(len(self.args)),
114
+ ] + self.args
115
+ if self.name:
116
+ args.extend([FtAggregateKeywords.AS, self.name])
117
+ return args
118
+
119
+
120
+ class FtAggregateGroupBy(FtAggregateClause):
121
+ """
122
+ A clause for grouping the results in the pipeline based on one or more properties.
123
+ """
124
+
125
+ def __init__(
126
+ self, properties: List[TEncodable], reducers: List[FtAggregateReducer]
127
+ ):
128
+ """
129
+ Initialize a new FtAggregateGroupBy instance.
130
+
131
+ Args:
132
+ properties (List[TEncodable]): The list of properties to be used for grouping the results in the pipeline.
133
+ reducers (List[Reducer]): The list of functions that handles the group entries by performing multiple aggregate operations.
134
+ """
135
+ self.properties = properties
136
+ self.reducers = reducers
137
+
138
+ def to_args(self) -> List[TEncodable]:
139
+ args = [
140
+ FtAggregateKeywords.GROUPBY,
141
+ str(len(self.properties)),
142
+ ] + self.properties
143
+ if self.reducers:
144
+ for reducer in self.reducers:
145
+ args.extend(reducer.to_args())
146
+ return args
147
+
148
+
149
+ class FtAggregateSortProperty:
150
+ """
151
+ This class represents the a single property for the SortBy clause.
152
+ """
153
+
154
+ def __init__(self, property: TEncodable, order: OrderBy):
155
+ """
156
+ Initialize a new FtAggregateSortProperty instance.
157
+
158
+ Args:
159
+ property (TEncodable): The sorting parameter.
160
+ order (OrderBy): The order for the sorting. This option can be added for each property.
161
+ """
162
+ self.property = property
163
+ self.order = order
164
+
165
+ def to_args(self) -> List[TEncodable]:
166
+ """
167
+ Get the arguments for the SortBy clause property.
168
+
169
+ Returns:
170
+ List[TEncodable]: A list of arguments for the SortBy clause property.
171
+ """
172
+ return [self.property, self.order.value]
173
+
174
+
175
+ class FtAggregateSortBy(FtAggregateClause):
176
+ """
177
+ A clause for sorting the pipeline up until the point of SORTBY, using a list of properties.
178
+ """
179
+
180
+ def __init__(
181
+ self, properties: List[FtAggregateSortProperty], max: Optional[int] = None
182
+ ):
183
+ """
184
+ Initialize a new FtAggregateSortBy instance.
185
+
186
+ Args:
187
+ properties (List[FtAggregateSortProperty]): A list of sorting parameters for the sort operation.
188
+ max: (Optional[int]): The MAX value for optimizing the sorting, by sorting only for the n-largest elements.
189
+ """
190
+ self.properties = properties
191
+ self.max = max
192
+
193
+ def to_args(self) -> List[TEncodable]:
194
+ """
195
+ Get the arguments for the SortBy clause.
196
+
197
+ Returns:
198
+ List[TEncodable]: A list of arguments for the SortBy clause.
199
+ """
200
+ args: List[TEncodable] = [
201
+ FtAggregateKeywords.SORTBY,
202
+ str(len(self.properties) * 2),
203
+ ]
204
+ for property in self.properties:
205
+ args.extend(property.to_args())
206
+ if self.max:
207
+ args.extend([FtAggregateKeywords.MAX, str(self.max)])
208
+ return args
209
+
210
+
211
+ class FtAggregateApply(FtAggregateClause):
212
+ """
213
+ A clause for applying a 1-to-1 transformation on one or more properties and stores the result as a new property down the pipeline or replaces any property using this transformation.
214
+ """
215
+
216
+ def __init__(self, expression: TEncodable, name: TEncodable):
217
+ """
218
+ Initialize a new FtAggregateApply instance.
219
+
220
+ Args:
221
+ expression (TEncodable): The expression to be transformed.
222
+ name (TEncodable): The new property name to store the result of apply. This name can be referenced by further APPLY/SORTBY/GROUPBY/REDUCE operations down the pipeline.
223
+ """
224
+ self.expression = expression
225
+ self.name = name
226
+
227
+ def to_args(self) -> List[TEncodable]:
228
+ """
229
+ Get the arguments for the Apply clause.
230
+
231
+ Returns:
232
+ List[TEncodable]: A list of arguments for the Apply clause.
233
+ """
234
+ return [
235
+ FtAggregateKeywords.APPLY,
236
+ self.expression,
237
+ FtAggregateKeywords.AS,
238
+ self.name,
239
+ ]
240
+
241
+
242
+ class FtAggregateOptions:
243
+ """
244
+ This class represents the optional arguments for the FT.AGGREGATE command.
245
+ """
246
+
247
+ def __init__(
248
+ self,
249
+ loadAll: Optional[bool] = False,
250
+ loadFields: Optional[List[TEncodable]] = [],
251
+ timeout: Optional[int] = None,
252
+ params: Optional[Mapping[TEncodable, TEncodable]] = {},
253
+ clauses: Optional[List[FtAggregateClause]] = [],
254
+ ):
255
+ """
256
+ Initialize a new FtAggregateOptions instance.
257
+
258
+ Args:
259
+ loadAll (Optional[bool]): An option to load all fields declared in the index.
260
+ loadFields (Optional[List[TEncodable]]): An option to load only the fields passed in this list.
261
+ timeout (Optional[int]): Overrides the timeout parameter of the module.
262
+ params (Optional[Mapping[TEncodable, TEncodable]]): The key/value pairs can be referenced from within the query expression.
263
+ clauses (Optional[List[FtAggregateClause]]): FILTER, LIMIT, GROUPBY, SORTBY and APPLY clauses, that can be repeated multiple times in any order and be freely intermixed. They are applied in the order specified, with the output of one clause feeding the input of the next clause.
264
+ """
265
+ self.loadAll = loadAll
266
+ self.loadFields = loadFields
267
+ self.timeout = timeout
268
+ self.params = params
269
+ self.clauses = clauses
270
+
271
+ def to_args(self) -> List[TEncodable]:
272
+ """
273
+ Get the optional arguments for the FT.AGGREGATE command.
274
+
275
+ Returns:
276
+ List[TEncodable]: A list of optional arguments for the FT.AGGREGATE command.
277
+ """
278
+ args: List[TEncodable] = []
279
+ if self.loadAll:
280
+ args.extend([FtAggregateKeywords.LOAD, "*"])
281
+ elif self.loadFields:
282
+ args.extend([FtAggregateKeywords.LOAD, str(len(self.loadFields))])
283
+ args.extend(self.loadFields)
284
+ if self.timeout:
285
+ args.extend([FtAggregateKeywords.TIMEOUT, str(self.timeout)])
286
+ if self.params:
287
+ args.extend([FtAggregateKeywords.PARAMS, str(len(self.params) * 2)])
288
+ for [name, value] in self.params.items():
289
+ args.extend([name, value])
290
+ if self.clauses:
291
+ for clause in self.clauses:
292
+ args.extend(clause.to_args())
293
+ return args