0
# Redis Modules
1
2
This document covers Jedis support for Redis modules including RediSearch, RedisJSON, Redis Bloom filters, and RedisTimeSeries. These modules extend Redis functionality with advanced data structures and search capabilities.
3
4
## RediSearch Module
5
6
### Core Search Commands
7
8
Full-text search and secondary indexing for Redis.
9
10
```java { .api }
11
public interface RediSearchCommands {
12
/**
13
* Create search index
14
* @param indexName Name of the index
15
* @param schema Index schema with field definitions
16
* @return Status code reply
17
*/
18
String ftCreate(String indexName, Schema schema);
19
20
/**
21
* Create search index with options
22
* @param indexName Name of the index
23
* @param indexOptions Index creation options
24
* @param schema Index schema
25
* @return Status code reply
26
*/
27
String ftCreate(String indexName, IndexOptions indexOptions, Schema schema);
28
29
/**
30
* Search the index
31
* @param indexName Name of the index
32
* @param query Search query string
33
* @return Search results
34
*/
35
SearchResult ftSearch(String indexName, String query);
36
37
/**
38
* Search with query object
39
* @param indexName Name of the index
40
* @param query Query object with parameters
41
* @return Search results
42
*/
43
SearchResult ftSearch(String indexName, Query query);
44
45
/**
46
* Search with parameters
47
* @param indexName Name of the index
48
* @param query Search query
49
* @param params Search parameters
50
* @return Search results
51
*/
52
SearchResult ftSearch(String indexName, String query, FTSearchParams params);
53
54
/**
55
* Perform aggregation query
56
* @param indexName Name of the index
57
* @param aggr Aggregation pipeline
58
* @return Aggregation results
59
*/
60
AggregationResult ftAggregate(String indexName, AggregationBuilder aggr);
61
62
/**
63
* Get index information
64
* @param indexName Name of the index
65
* @return Index configuration and statistics
66
*/
67
Map<String, Object> ftInfo(String indexName);
68
69
/**
70
* Drop an index
71
* @param indexName Name of the index
72
* @return Status code reply
73
*/
74
String ftDropIndex(String indexName);
75
76
/**
77
* Drop index and associated documents
78
* @param indexName Name of the index
79
* @return Status code reply
80
*/
81
String ftDropIndex(String indexName, boolean deleteDocuments);
82
83
/**
84
* Add document to index
85
* @param indexName Name of the index
86
* @param docId Document ID
87
* @param fields Document fields as key-value pairs
88
* @return Status code reply
89
*/
90
String ftAdd(String indexName, String docId, Map<String, Object> fields);
91
92
/**
93
* Delete document from index
94
* @param indexName Name of the index
95
* @param docId Document ID
96
* @return 1 if document deleted, 0 if not found
97
*/
98
Long ftDel(String indexName, String docId);
99
100
/**
101
* Get document by ID
102
* @param indexName Name of the index
103
* @param docId Document ID
104
* @return Document fields
105
*/
106
Map<String, Object> ftGet(String indexName, String docId);
107
108
/**
109
* Spell check query
110
* @param indexName Name of the index
111
* @param query Query to check
112
* @return Spell check suggestions
113
*/
114
Map<String, Map<String, Double>> ftSpellCheck(String indexName, String query);
115
}
116
```
117
118
### Schema Definition
119
120
Define index schema with field types and options.
121
122
```java { .api }
123
public class Schema {
124
/**
125
* Create new schema
126
*/
127
public Schema();
128
129
/**
130
* Add text field to schema
131
* @param fieldName Field name
132
* @param weight Field weight for scoring (default 1.0)
133
* @return Schema instance for chaining
134
*/
135
public Schema addTextField(String fieldName, double weight);
136
137
/**
138
* Add text field with options
139
* @param field Text field configuration
140
* @return Schema instance
141
*/
142
public Schema addField(TextField field);
143
144
/**
145
* Add numeric field
146
* @param fieldName Field name
147
* @return Schema instance
148
*/
149
public Schema addNumericField(String fieldName);
150
151
/**
152
* Add numeric field with options
153
* @param field Numeric field configuration
154
* @return Schema instance
155
*/
156
public Schema addField(NumericField field);
157
158
/**
159
* Add geo field for geospatial queries
160
* @param fieldName Field name
161
* @return Schema instance
162
*/
163
public Schema addGeoField(String fieldName);
164
165
/**
166
* Add geo field with options
167
* @param field Geo field configuration
168
* @return Schema instance
169
*/
170
public Schema addField(GeoField field);
171
172
/**
173
* Add tag field for exact matching
174
* @param fieldName Field name
175
* @return Schema instance
176
*/
177
public Schema addTagField(String fieldName);
178
179
/**
180
* Add tag field with options
181
* @param field Tag field configuration
182
* @return Schema instance
183
*/
184
public Schema addField(TagField field);
185
186
/**
187
* Add vector field for similarity search
188
* @param fieldName Field name
189
* @param vectorType Vector algorithm (FLAT or HNSW)
190
* @param attributes Vector configuration
191
* @return Schema instance
192
*/
193
public Schema addVectorField(String fieldName, VectorField.VectorAlgorithm vectorType,
194
Map<String, Object> attributes);
195
196
/**
197
* Get all fields in schema
198
* @return List of schema fields
199
*/
200
public List<SchemaField> getFields();
201
}
202
203
// Field type implementations
204
public class TextField extends SchemaField {
205
public TextField(String name);
206
public TextField weight(double weight);
207
public TextField sortable();
208
public TextField noStem();
209
public TextField noIndex();
210
public TextField phonetic(String phonetic);
211
}
212
213
public class NumericField extends SchemaField {
214
public NumericField(String name);
215
public NumericField sortable();
216
public NumericField noIndex();
217
}
218
219
public class TagField extends SchemaField {
220
public TagField(String name);
221
public TagField separator(String separator);
222
public TagField sortable();
223
public TagField noIndex();
224
}
225
226
public class GeoField extends SchemaField {
227
public GeoField(String name);
228
public GeoField noIndex();
229
}
230
231
public class VectorField extends SchemaField {
232
public enum VectorAlgorithm { FLAT, HNSW }
233
234
public VectorField(String name, VectorAlgorithm algorithm, Map<String, Object> attributes);
235
}
236
```
237
238
### Query Building
239
240
```java { .api }
241
public class Query {
242
/**
243
* Create query with query string
244
* @param queryString Search query
245
*/
246
public Query(String queryString);
247
248
/**
249
* Limit results
250
* @param offset Result offset
251
* @param count Number of results
252
* @return Query instance
253
*/
254
public Query limit(int offset, int count);
255
256
/**
257
* Sort results
258
* @param field Sort field
259
* @param ascending Sort direction
260
* @return Query instance
261
*/
262
public Query sortBy(String field, boolean ascending);
263
264
/**
265
* Return specific fields
266
* @param fields Fields to return
267
* @return Query instance
268
*/
269
public Query returnFields(String... fields);
270
271
/**
272
* Highlight matched terms
273
* @param fields Fields to highlight
274
* @return Query instance
275
*/
276
public Query highlight(String... fields);
277
278
/**
279
* Set highlight tags
280
* @param openTag Opening highlight tag
281
* @param closeTag Closing highlight tag
282
* @return Query instance
283
*/
284
public Query highlightTags(String openTag, String closeTag);
285
286
/**
287
* Add numeric filter
288
* @param field Field name
289
* @param min Minimum value
290
* @param max Maximum value
291
* @return Query instance
292
*/
293
public Query addFilter(String field, double min, double max);
294
295
/**
296
* Add geo filter
297
* @param field Geo field name
298
* @param lon Longitude center
299
* @param lat Latitude center
300
* @param radius Search radius
301
* @param unit Distance unit
302
* @return Query instance
303
*/
304
public Query addFilter(String field, double lon, double lat, double radius, GeoUnit unit);
305
306
/**
307
* Set query timeout
308
* @param timeout Timeout in milliseconds
309
* @return Query instance
310
*/
311
public Query timeout(long timeout);
312
}
313
```
314
315
### Search Results
316
317
```java { .api }
318
public class SearchResult {
319
/**
320
* Get total number of results
321
* @return Total result count
322
*/
323
public long getTotalResults();
324
325
/**
326
* Get result documents
327
* @return List of documents
328
*/
329
public List<Document> getDocuments();
330
331
/**
332
* Check if results were truncated due to timeout
333
* @return true if results incomplete
334
*/
335
public boolean isTimedOut();
336
337
/**
338
* Get query execution time
339
* @return Execution time in milliseconds
340
*/
341
public double getElapsedTime();
342
}
343
344
public class Document {
345
/**
346
* Get document ID
347
* @return Document identifier
348
*/
349
public String getId();
350
351
/**
352
* Get document score
353
* @return Relevance score
354
*/
355
public double getScore();
356
357
/**
358
* Get document properties
359
* @return Map of field names to values
360
*/
361
public Map<String, Object> getProperties();
362
363
/**
364
* Get specific property value
365
* @param key Property name
366
* @return Property value
367
*/
368
public Object get(String key);
369
370
/**
371
* Get string property
372
* @param key Property name
373
* @return String value or null
374
*/
375
public String getString(String key);
376
}
377
```
378
379
#### Usage Example
380
381
```java
382
Jedis jedis = new Jedis("localhost", 6379);
383
384
// Create search index
385
Schema schema = new Schema()
386
.addTextField("title", 2.0) // Higher weight for title
387
.addTextField("content", 1.0)
388
.addNumericField("price")
389
.addTagField("category")
390
.addGeoField("location");
391
392
jedis.ftCreate("products", schema);
393
394
// Add documents
395
Map<String, Object> doc1 = new HashMap<>();
396
doc1.put("title", "iPhone 14 Pro");
397
doc1.put("content", "Latest smartphone with advanced camera");
398
doc1.put("price", 999.99);
399
doc1.put("category", "electronics,phone");
400
doc1.put("location", "-122.4194,37.7749"); // San Francisco
401
402
jedis.ftAdd("products", "product:1", doc1);
403
404
// Search with simple query
405
SearchResult results = jedis.ftSearch("products", "iPhone");
406
407
// Advanced query with filters and sorting
408
Query query = new Query("smartphone")
409
.addFilter("price", 500, 1500) // Price range
410
.sortBy("price", true) // Sort by price ascending
411
.limit(0, 10) // First 10 results
412
.returnFields("title", "price") // Return specific fields
413
.highlight("title", "content"); // Highlight matches
414
415
SearchResult advancedResults = jedis.ftSearch("products", query);
416
417
// Process results
418
for (Document doc : advancedResults.getDocuments()) {
419
System.out.println("ID: " + doc.getId());
420
System.out.println("Score: " + doc.getScore());
421
System.out.println("Title: " + doc.getString("title"));
422
System.out.println("Price: " + doc.get("price"));
423
}
424
425
jedis.close();
426
```
427
428
### Aggregation Queries
429
430
```java { .api }
431
public class AggregationBuilder {
432
/**
433
* Create aggregation on index
434
* @param query Base query for aggregation
435
*/
436
public AggregationBuilder(String query);
437
438
/**
439
* Group by field
440
* @param fields Fields to group by
441
* @return Group operation
442
*/
443
public Group groupBy(String... fields);
444
445
/**
446
* Apply function to create computed field
447
* @param expression Mathematical expression
448
* @param alias Field alias
449
* @return Aggregation builder
450
*/
451
public AggregationBuilder apply(String expression, String alias);
452
453
/**
454
* Sort results
455
* @param max Maximum number of results
456
* @param sortFields Fields to sort by
457
* @return Aggregation builder
458
*/
459
public AggregationBuilder sortBy(int max, SortedField... sortFields);
460
461
/**
462
* Limit results
463
* @param offset Result offset
464
* @param count Result count
465
* @return Aggregation builder
466
*/
467
public AggregationBuilder limit(int offset, int count);
468
469
/**
470
* Load additional fields
471
* @param fields Fields to load
472
* @return Aggregation builder
473
*/
474
public AggregationBuilder load(String... fields);
475
}
476
477
public class Group {
478
/**
479
* Add reducer function
480
* @param reducer Aggregation function
481
* @return Group instance
482
*/
483
public Group reduce(Reducer reducer);
484
}
485
486
public class Reducers {
487
/**
488
* Count reducer
489
* @return Count reducer
490
*/
491
public static Reducer count();
492
493
/**
494
* Sum reducer
495
* @param field Field to sum
496
* @return Sum reducer
497
*/
498
public static Reducer sum(String field);
499
500
/**
501
* Average reducer
502
* @param field Field to average
503
* @return Average reducer
504
*/
505
public static Reducer avg(String field);
506
507
/**
508
* Minimum value reducer
509
* @param field Field to find minimum
510
* @return Min reducer
511
*/
512
public static Reducer min(String field);
513
514
/**
515
* Maximum value reducer
516
* @param field Field to find maximum
517
* @return Max reducer
518
*/
519
public static Reducer max(String field);
520
521
/**
522
* Standard deviation reducer
523
* @param field Field for standard deviation
524
* @return StdDev reducer
525
*/
526
public static Reducer stddev(String field);
527
528
/**
529
* Collect distinct values
530
* @param field Field to collect
531
* @return ToList reducer
532
*/
533
public static Reducer toList(String field);
534
}
535
```
536
537
#### Aggregation Example
538
539
```java
540
// Aggregate sales data by category
541
AggregationBuilder aggr = new AggregationBuilder("*")
542
.groupBy("@category")
543
.reduce(Reducers.count().as("count"))
544
.reduce(Reducers.sum("@price").as("total_sales"))
545
.reduce(Reducers.avg("@price").as("avg_price"))
546
.sortBy(10, SortedField.desc("@total_sales"));
547
548
AggregationResult result = jedis.ftAggregate("products", aggr);
549
550
for (Row row : result.getRows()) {
551
System.out.println("Category: " + row.getString("category"));
552
System.out.println("Count: " + row.getLong("count"));
553
System.out.println("Total Sales: " + row.getDouble("total_sales"));
554
System.out.println("Average Price: " + row.getDouble("avg_price"));
555
}
556
```
557
558
## RedisJSON Module
559
560
### JSON Commands
561
562
Store, retrieve, and manipulate JSON documents in Redis.
563
564
```java { .api }
565
public interface RedisJsonCommands {
566
/**
567
* Set JSON document or path
568
* @param key Redis key
569
* @param path JSON path (use Path.ROOT_PATH for entire document)
570
* @param object Object to serialize to JSON
571
* @return Status code reply
572
*/
573
String jsonSet(String key, Path path, Object object);
574
575
/**
576
* Set JSON with parameters
577
* @param key Redis key
578
* @param path JSON path
579
* @param object Object to store
580
* @param params Set parameters (NX, XX)
581
* @return Status code reply
582
*/
583
String jsonSet(String key, Path path, Object object, JsonSetParams params);
584
585
/**
586
* Get JSON document or path
587
* @param key Redis key
588
* @param clazz Class to deserialize to
589
* @return Deserialized object
590
*/
591
<T> T jsonGet(String key, Class<T> clazz);
592
593
/**
594
* Get JSON at specific path
595
* @param key Redis key
596
* @param clazz Class to deserialize to
597
* @param path JSON path
598
* @return Deserialized object
599
*/
600
<T> T jsonGet(String key, Class<T> clazz, Path path);
601
602
/**
603
* Get multiple paths
604
* @param key Redis key
605
* @param clazz Class to deserialize to
606
* @param paths JSON paths to retrieve
607
* @return Deserialized objects
608
*/
609
<T> T jsonGet(String key, Class<T> clazz, Path... paths);
610
611
/**
612
* Get JSON from multiple keys
613
* @param clazz Class to deserialize to
614
* @param path JSON path
615
* @param keys Redis keys
616
* @return List of deserialized objects
617
*/
618
<T> List<T> jsonMGet(Class<T> clazz, Path path, String... keys);
619
620
/**
621
* Delete JSON path
622
* @param key Redis key
623
* @param path JSON path to delete
624
* @return Number of paths deleted
625
*/
626
Long jsonDel(String key, Path path);
627
628
/**
629
* Get type of JSON path
630
* @param key Redis key
631
* @param path JSON path
632
* @return JSON type (object, array, string, number, boolean, null)
633
*/
634
String jsonType(String key, Path path);
635
636
/**
637
* Get number of keys in JSON object
638
* @param key Redis key
639
* @param path JSON path to object
640
* @return Number of keys
641
*/
642
Long jsonObjKeys(String key, Path path);
643
644
/**
645
* Get length of JSON array
646
* @param key Redis key
647
* @param path JSON path to array
648
* @return Array length
649
*/
650
Long jsonArrLen(String key, Path path);
651
652
/**
653
* Append to JSON array
654
* @param key Redis key
655
* @param path JSON path to array
656
* @param objects Objects to append
657
* @return New array length
658
*/
659
Long jsonArrAppend(String key, Path path, Object... objects);
660
661
/**
662
* Insert into JSON array
663
* @param key Redis key
664
* @param path JSON path to array
665
* @param index Insert position
666
* @param objects Objects to insert
667
* @return New array length
668
*/
669
Long jsonArrInsert(String key, Path path, int index, Object... objects);
670
671
/**
672
* Pop element from JSON array
673
* @param key Redis key
674
* @param clazz Class to deserialize to
675
* @param path JSON path to array
676
* @param index Index to pop (-1 for last element)
677
* @return Popped element
678
*/
679
<T> T jsonArrPop(String key, Class<T> clazz, Path path, int index);
680
681
/**
682
* Increment numeric value
683
* @param key Redis key
684
* @param path JSON path to number
685
* @param value Increment value
686
* @return New numeric value
687
*/
688
Double jsonNumIncrBy(String key, Path path, double value);
689
690
/**
691
* Get string length
692
* @param key Redis key
693
* @param path JSON path to string
694
* @return String length
695
*/
696
Long jsonStrLen(String key, Path path);
697
698
/**
699
* Append to JSON string
700
* @param key Redis key
701
* @param path JSON path to string
702
* @param string String to append
703
* @return New string length
704
*/
705
Long jsonStrAppend(String key, Path path, String string);
706
}
707
```
708
709
### JSON Path Support
710
711
```java { .api }
712
public class Path {
713
/**
714
* Root path for entire JSON document
715
*/
716
public static final Path ROOT_PATH = new Path(".");
717
718
/**
719
* Create path from string
720
* @param path Path expression
721
*/
722
public Path(String path);
723
724
/**
725
* Create root path
726
* @return Root path instance
727
*/
728
public static Path of(String path);
729
730
@Override
731
public String toString();
732
}
733
734
// Path2 for JSONPath v2 (RedisJSON 2.0+)
735
public class Path2 {
736
/**
737
* Root path for JSONPath v2
738
*/
739
public static final Path2 ROOT_PATH = new Path2("$");
740
741
/**
742
* Create JSONPath v2 expression
743
* @param path JSONPath expression
744
*/
745
public Path2(String path);
746
747
/**
748
* Create path from string
749
* @param path Path expression
750
* @return Path2 instance
751
*/
752
public static Path2 of(String path);
753
}
754
```
755
756
### JSON Parameters
757
758
```java { .api }
759
public class JsonSetParams implements IParams {
760
/**
761
* Set only if key doesn't exist
762
* @return Parameters instance
763
*/
764
public JsonSetParams nx();
765
766
/**
767
* Set only if key exists
768
* @return Parameters instance
769
*/
770
public JsonSetParams xx();
771
}
772
```
773
774
#### Usage Example
775
776
```java
777
Jedis jedis = new Jedis("localhost", 6379);
778
779
// Store JSON document
780
User user = new User("John", "john@example.com", 30);
781
jedis.jsonSet("user:1", Path.ROOT_PATH, user);
782
783
// Get entire document
784
User retrievedUser = jedis.jsonGet("user:1", User.class);
785
786
// Work with nested JSON
787
Map<String, Object> profile = new HashMap<>();
788
profile.put("name", "John Doe");
789
profile.put("age", 30);
790
profile.put("skills", Arrays.asList("Java", "Redis", "JSON"));
791
792
jedis.jsonSet("profile:1", Path.ROOT_PATH, profile);
793
794
// Get specific path
795
String name = jedis.jsonGet("profile:1", String.class, Path.of(".name"));
796
797
// Array operations
798
jedis.jsonArrAppend("profile:1", Path.of(".skills"), "Docker", "Kubernetes");
799
Long skillCount = jedis.jsonArrLen("profile:1", Path.of(".skills"));
800
801
// Increment numeric value
802
jedis.jsonNumIncrBy("profile:1", Path.of(".age"), 1);
803
804
// Complex nested document
805
String complexJson = """
806
{
807
"user": {
808
"id": 123,
809
"profile": {
810
"name": "Alice",
811
"preferences": {
812
"theme": "dark",
813
"notifications": true
814
}
815
},
816
"posts": [
817
{"title": "Hello World", "likes": 10},
818
{"title": "JSON in Redis", "likes": 25}
819
]
820
}
821
}
822
""";
823
824
jedis.jsonSet("document:1", Path.ROOT_PATH, complexJson);
825
826
// Query nested paths
827
String theme = jedis.jsonGet("document:1", String.class,
828
Path.of(".user.profile.preferences.theme"));
829
830
// Array element access
831
Integer likes = jedis.jsonGet("document:1", Integer.class,
832
Path.of(".user.posts[1].likes"));
833
834
jedis.close();
835
```
836
837
## Redis Bloom Module
838
839
### Bloom Filter Commands
840
841
Probabilistic data structures for membership testing.
842
843
```java { .api }
844
public interface BloomFilterCommands {
845
/**
846
* Reserve Bloom filter with capacity and error rate
847
* @param key Bloom filter key
848
* @param errorRate Desired false positive rate
849
* @param capacity Expected number of elements
850
* @return Status code reply
851
*/
852
String bfReserve(String key, double errorRate, long capacity);
853
854
/**
855
* Reserve Bloom filter with parameters
856
* @param key Bloom filter key
857
* @param params Reserve parameters
858
* @return Status code reply
859
*/
860
String bfReserve(String key, BFReserveParams params);
861
862
/**
863
* Add item to Bloom filter
864
* @param key Bloom filter key
865
* @param item Item to add
866
* @return true if item was added (first time), false if already existed
867
*/
868
Boolean bfAdd(String key, String item);
869
870
/**
871
* Add multiple items to Bloom filter
872
* @param key Bloom filter key
873
* @param items Items to add
874
* @return List of boolean results for each item
875
*/
876
List<Boolean> bfMAdd(String key, String... items);
877
878
/**
879
* Test if item exists in Bloom filter
880
* @param key Bloom filter key
881
* @param item Item to test
882
* @return true if item might exist, false if definitely doesn't exist
883
*/
884
Boolean bfExists(String key, String item);
885
886
/**
887
* Test multiple items
888
* @param key Bloom filter key
889
* @param items Items to test
890
* @return List of existence test results
891
*/
892
List<Boolean> bfMExists(String key, String... items);
893
894
/**
895
* Get Bloom filter information
896
* @param key Bloom filter key
897
* @return Filter statistics and configuration
898
*/
899
Map<String, Object> bfInfo(String key);
900
901
/**
902
* Insert items with parameters
903
* @param key Bloom filter key
904
* @param params Insert parameters
905
* @param items Items to insert
906
* @return List of insertion results
907
*/
908
List<Boolean> bfInsert(String key, BFInsertParams params, String... items);
909
910
/**
911
* Load Bloom filter from external data
912
* @param key Bloom filter key
913
* @param iterator External iterator position
914
* @param data Chunk data
915
* @return Status code reply
916
*/
917
String bfLoadChunk(String key, long iterator, byte[] data);
918
919
/**
920
* Scan and dump Bloom filter
921
* @param key Bloom filter key
922
* @param iterator Iterator position
923
* @return Chunk data and next iterator
924
*/
925
List<Object> bfScanDump(String key, long iterator);
926
}
927
```
928
929
### Cuckoo Filter Commands
930
931
```java { .api }
932
public interface CuckooFilterCommands {
933
/**
934
* Reserve Cuckoo filter
935
* @param key Cuckoo filter key
936
* @param capacity Expected capacity
937
* @return Status code reply
938
*/
939
String cfReserve(String key, long capacity);
940
941
/**
942
* Reserve with parameters
943
* @param key Cuckoo filter key
944
* @param params Reserve parameters
945
* @return Status code reply
946
*/
947
String cfReserve(String key, CFReserveParams params);
948
949
/**
950
* Add item to Cuckoo filter
951
* @param key Cuckoo filter key
952
* @param item Item to add
953
* @return true if added successfully
954
*/
955
Boolean cfAdd(String key, String item);
956
957
/**
958
* Add item only if it doesn't exist
959
* @param key Cuckoo filter key
960
* @param item Item to add
961
* @return true if added, false if already exists
962
*/
963
Boolean cfAddNx(String key, String item);
964
965
/**
966
* Insert multiple items
967
* @param key Cuckoo filter key
968
* @param params Insert parameters
969
* @param items Items to insert
970
* @return Insertion results
971
*/
972
List<Boolean> cfInsert(String key, CFInsertParams params, String... items);
973
974
/**
975
* Test item existence
976
* @param key Cuckoo filter key
977
* @param item Item to test
978
* @return true if item might exist
979
*/
980
Boolean cfExists(String key, String item);
981
982
/**
983
* Delete item from filter
984
* @param key Cuckoo filter key
985
* @param item Item to delete
986
* @return true if item was deleted
987
*/
988
Boolean cfDel(String key, String item);
989
990
/**
991
* Count item occurrences
992
* @param key Cuckoo filter key
993
* @param item Item to count
994
* @return Number of occurrences
995
*/
996
Long cfCount(String key, String item);
997
}
998
```
999
1000
### Count-Min Sketch Commands
1001
1002
```java { .api }
1003
public interface CountMinSketchCommands {
1004
/**
1005
* Initialize Count-Min Sketch by dimensions
1006
* @param key CMS key
1007
* @param width Sketch width
1008
* @param depth Sketch depth
1009
* @return Status code reply
1010
*/
1011
String cmsInitByDim(String key, long width, long depth);
1012
1013
/**
1014
* Initialize by probability and error
1015
* @param key CMS key
1016
* @param error Error rate
1017
* @param probability Confidence probability
1018
* @return Status code reply
1019
*/
1020
String cmsInitByProb(String key, double error, double probability);
1021
1022
/**
1023
* Increment item count
1024
* @param key CMS key
1025
* @param item Item to increment
1026
* @param increment Increment value
1027
* @return Updated count estimate
1028
*/
1029
Long cmsIncrBy(String key, String item, long increment);
1030
1031
/**
1032
* Increment multiple items
1033
* @param key CMS key
1034
* @param itemIncrements Map of items to increments
1035
* @return List of updated count estimates
1036
*/
1037
List<Long> cmsIncrBy(String key, Map<String, Long> itemIncrements);
1038
1039
/**
1040
* Query item count
1041
* @param key CMS key
1042
* @param items Items to query
1043
* @return List of count estimates
1044
*/
1045
List<Long> cmsQuery(String key, String... items);
1046
1047
/**
1048
* Get CMS information
1049
* @param key CMS key
1050
* @return CMS statistics
1051
*/
1052
Map<String, Object> cmsInfo(String key);
1053
1054
/**
1055
* Merge Count-Min Sketches
1056
* @param destKey Destination key
1057
* @param sourceKeys Source keys to merge
1058
* @param weights Merge weights
1059
* @return Status code reply
1060
*/
1061
String cmsMerge(String destKey, String[] sourceKeys, long[] weights);
1062
}
1063
```
1064
1065
#### Bloom Filter Usage Example
1066
1067
```java
1068
Jedis jedis = new Jedis("localhost", 6379);
1069
1070
// Create Bloom filter for 1 million items with 1% false positive rate
1071
jedis.bfReserve("users:visited", 0.01, 1000000);
1072
1073
// Add items
1074
jedis.bfAdd("users:visited", "user:123");
1075
jedis.bfAdd("users:visited", "user:456");
1076
jedis.bfAdd("users:visited", "user:789");
1077
1078
// Bulk add
1079
List<Boolean> addResults = jedis.bfMAdd("users:visited",
1080
"user:100", "user:200", "user:300");
1081
1082
// Test membership
1083
boolean exists = jedis.bfExists("users:visited", "user:123"); // true
1084
boolean notExists = jedis.bfExists("users:visited", "user:999"); // false (probably)
1085
1086
// Batch test
1087
List<Boolean> existResults = jedis.bfMExists("users:visited",
1088
"user:123", "user:456", "user:999");
1089
1090
// Get filter info
1091
Map<String, Object> info = jedis.bfInfo("users:visited");
1092
System.out.println("Capacity: " + info.get("Capacity"));
1093
System.out.println("Size: " + info.get("Size"));
1094
System.out.println("Filters: " + info.get("Number of filters"));
1095
1096
// Count-Min Sketch for frequency counting
1097
jedis.cmsInitByProb("page:views", 0.01, 0.99); // 1% error, 99% confidence
1098
1099
// Count page views
1100
jedis.cmsIncrBy("page:views", "/home", 1);
1101
jedis.cmsIncrBy("page:views", "/products", 5);
1102
jedis.cmsIncrBy("page:views", "/about", 2);
1103
1104
// Query counts
1105
List<Long> viewCounts = jedis.cmsQuery("page:views", "/home", "/products", "/about");
1106
System.out.println("Page view counts: " + viewCounts);
1107
1108
jedis.close();
1109
```
1110
1111
## RedisTimeSeries Module
1112
1113
### Time Series Commands
1114
1115
Store and query time series data efficiently.
1116
1117
```java { .api }
1118
public interface TimeSeriesCommands {
1119
/**
1120
* Create time series
1121
* @param key Time series key
1122
* @return Status code reply
1123
*/
1124
String tsCreate(String key);
1125
1126
/**
1127
* Create time series with parameters
1128
* @param key Time series key
1129
* @param params Creation parameters
1130
* @return Status code reply
1131
*/
1132
String tsCreate(String key, TSCreateParams params);
1133
1134
/**
1135
* Add sample to time series
1136
* @param key Time series key
1137
* @param timestamp Sample timestamp (Unix timestamp in milliseconds)
1138
* @param value Sample value
1139
* @return Timestamp of added sample
1140
*/
1141
Long tsAdd(String key, long timestamp, double value);
1142
1143
/**
1144
* Add sample with parameters
1145
* @param key Time series key
1146
* @param timestamp Sample timestamp
1147
* @param value Sample value
1148
* @param params Add parameters
1149
* @return Timestamp of added sample
1150
*/
1151
Long tsAdd(String key, long timestamp, double value, TSAddParams params);
1152
1153
/**
1154
* Add multiple samples
1155
* @param sampleKeyValueTimestamp Array of samples (key, timestamp, value)
1156
* @return List of add results
1157
*/
1158
List<Long> tsMAdd(String... sampleKeyValueTimestamp);
1159
1160
/**
1161
* Increment time series value
1162
* @param key Time series key
1163
* @param value Increment value
1164
* @return Timestamp of incremented sample
1165
*/
1166
Long tsIncrBy(String key, double value);
1167
1168
/**
1169
* Increment with timestamp
1170
* @param key Time series key
1171
* @param value Increment value
1172
* @param timestamp Specific timestamp
1173
* @return Timestamp of incremented sample
1174
*/
1175
Long tsIncrBy(String key, double value, long timestamp);
1176
1177
/**
1178
* Decrement time series value
1179
* @param key Time series key
1180
* @param value Decrement value
1181
* @return Timestamp of decremented sample
1182
*/
1183
Long tsDecrBy(String key, double value);
1184
1185
/**
1186
* Get range of samples
1187
* @param key Time series key
1188
* @param fromTimestamp Start timestamp
1189
* @param toTimestamp End timestamp
1190
* @return List of time series elements
1191
*/
1192
List<TSElement> tsRange(String key, long fromTimestamp, long toTimestamp);
1193
1194
/**
1195
* Get range with parameters
1196
* @param key Time series key
1197
* @param fromTimestamp Start timestamp
1198
* @param toTimestamp End timestamp
1199
* @param params Range parameters
1200
* @return List of time series elements
1201
*/
1202
List<TSElement> tsRange(String key, long fromTimestamp, long toTimestamp,
1203
TSRangeParams params);
1204
1205
/**
1206
* Get reverse range
1207
* @param key Time series key
1208
* @param fromTimestamp Start timestamp
1209
* @param toTimestamp End timestamp
1210
* @return List of time series elements in reverse order
1211
*/
1212
List<TSElement> tsRevRange(String key, long fromTimestamp, long toTimestamp);
1213
1214
/**
1215
* Get multiple time series ranges
1216
* @param fromTimestamp Start timestamp
1217
* @param toTimestamp End timestamp
1218
* @param filters Filter expressions
1219
* @return Map of time series keys to elements
1220
*/
1221
Map<String, List<TSElement>> tsMRange(long fromTimestamp, long toTimestamp,
1222
String... filters);
1223
1224
/**
1225
* Multi-range with parameters
1226
* @param params Multi-range parameters
1227
* @return Map of time series to elements
1228
*/
1229
Map<String, List<TSElement>> tsMRange(TSMRangeParams params);
1230
1231
/**
1232
* Get latest sample
1233
* @param key Time series key
1234
* @return Latest time series element
1235
*/
1236
TSElement tsGet(String key);
1237
1238
/**
1239
* Get latest samples from multiple series
1240
* @param filters Filter expressions
1241
* @return Map of time series keys to latest elements
1242
*/
1243
Map<String, TSElement> tsMGet(String... filters);
1244
1245
/**
1246
* Get time series information
1247
* @param key Time series key
1248
* @return Time series metadata and statistics
1249
*/
1250
TSInfo tsInfo(String key);
1251
1252
/**
1253
* Delete range of samples
1254
* @param key Time series key
1255
* @param fromTimestamp Start timestamp
1256
* @param toTimestamp End timestamp
1257
* @return Number of deleted samples
1258
*/
1259
Long tsDel(String key, long fromTimestamp, long toTimestamp);
1260
1261
/**
1262
* Create aggregation rule
1263
* @param sourceKey Source time series
1264
* @param destKey Destination time series
1265
* @param aggregationType Aggregation function
1266
* @param timeBucket Time bucket duration
1267
* @return Status code reply
1268
*/
1269
String tsCreateRule(String sourceKey, String destKey,
1270
AggregationType aggregationType, long timeBucket);
1271
1272
/**
1273
* Delete aggregation rule
1274
* @param sourceKey Source time series
1275
* @param destKey Destination time series
1276
* @return Status code reply
1277
*/
1278
String tsDeleteRule(String sourceKey, String destKey);
1279
1280
/**
1281
* Query index for time series keys
1282
* @param filters Filter expressions
1283
* @return List of matching time series keys
1284
*/
1285
List<String> tsQueryIndex(String... filters);
1286
}
1287
```
1288
1289
### Time Series Parameters
1290
1291
```java { .api }
1292
public class TSCreateParams implements IParams {
1293
/**
1294
* Set retention period in milliseconds
1295
* @param retention Retention period
1296
* @return Parameters instance
1297
*/
1298
public TSCreateParams retention(long retention);
1299
1300
/**
1301
* Set uncompressed storage
1302
* @return Parameters instance
1303
*/
1304
public TSCreateParams uncompressed();
1305
1306
/**
1307
* Add labels for indexing and filtering
1308
* @param labels Label key-value pairs
1309
* @return Parameters instance
1310
*/
1311
public TSCreateParams labels(Map<String, String> labels);
1312
1313
/**
1314
* Set duplicate policy
1315
* @param policy Duplicate handling policy
1316
* @return Parameters instance
1317
*/
1318
public TSCreateParams duplicatePolicy(DuplicatePolicy policy);
1319
1320
/**
1321
* Set chunk size
1322
* @param chunkSize Chunk size in bytes
1323
* @return Parameters instance
1324
*/
1325
public TSCreateParams chunkSize(long chunkSize);
1326
}
1327
1328
public class TSAddParams implements IParams {
1329
public TSAddParams retention(long retention);
1330
public TSAddParams uncompressed();
1331
public TSAddParams labels(Map<String, String> labels);
1332
public TSAddParams onDuplicate(DuplicatePolicy policy);
1333
public TSAddParams chunkSize(long chunkSize);
1334
}
1335
1336
public class TSRangeParams implements IParams {
1337
/**
1338
* Limit number of samples returned
1339
* @param count Maximum number of samples
1340
* @return Parameters instance
1341
*/
1342
public TSRangeParams count(long count);
1343
1344
/**
1345
* Aggregate samples
1346
* @param aggregationType Aggregation function
1347
* @param timeBucket Time bucket size
1348
* @return Parameters instance
1349
*/
1350
public TSRangeParams aggregation(AggregationType aggregationType, long timeBucket);
1351
1352
/**
1353
* Filter by labels
1354
* @param filters Label filter expressions
1355
* @return Parameters instance
1356
*/
1357
public TSRangeParams filterByLabels(String... filters);
1358
}
1359
1360
public enum AggregationType {
1361
AVG, SUM, MIN, MAX, RANGE, COUNT, STD_P, STD_S, VAR_P, VAR_S, FIRST, LAST
1362
}
1363
1364
public enum DuplicatePolicy {
1365
BLOCK, FIRST, LAST, MIN, MAX, SUM
1366
}
1367
```
1368
1369
### Time Series Data Types
1370
1371
```java { .api }
1372
public class TSElement {
1373
/**
1374
* Get sample timestamp
1375
* @return Unix timestamp in milliseconds
1376
*/
1377
public long getTimestamp();
1378
1379
/**
1380
* Get sample value
1381
* @return Numeric value
1382
*/
1383
public double getValue();
1384
1385
@Override
1386
public String toString();
1387
}
1388
1389
public class TSInfo {
1390
/**
1391
* Get total samples in time series
1392
* @return Sample count
1393
*/
1394
public long getTotalSamples();
1395
1396
/**
1397
* Get memory usage in bytes
1398
* @return Memory usage
1399
*/
1400
public long getMemoryUsage();
1401
1402
/**
1403
* Get first timestamp
1404
* @return First timestamp
1405
*/
1406
public long getFirstTimestamp();
1407
1408
/**
1409
* Get last timestamp
1410
* @return Last timestamp
1411
*/
1412
public long getLastTimestamp();
1413
1414
/**
1415
* Get retention period
1416
* @return Retention in milliseconds
1417
*/
1418
public long getRetentionTime();
1419
1420
/**
1421
* Get labels
1422
* @return Label map
1423
*/
1424
public Map<String, String> getLabels();
1425
1426
/**
1427
* Get aggregation rules
1428
* @return List of rules
1429
*/
1430
public List<Map<String, Object>> getRules();
1431
}
1432
```
1433
1434
#### Time Series Usage Example
1435
1436
```java
1437
Jedis jedis = new Jedis("localhost", 6379);
1438
1439
// Create time series for temperature sensor
1440
Map<String, String> labels = Map.of(
1441
"sensor", "temperature",
1442
"location", "server_room",
1443
"unit", "celsius"
1444
);
1445
1446
TSCreateParams createParams = TSCreateParams.createParams()
1447
.retention(86400000) // 1 day retention
1448
.labels(labels);
1449
1450
jedis.tsCreate("temperature:sensor1", createParams);
1451
1452
// Add temperature readings
1453
long now = System.currentTimeMillis();
1454
jedis.tsAdd("temperature:sensor1", now - 3600000, 22.5); // 1 hour ago
1455
jedis.tsAdd("temperature:sensor1", now - 1800000, 23.1); // 30 min ago
1456
jedis.tsAdd("temperature:sensor1", now, 24.2); // Now
1457
1458
// Create aggregated series for hourly averages
1459
jedis.tsCreate("temperature:sensor1:hourly");
1460
jedis.tsCreateRule("temperature:sensor1", "temperature:sensor1:hourly",
1461
AggregationType.AVG, 3600000); // 1 hour buckets
1462
1463
// Query recent temperature data
1464
List<TSElement> recentData = jedis.tsRange("temperature:sensor1",
1465
now - 7200000, now);
1466
1467
for (TSElement element : recentData) {
1468
System.out.printf("Timestamp: %d, Temperature: %.1f°C%n",
1469
element.getTimestamp(), element.getValue());
1470
}
1471
1472
// Get hourly aggregates
1473
TSRangeParams rangeParams = TSRangeParams.rangeParams()
1474
.aggregation(AggregationType.AVG, 3600000) // Hourly average
1475
.count(24); // Last 24 hours
1476
1477
List<TSElement> hourlyAvg = jedis.tsRange("temperature:sensor1",
1478
now - 86400000, now, rangeParams);
1479
1480
// Multi-series query with filters
1481
Map<String, List<TSElement>> multiData = jedis.tsMRange(
1482
now - 3600000, now,
1483
"sensor=temperature", "location=server_room"
1484
);
1485
1486
// Get latest readings from all temperature sensors
1487
Map<String, TSElement> latestReadings = jedis.tsMGet("sensor=temperature");
1488
1489
// Time series information
1490
TSInfo info = jedis.tsInfo("temperature:sensor1");
1491
System.out.println("Total samples: " + info.getTotalSamples());
1492
System.out.println("Memory usage: " + info.getMemoryUsage() + " bytes");
1493
System.out.println("Retention: " + info.getRetentionTime() + " ms");
1494
1495
jedis.close();
1496
```
1497
1498
Redis modules extend Redis functionality significantly, providing specialized data structures and operations for search, JSON manipulation, probabilistic data structures, and time series data. Jedis provides comprehensive support for all these modules with type-safe APIs and convenient helper methods.