Jedis is a blazingly small and sane Redis java client.
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.
Full-text search and secondary indexing for Redis.
public interface RediSearchCommands {
/**
* Create search index
* @param indexName Name of the index
* @param schema Index schema with field definitions
* @return Status code reply
*/
String ftCreate(String indexName, Schema schema);
/**
* Create search index with options
* @param indexName Name of the index
* @param indexOptions Index creation options
* @param schema Index schema
* @return Status code reply
*/
String ftCreate(String indexName, IndexOptions indexOptions, Schema schema);
/**
* Search the index
* @param indexName Name of the index
* @param query Search query string
* @return Search results
*/
SearchResult ftSearch(String indexName, String query);
/**
* Search with query object
* @param indexName Name of the index
* @param query Query object with parameters
* @return Search results
*/
SearchResult ftSearch(String indexName, Query query);
/**
* Search with parameters
* @param indexName Name of the index
* @param query Search query
* @param params Search parameters
* @return Search results
*/
SearchResult ftSearch(String indexName, String query, FTSearchParams params);
/**
* Perform aggregation query
* @param indexName Name of the index
* @param aggr Aggregation pipeline
* @return Aggregation results
*/
AggregationResult ftAggregate(String indexName, AggregationBuilder aggr);
/**
* Get index information
* @param indexName Name of the index
* @return Index configuration and statistics
*/
Map<String, Object> ftInfo(String indexName);
/**
* Drop an index
* @param indexName Name of the index
* @return Status code reply
*/
String ftDropIndex(String indexName);
/**
* Drop index and associated documents
* @param indexName Name of the index
* @return Status code reply
*/
String ftDropIndex(String indexName, boolean deleteDocuments);
/**
* Add document to index
* @param indexName Name of the index
* @param docId Document ID
* @param fields Document fields as key-value pairs
* @return Status code reply
*/
String ftAdd(String indexName, String docId, Map<String, Object> fields);
/**
* Delete document from index
* @param indexName Name of the index
* @param docId Document ID
* @return 1 if document deleted, 0 if not found
*/
Long ftDel(String indexName, String docId);
/**
* Get document by ID
* @param indexName Name of the index
* @param docId Document ID
* @return Document fields
*/
Map<String, Object> ftGet(String indexName, String docId);
/**
* Spell check query
* @param indexName Name of the index
* @param query Query to check
* @return Spell check suggestions
*/
Map<String, Map<String, Double>> ftSpellCheck(String indexName, String query);
}Define index schema with field types and options.
public class Schema {
/**
* Create new schema
*/
public Schema();
/**
* Add text field to schema
* @param fieldName Field name
* @param weight Field weight for scoring (default 1.0)
* @return Schema instance for chaining
*/
public Schema addTextField(String fieldName, double weight);
/**
* Add text field with options
* @param field Text field configuration
* @return Schema instance
*/
public Schema addField(TextField field);
/**
* Add numeric field
* @param fieldName Field name
* @return Schema instance
*/
public Schema addNumericField(String fieldName);
/**
* Add numeric field with options
* @param field Numeric field configuration
* @return Schema instance
*/
public Schema addField(NumericField field);
/**
* Add geo field for geospatial queries
* @param fieldName Field name
* @return Schema instance
*/
public Schema addGeoField(String fieldName);
/**
* Add geo field with options
* @param field Geo field configuration
* @return Schema instance
*/
public Schema addField(GeoField field);
/**
* Add tag field for exact matching
* @param fieldName Field name
* @return Schema instance
*/
public Schema addTagField(String fieldName);
/**
* Add tag field with options
* @param field Tag field configuration
* @return Schema instance
*/
public Schema addField(TagField field);
/**
* Add vector field for similarity search
* @param fieldName Field name
* @param vectorType Vector algorithm (FLAT or HNSW)
* @param attributes Vector configuration
* @return Schema instance
*/
public Schema addVectorField(String fieldName, VectorField.VectorAlgorithm vectorType,
Map<String, Object> attributes);
/**
* Get all fields in schema
* @return List of schema fields
*/
public List<SchemaField> getFields();
}
// Field type implementations
public class TextField extends SchemaField {
public TextField(String name);
public TextField weight(double weight);
public TextField sortable();
public TextField noStem();
public TextField noIndex();
public TextField phonetic(String phonetic);
}
public class NumericField extends SchemaField {
public NumericField(String name);
public NumericField sortable();
public NumericField noIndex();
}
public class TagField extends SchemaField {
public TagField(String name);
public TagField separator(String separator);
public TagField sortable();
public TagField noIndex();
}
public class GeoField extends SchemaField {
public GeoField(String name);
public GeoField noIndex();
}
public class VectorField extends SchemaField {
public enum VectorAlgorithm { FLAT, HNSW }
public VectorField(String name, VectorAlgorithm algorithm, Map<String, Object> attributes);
}public class Query {
/**
* Create query with query string
* @param queryString Search query
*/
public Query(String queryString);
/**
* Limit results
* @param offset Result offset
* @param count Number of results
* @return Query instance
*/
public Query limit(int offset, int count);
/**
* Sort results
* @param field Sort field
* @param ascending Sort direction
* @return Query instance
*/
public Query sortBy(String field, boolean ascending);
/**
* Return specific fields
* @param fields Fields to return
* @return Query instance
*/
public Query returnFields(String... fields);
/**
* Highlight matched terms
* @param fields Fields to highlight
* @return Query instance
*/
public Query highlight(String... fields);
/**
* Set highlight tags
* @param openTag Opening highlight tag
* @param closeTag Closing highlight tag
* @return Query instance
*/
public Query highlightTags(String openTag, String closeTag);
/**
* Add numeric filter
* @param field Field name
* @param min Minimum value
* @param max Maximum value
* @return Query instance
*/
public Query addFilter(String field, double min, double max);
/**
* Add geo filter
* @param field Geo field name
* @param lon Longitude center
* @param lat Latitude center
* @param radius Search radius
* @param unit Distance unit
* @return Query instance
*/
public Query addFilter(String field, double lon, double lat, double radius, GeoUnit unit);
/**
* Set query timeout
* @param timeout Timeout in milliseconds
* @return Query instance
*/
public Query timeout(long timeout);
}public class SearchResult {
/**
* Get total number of results
* @return Total result count
*/
public long getTotalResults();
/**
* Get result documents
* @return List of documents
*/
public List<Document> getDocuments();
/**
* Check if results were truncated due to timeout
* @return true if results incomplete
*/
public boolean isTimedOut();
/**
* Get query execution time
* @return Execution time in milliseconds
*/
public double getElapsedTime();
}
public class Document {
/**
* Get document ID
* @return Document identifier
*/
public String getId();
/**
* Get document score
* @return Relevance score
*/
public double getScore();
/**
* Get document properties
* @return Map of field names to values
*/
public Map<String, Object> getProperties();
/**
* Get specific property value
* @param key Property name
* @return Property value
*/
public Object get(String key);
/**
* Get string property
* @param key Property name
* @return String value or null
*/
public String getString(String key);
}Jedis jedis = new Jedis("localhost", 6379);
// Create search index
Schema schema = new Schema()
.addTextField("title", 2.0) // Higher weight for title
.addTextField("content", 1.0)
.addNumericField("price")
.addTagField("category")
.addGeoField("location");
jedis.ftCreate("products", schema);
// Add documents
Map<String, Object> doc1 = new HashMap<>();
doc1.put("title", "iPhone 14 Pro");
doc1.put("content", "Latest smartphone with advanced camera");
doc1.put("price", 999.99);
doc1.put("category", "electronics,phone");
doc1.put("location", "-122.4194,37.7749"); // San Francisco
jedis.ftAdd("products", "product:1", doc1);
// Search with simple query
SearchResult results = jedis.ftSearch("products", "iPhone");
// Advanced query with filters and sorting
Query query = new Query("smartphone")
.addFilter("price", 500, 1500) // Price range
.sortBy("price", true) // Sort by price ascending
.limit(0, 10) // First 10 results
.returnFields("title", "price") // Return specific fields
.highlight("title", "content"); // Highlight matches
SearchResult advancedResults = jedis.ftSearch("products", query);
// Process results
for (Document doc : advancedResults.getDocuments()) {
System.out.println("ID: " + doc.getId());
System.out.println("Score: " + doc.getScore());
System.out.println("Title: " + doc.getString("title"));
System.out.println("Price: " + doc.get("price"));
}
jedis.close();public class AggregationBuilder {
/**
* Create aggregation on index
* @param query Base query for aggregation
*/
public AggregationBuilder(String query);
/**
* Group by field
* @param fields Fields to group by
* @return Group operation
*/
public Group groupBy(String... fields);
/**
* Apply function to create computed field
* @param expression Mathematical expression
* @param alias Field alias
* @return Aggregation builder
*/
public AggregationBuilder apply(String expression, String alias);
/**
* Sort results
* @param max Maximum number of results
* @param sortFields Fields to sort by
* @return Aggregation builder
*/
public AggregationBuilder sortBy(int max, SortedField... sortFields);
/**
* Limit results
* @param offset Result offset
* @param count Result count
* @return Aggregation builder
*/
public AggregationBuilder limit(int offset, int count);
/**
* Load additional fields
* @param fields Fields to load
* @return Aggregation builder
*/
public AggregationBuilder load(String... fields);
}
public class Group {
/**
* Add reducer function
* @param reducer Aggregation function
* @return Group instance
*/
public Group reduce(Reducer reducer);
}
public class Reducers {
/**
* Count reducer
* @return Count reducer
*/
public static Reducer count();
/**
* Sum reducer
* @param field Field to sum
* @return Sum reducer
*/
public static Reducer sum(String field);
/**
* Average reducer
* @param field Field to average
* @return Average reducer
*/
public static Reducer avg(String field);
/**
* Minimum value reducer
* @param field Field to find minimum
* @return Min reducer
*/
public static Reducer min(String field);
/**
* Maximum value reducer
* @param field Field to find maximum
* @return Max reducer
*/
public static Reducer max(String field);
/**
* Standard deviation reducer
* @param field Field for standard deviation
* @return StdDev reducer
*/
public static Reducer stddev(String field);
/**
* Collect distinct values
* @param field Field to collect
* @return ToList reducer
*/
public static Reducer toList(String field);
}// Aggregate sales data by category
AggregationBuilder aggr = new AggregationBuilder("*")
.groupBy("@category")
.reduce(Reducers.count().as("count"))
.reduce(Reducers.sum("@price").as("total_sales"))
.reduce(Reducers.avg("@price").as("avg_price"))
.sortBy(10, SortedField.desc("@total_sales"));
AggregationResult result = jedis.ftAggregate("products", aggr);
for (Row row : result.getRows()) {
System.out.println("Category: " + row.getString("category"));
System.out.println("Count: " + row.getLong("count"));
System.out.println("Total Sales: " + row.getDouble("total_sales"));
System.out.println("Average Price: " + row.getDouble("avg_price"));
}Store, retrieve, and manipulate JSON documents in Redis.
public interface RedisJsonCommands {
/**
* Set JSON document or path
* @param key Redis key
* @param path JSON path (use Path.ROOT_PATH for entire document)
* @param object Object to serialize to JSON
* @return Status code reply
*/
String jsonSet(String key, Path path, Object object);
/**
* Set JSON with parameters
* @param key Redis key
* @param path JSON path
* @param object Object to store
* @param params Set parameters (NX, XX)
* @return Status code reply
*/
String jsonSet(String key, Path path, Object object, JsonSetParams params);
/**
* Get JSON document or path
* @param key Redis key
* @param clazz Class to deserialize to
* @return Deserialized object
*/
<T> T jsonGet(String key, Class<T> clazz);
/**
* Get JSON at specific path
* @param key Redis key
* @param clazz Class to deserialize to
* @param path JSON path
* @return Deserialized object
*/
<T> T jsonGet(String key, Class<T> clazz, Path path);
/**
* Get multiple paths
* @param key Redis key
* @param clazz Class to deserialize to
* @param paths JSON paths to retrieve
* @return Deserialized objects
*/
<T> T jsonGet(String key, Class<T> clazz, Path... paths);
/**
* Get JSON from multiple keys
* @param clazz Class to deserialize to
* @param path JSON path
* @param keys Redis keys
* @return List of deserialized objects
*/
<T> List<T> jsonMGet(Class<T> clazz, Path path, String... keys);
/**
* Delete JSON path
* @param key Redis key
* @param path JSON path to delete
* @return Number of paths deleted
*/
Long jsonDel(String key, Path path);
/**
* Get type of JSON path
* @param key Redis key
* @param path JSON path
* @return JSON type (object, array, string, number, boolean, null)
*/
String jsonType(String key, Path path);
/**
* Get number of keys in JSON object
* @param key Redis key
* @param path JSON path to object
* @return Number of keys
*/
Long jsonObjKeys(String key, Path path);
/**
* Get length of JSON array
* @param key Redis key
* @param path JSON path to array
* @return Array length
*/
Long jsonArrLen(String key, Path path);
/**
* Append to JSON array
* @param key Redis key
* @param path JSON path to array
* @param objects Objects to append
* @return New array length
*/
Long jsonArrAppend(String key, Path path, Object... objects);
/**
* Insert into JSON array
* @param key Redis key
* @param path JSON path to array
* @param index Insert position
* @param objects Objects to insert
* @return New array length
*/
Long jsonArrInsert(String key, Path path, int index, Object... objects);
/**
* Pop element from JSON array
* @param key Redis key
* @param clazz Class to deserialize to
* @param path JSON path to array
* @param index Index to pop (-1 for last element)
* @return Popped element
*/
<T> T jsonArrPop(String key, Class<T> clazz, Path path, int index);
/**
* Increment numeric value
* @param key Redis key
* @param path JSON path to number
* @param value Increment value
* @return New numeric value
*/
Double jsonNumIncrBy(String key, Path path, double value);
/**
* Get string length
* @param key Redis key
* @param path JSON path to string
* @return String length
*/
Long jsonStrLen(String key, Path path);
/**
* Append to JSON string
* @param key Redis key
* @param path JSON path to string
* @param string String to append
* @return New string length
*/
Long jsonStrAppend(String key, Path path, String string);
}public class Path {
/**
* Root path for entire JSON document
*/
public static final Path ROOT_PATH = new Path(".");
/**
* Create path from string
* @param path Path expression
*/
public Path(String path);
/**
* Create root path
* @return Root path instance
*/
public static Path of(String path);
@Override
public String toString();
}
// Path2 for JSONPath v2 (RedisJSON 2.0+)
public class Path2 {
/**
* Root path for JSONPath v2
*/
public static final Path2 ROOT_PATH = new Path2("$");
/**
* Create JSONPath v2 expression
* @param path JSONPath expression
*/
public Path2(String path);
/**
* Create path from string
* @param path Path expression
* @return Path2 instance
*/
public static Path2 of(String path);
}public class JsonSetParams implements IParams {
/**
* Set only if key doesn't exist
* @return Parameters instance
*/
public JsonSetParams nx();
/**
* Set only if key exists
* @return Parameters instance
*/
public JsonSetParams xx();
}Jedis jedis = new Jedis("localhost", 6379);
// Store JSON document
User user = new User("John", "john@example.com", 30);
jedis.jsonSet("user:1", Path.ROOT_PATH, user);
// Get entire document
User retrievedUser = jedis.jsonGet("user:1", User.class);
// Work with nested JSON
Map<String, Object> profile = new HashMap<>();
profile.put("name", "John Doe");
profile.put("age", 30);
profile.put("skills", Arrays.asList("Java", "Redis", "JSON"));
jedis.jsonSet("profile:1", Path.ROOT_PATH, profile);
// Get specific path
String name = jedis.jsonGet("profile:1", String.class, Path.of(".name"));
// Array operations
jedis.jsonArrAppend("profile:1", Path.of(".skills"), "Docker", "Kubernetes");
Long skillCount = jedis.jsonArrLen("profile:1", Path.of(".skills"));
// Increment numeric value
jedis.jsonNumIncrBy("profile:1", Path.of(".age"), 1);
// Complex nested document
String complexJson = """
{
"user": {
"id": 123,
"profile": {
"name": "Alice",
"preferences": {
"theme": "dark",
"notifications": true
}
},
"posts": [
{"title": "Hello World", "likes": 10},
{"title": "JSON in Redis", "likes": 25}
]
}
}
""";
jedis.jsonSet("document:1", Path.ROOT_PATH, complexJson);
// Query nested paths
String theme = jedis.jsonGet("document:1", String.class,
Path.of(".user.profile.preferences.theme"));
// Array element access
Integer likes = jedis.jsonGet("document:1", Integer.class,
Path.of(".user.posts[1].likes"));
jedis.close();Probabilistic data structures for membership testing.
public interface BloomFilterCommands {
/**
* Reserve Bloom filter with capacity and error rate
* @param key Bloom filter key
* @param errorRate Desired false positive rate
* @param capacity Expected number of elements
* @return Status code reply
*/
String bfReserve(String key, double errorRate, long capacity);
/**
* Reserve Bloom filter with parameters
* @param key Bloom filter key
* @param params Reserve parameters
* @return Status code reply
*/
String bfReserve(String key, BFReserveParams params);
/**
* Add item to Bloom filter
* @param key Bloom filter key
* @param item Item to add
* @return true if item was added (first time), false if already existed
*/
Boolean bfAdd(String key, String item);
/**
* Add multiple items to Bloom filter
* @param key Bloom filter key
* @param items Items to add
* @return List of boolean results for each item
*/
List<Boolean> bfMAdd(String key, String... items);
/**
* Test if item exists in Bloom filter
* @param key Bloom filter key
* @param item Item to test
* @return true if item might exist, false if definitely doesn't exist
*/
Boolean bfExists(String key, String item);
/**
* Test multiple items
* @param key Bloom filter key
* @param items Items to test
* @return List of existence test results
*/
List<Boolean> bfMExists(String key, String... items);
/**
* Get Bloom filter information
* @param key Bloom filter key
* @return Filter statistics and configuration
*/
Map<String, Object> bfInfo(String key);
/**
* Insert items with parameters
* @param key Bloom filter key
* @param params Insert parameters
* @param items Items to insert
* @return List of insertion results
*/
List<Boolean> bfInsert(String key, BFInsertParams params, String... items);
/**
* Load Bloom filter from external data
* @param key Bloom filter key
* @param iterator External iterator position
* @param data Chunk data
* @return Status code reply
*/
String bfLoadChunk(String key, long iterator, byte[] data);
/**
* Scan and dump Bloom filter
* @param key Bloom filter key
* @param iterator Iterator position
* @return Chunk data and next iterator
*/
List<Object> bfScanDump(String key, long iterator);
}public interface CuckooFilterCommands {
/**
* Reserve Cuckoo filter
* @param key Cuckoo filter key
* @param capacity Expected capacity
* @return Status code reply
*/
String cfReserve(String key, long capacity);
/**
* Reserve with parameters
* @param key Cuckoo filter key
* @param params Reserve parameters
* @return Status code reply
*/
String cfReserve(String key, CFReserveParams params);
/**
* Add item to Cuckoo filter
* @param key Cuckoo filter key
* @param item Item to add
* @return true if added successfully
*/
Boolean cfAdd(String key, String item);
/**
* Add item only if it doesn't exist
* @param key Cuckoo filter key
* @param item Item to add
* @return true if added, false if already exists
*/
Boolean cfAddNx(String key, String item);
/**
* Insert multiple items
* @param key Cuckoo filter key
* @param params Insert parameters
* @param items Items to insert
* @return Insertion results
*/
List<Boolean> cfInsert(String key, CFInsertParams params, String... items);
/**
* Test item existence
* @param key Cuckoo filter key
* @param item Item to test
* @return true if item might exist
*/
Boolean cfExists(String key, String item);
/**
* Delete item from filter
* @param key Cuckoo filter key
* @param item Item to delete
* @return true if item was deleted
*/
Boolean cfDel(String key, String item);
/**
* Count item occurrences
* @param key Cuckoo filter key
* @param item Item to count
* @return Number of occurrences
*/
Long cfCount(String key, String item);
}public interface CountMinSketchCommands {
/**
* Initialize Count-Min Sketch by dimensions
* @param key CMS key
* @param width Sketch width
* @param depth Sketch depth
* @return Status code reply
*/
String cmsInitByDim(String key, long width, long depth);
/**
* Initialize by probability and error
* @param key CMS key
* @param error Error rate
* @param probability Confidence probability
* @return Status code reply
*/
String cmsInitByProb(String key, double error, double probability);
/**
* Increment item count
* @param key CMS key
* @param item Item to increment
* @param increment Increment value
* @return Updated count estimate
*/
Long cmsIncrBy(String key, String item, long increment);
/**
* Increment multiple items
* @param key CMS key
* @param itemIncrements Map of items to increments
* @return List of updated count estimates
*/
List<Long> cmsIncrBy(String key, Map<String, Long> itemIncrements);
/**
* Query item count
* @param key CMS key
* @param items Items to query
* @return List of count estimates
*/
List<Long> cmsQuery(String key, String... items);
/**
* Get CMS information
* @param key CMS key
* @return CMS statistics
*/
Map<String, Object> cmsInfo(String key);
/**
* Merge Count-Min Sketches
* @param destKey Destination key
* @param sourceKeys Source keys to merge
* @param weights Merge weights
* @return Status code reply
*/
String cmsMerge(String destKey, String[] sourceKeys, long[] weights);
}Jedis jedis = new Jedis("localhost", 6379);
// Create Bloom filter for 1 million items with 1% false positive rate
jedis.bfReserve("users:visited", 0.01, 1000000);
// Add items
jedis.bfAdd("users:visited", "user:123");
jedis.bfAdd("users:visited", "user:456");
jedis.bfAdd("users:visited", "user:789");
// Bulk add
List<Boolean> addResults = jedis.bfMAdd("users:visited",
"user:100", "user:200", "user:300");
// Test membership
boolean exists = jedis.bfExists("users:visited", "user:123"); // true
boolean notExists = jedis.bfExists("users:visited", "user:999"); // false (probably)
// Batch test
List<Boolean> existResults = jedis.bfMExists("users:visited",
"user:123", "user:456", "user:999");
// Get filter info
Map<String, Object> info = jedis.bfInfo("users:visited");
System.out.println("Capacity: " + info.get("Capacity"));
System.out.println("Size: " + info.get("Size"));
System.out.println("Filters: " + info.get("Number of filters"));
// Count-Min Sketch for frequency counting
jedis.cmsInitByProb("page:views", 0.01, 0.99); // 1% error, 99% confidence
// Count page views
jedis.cmsIncrBy("page:views", "/home", 1);
jedis.cmsIncrBy("page:views", "/products", 5);
jedis.cmsIncrBy("page:views", "/about", 2);
// Query counts
List<Long> viewCounts = jedis.cmsQuery("page:views", "/home", "/products", "/about");
System.out.println("Page view counts: " + viewCounts);
jedis.close();Store and query time series data efficiently.
public interface TimeSeriesCommands {
/**
* Create time series
* @param key Time series key
* @return Status code reply
*/
String tsCreate(String key);
/**
* Create time series with parameters
* @param key Time series key
* @param params Creation parameters
* @return Status code reply
*/
String tsCreate(String key, TSCreateParams params);
/**
* Add sample to time series
* @param key Time series key
* @param timestamp Sample timestamp (Unix timestamp in milliseconds)
* @param value Sample value
* @return Timestamp of added sample
*/
Long tsAdd(String key, long timestamp, double value);
/**
* Add sample with parameters
* @param key Time series key
* @param timestamp Sample timestamp
* @param value Sample value
* @param params Add parameters
* @return Timestamp of added sample
*/
Long tsAdd(String key, long timestamp, double value, TSAddParams params);
/**
* Add multiple samples
* @param sampleKeyValueTimestamp Array of samples (key, timestamp, value)
* @return List of add results
*/
List<Long> tsMAdd(String... sampleKeyValueTimestamp);
/**
* Increment time series value
* @param key Time series key
* @param value Increment value
* @return Timestamp of incremented sample
*/
Long tsIncrBy(String key, double value);
/**
* Increment with timestamp
* @param key Time series key
* @param value Increment value
* @param timestamp Specific timestamp
* @return Timestamp of incremented sample
*/
Long tsIncrBy(String key, double value, long timestamp);
/**
* Decrement time series value
* @param key Time series key
* @param value Decrement value
* @return Timestamp of decremented sample
*/
Long tsDecrBy(String key, double value);
/**
* Get range of samples
* @param key Time series key
* @param fromTimestamp Start timestamp
* @param toTimestamp End timestamp
* @return List of time series elements
*/
List<TSElement> tsRange(String key, long fromTimestamp, long toTimestamp);
/**
* Get range with parameters
* @param key Time series key
* @param fromTimestamp Start timestamp
* @param toTimestamp End timestamp
* @param params Range parameters
* @return List of time series elements
*/
List<TSElement> tsRange(String key, long fromTimestamp, long toTimestamp,
TSRangeParams params);
/**
* Get reverse range
* @param key Time series key
* @param fromTimestamp Start timestamp
* @param toTimestamp End timestamp
* @return List of time series elements in reverse order
*/
List<TSElement> tsRevRange(String key, long fromTimestamp, long toTimestamp);
/**
* Get multiple time series ranges
* @param fromTimestamp Start timestamp
* @param toTimestamp End timestamp
* @param filters Filter expressions
* @return Map of time series keys to elements
*/
Map<String, List<TSElement>> tsMRange(long fromTimestamp, long toTimestamp,
String... filters);
/**
* Multi-range with parameters
* @param params Multi-range parameters
* @return Map of time series to elements
*/
Map<String, List<TSElement>> tsMRange(TSMRangeParams params);
/**
* Get latest sample
* @param key Time series key
* @return Latest time series element
*/
TSElement tsGet(String key);
/**
* Get latest samples from multiple series
* @param filters Filter expressions
* @return Map of time series keys to latest elements
*/
Map<String, TSElement> tsMGet(String... filters);
/**
* Get time series information
* @param key Time series key
* @return Time series metadata and statistics
*/
TSInfo tsInfo(String key);
/**
* Delete range of samples
* @param key Time series key
* @param fromTimestamp Start timestamp
* @param toTimestamp End timestamp
* @return Number of deleted samples
*/
Long tsDel(String key, long fromTimestamp, long toTimestamp);
/**
* Create aggregation rule
* @param sourceKey Source time series
* @param destKey Destination time series
* @param aggregationType Aggregation function
* @param timeBucket Time bucket duration
* @return Status code reply
*/
String tsCreateRule(String sourceKey, String destKey,
AggregationType aggregationType, long timeBucket);
/**
* Delete aggregation rule
* @param sourceKey Source time series
* @param destKey Destination time series
* @return Status code reply
*/
String tsDeleteRule(String sourceKey, String destKey);
/**
* Query index for time series keys
* @param filters Filter expressions
* @return List of matching time series keys
*/
List<String> tsQueryIndex(String... filters);
}public class TSCreateParams implements IParams {
/**
* Set retention period in milliseconds
* @param retention Retention period
* @return Parameters instance
*/
public TSCreateParams retention(long retention);
/**
* Set uncompressed storage
* @return Parameters instance
*/
public TSCreateParams uncompressed();
/**
* Add labels for indexing and filtering
* @param labels Label key-value pairs
* @return Parameters instance
*/
public TSCreateParams labels(Map<String, String> labels);
/**
* Set duplicate policy
* @param policy Duplicate handling policy
* @return Parameters instance
*/
public TSCreateParams duplicatePolicy(DuplicatePolicy policy);
/**
* Set chunk size
* @param chunkSize Chunk size in bytes
* @return Parameters instance
*/
public TSCreateParams chunkSize(long chunkSize);
}
public class TSAddParams implements IParams {
public TSAddParams retention(long retention);
public TSAddParams uncompressed();
public TSAddParams labels(Map<String, String> labels);
public TSAddParams onDuplicate(DuplicatePolicy policy);
public TSAddParams chunkSize(long chunkSize);
}
public class TSRangeParams implements IParams {
/**
* Limit number of samples returned
* @param count Maximum number of samples
* @return Parameters instance
*/
public TSRangeParams count(long count);
/**
* Aggregate samples
* @param aggregationType Aggregation function
* @param timeBucket Time bucket size
* @return Parameters instance
*/
public TSRangeParams aggregation(AggregationType aggregationType, long timeBucket);
/**
* Filter by labels
* @param filters Label filter expressions
* @return Parameters instance
*/
public TSRangeParams filterByLabels(String... filters);
}
public enum AggregationType {
AVG, SUM, MIN, MAX, RANGE, COUNT, STD_P, STD_S, VAR_P, VAR_S, FIRST, LAST
}
public enum DuplicatePolicy {
BLOCK, FIRST, LAST, MIN, MAX, SUM
}public class TSElement {
/**
* Get sample timestamp
* @return Unix timestamp in milliseconds
*/
public long getTimestamp();
/**
* Get sample value
* @return Numeric value
*/
public double getValue();
@Override
public String toString();
}
public class TSInfo {
/**
* Get total samples in time series
* @return Sample count
*/
public long getTotalSamples();
/**
* Get memory usage in bytes
* @return Memory usage
*/
public long getMemoryUsage();
/**
* Get first timestamp
* @return First timestamp
*/
public long getFirstTimestamp();
/**
* Get last timestamp
* @return Last timestamp
*/
public long getLastTimestamp();
/**
* Get retention period
* @return Retention in milliseconds
*/
public long getRetentionTime();
/**
* Get labels
* @return Label map
*/
public Map<String, String> getLabels();
/**
* Get aggregation rules
* @return List of rules
*/
public List<Map<String, Object>> getRules();
}Jedis jedis = new Jedis("localhost", 6379);
// Create time series for temperature sensor
Map<String, String> labels = Map.of(
"sensor", "temperature",
"location", "server_room",
"unit", "celsius"
);
TSCreateParams createParams = TSCreateParams.createParams()
.retention(86400000) // 1 day retention
.labels(labels);
jedis.tsCreate("temperature:sensor1", createParams);
// Add temperature readings
long now = System.currentTimeMillis();
jedis.tsAdd("temperature:sensor1", now - 3600000, 22.5); // 1 hour ago
jedis.tsAdd("temperature:sensor1", now - 1800000, 23.1); // 30 min ago
jedis.tsAdd("temperature:sensor1", now, 24.2); // Now
// Create aggregated series for hourly averages
jedis.tsCreate("temperature:sensor1:hourly");
jedis.tsCreateRule("temperature:sensor1", "temperature:sensor1:hourly",
AggregationType.AVG, 3600000); // 1 hour buckets
// Query recent temperature data
List<TSElement> recentData = jedis.tsRange("temperature:sensor1",
now - 7200000, now);
for (TSElement element : recentData) {
System.out.printf("Timestamp: %d, Temperature: %.1f°C%n",
element.getTimestamp(), element.getValue());
}
// Get hourly aggregates
TSRangeParams rangeParams = TSRangeParams.rangeParams()
.aggregation(AggregationType.AVG, 3600000) // Hourly average
.count(24); // Last 24 hours
List<TSElement> hourlyAvg = jedis.tsRange("temperature:sensor1",
now - 86400000, now, rangeParams);
// Multi-series query with filters
Map<String, List<TSElement>> multiData = jedis.tsMRange(
now - 3600000, now,
"sensor=temperature", "location=server_room"
);
// Get latest readings from all temperature sensors
Map<String, TSElement> latestReadings = jedis.tsMGet("sensor=temperature");
// Time series information
TSInfo info = jedis.tsInfo("temperature:sensor1");
System.out.println("Total samples: " + info.getTotalSamples());
System.out.println("Memory usage: " + info.getMemoryUsage() + " bytes");
System.out.println("Retention: " + info.getRetentionTime() + " ms");
jedis.close();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.
Install with Tessl CLI
npx tessl i tessl/maven-redis-clients--jedis