Skip to content

Commit

Permalink
Redis.io code examples (#3418)
Browse files Browse the repository at this point in the history
* Added a simple SET and GET example

* Added a meta data file. Needs to be removed as soon as we added this into the files themselves.

* Update SetGetTest.java

Added output comments

* Update SetGetTest.java

Changed the output to be more use case specific.

* Wrapped the code by a test suite to keep it self-explaining

* Update SetGetExample.java

* Update SimpleCommandsTestSuite.java

Added some comments

* Update SimpleCommandsTestSuite.java

Added some additional comments about how to combine code samples with JUnit tests.

* Update SetGetExample.java

* Update example.json

Testing with wildcard search for examples.

* Update SetGetExample.java

Hiding the end of the file by default

* Update SetGetExample.java

* Update SetGetExample.java

* Test annotations are now ignored by the doc parser

* Changed the package name

* Remove indentation

* New 'Example' file name rule

* Revert indentation in SetGetExample.java

* skeleton of documentation tests

* Make doctests runnable in CI

- Move doctests to test folder to make them
  discoverable by JUnit
- Add doctests profile
- Fix doctests workflow

* Add Search QuickStart to doctests

* Fix workflow file

* Bump Java version to 11

* Exclude doctests from testCompile

* Give up on 2 Java versions support

* surefire plugin 3.0.0

* fix updated doc package

---------

Co-authored-by: David Maier <60782329+dmaier-redislabs@users.noreply.github.com>
Co-authored-by: M Sazzadul Hoque <7600764+sazzad16@users.noreply.github.com>
Co-authored-by: Chayim I. Kirshen <c@kirshen.com>
  • Loading branch information
4 people committed May 16, 2023
1 parent 1b7c5cc commit 8e6a709
Show file tree
Hide file tree
Showing 6 changed files with 309 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ Set up test environments with ```make start```, tear down those environments wit
* You can import code style file (located to hbase-formatter.xml) to Eclipse, IntelliJ
* line break by column count seems not working with IntelliJ
* <strike>You can run ```make format``` anytime to reformat without IDEs</strike>
* DO NOT format the source codes within `io.redis.examples` test package.
* A test class name MUST NOT end with `Example`.

## Adding commands

Expand Down
35 changes: 35 additions & 0 deletions .github/workflows/doctests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Documentation Tests

on:
push:
pull_request:
workflow_dispatch:

jobs:
doctests:
runs-on: ubuntu-latest
services:
redis-stack:
image: redis/redis-stack-server:latest
options: >-
--health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5
ports:
- 6379:6379

steps:
- uses: actions/checkout@v3
- name: Cache dependencies
uses: actions/cache@v2
with:
path: |
~/.m2/repository
/var/cache/apt
key: jedis-${{hashFiles('**/pom.xml')}}
- name: Set up Java
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'temurin'
- name: Run doctests
run: |
mvn -Pdoctests test
17 changes: 17 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@
<systemPropertyVariables>
<redis-hosts>${redis-hosts}</redis-hosts>
</systemPropertyVariables>
<excludes>
<exclude>**/examples/*Example.java</exclude>
</excludes>
<!--<trimStackTrace>false</trimStackTrace>-->
</configuration>
</plugin>
Expand Down Expand Up @@ -285,5 +288,19 @@
</plugins>
</build>
</profile>
<profile>
<id>doctests</id>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<test>**/examples/*Example.java</test>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
218 changes: 218 additions & 0 deletions src/test/java/io/redis/examples/SearchQuickstartExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
//EXAMPLE: set_and_get
//HIDE_START
package io.redis.examples;

import java.math.BigDecimal;
import java.util.*;

import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.*;
import redis.clients.jedis.search.*;
import redis.clients.jedis.search.aggr.*;
import redis.clients.jedis.search.schemafields.*;
//REMOVE_START
import org.junit.Test;

import static org.junit.Assert.assertEquals;
//REMOVE_END

class Bicycle {
public String brand;
public String model;
public BigDecimal price;
public String description;
public String condition;

public Bicycle(String brand, String model, BigDecimal price, String description, String condition) {
this.brand = brand;
this.model = model;
this.price = price;
this.description = description;
this.condition = condition;
}
}

public class SearchQuickstartExample {

@Test
public void run() {
//HIDE_END

// STEP_START connect
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
// STEP_END
// REMOVE_START
try {
jedis.ftDropIndex("idx:bicycle");
} catch (JedisDataException e) {
// ignore
}
// REMOVE_END

// STEP_START data_sample
Bicycle bike1 = new Bicycle(
"Diaz Ltd",
"Dealer Sl",
new BigDecimal(7315.58),
"The Diaz Ltd Dealer Sl is a reliable choice" +
" for urban cycling. The Diaz Ltd Dealer Sl " +
"is a comfortable choice for urban cycling.",
"used"
);
// STEP_END

Bicycle[] bicycles = {
bike1,
new Bicycle(
"Bridges Group",
"Project Pro",
new BigDecimal(3610.82),
"This mountain bike is perfect for mountain biking. The Bridges" +
" Group Project Pro is a responsive choice for mountain biking.",
"used"
),
new Bicycle(
"Vega, Cole and Miller",
"Group Advanced",
new BigDecimal(8961.42),
"The Vega, Cole and Miller Group Advanced provides a excellent" +
" ride. With its fast carbon frame and 24 gears, this bicycle is" +
" perfect for any terrain.",
"used"
),
new Bicycle(
"Powell-Montgomery",
"Angle Race",
new BigDecimal(4050.27),
"The Powell-Montgomery Angle Race is a smooth choice for road" +
" cycling. The Powell-Montgomery Angle Race provides a durable" +
" ride.",
"used"
),
new Bicycle(
"Gill-Lewis",
"Action Evo",
new BigDecimal(283.68),
"The Gill-Lewis Action Evo provides a smooth ride. The Gill-Lewis" +
" Action Evo provides a excellent ride.",
"used"
),
new Bicycle(
"Rodriguez-Guerrero",
"Drama Comp",
new BigDecimal(4462.55),
"This kids bike is perfect for young riders. With its excellent" +
" aluminum frame and 12 gears, this bicycle is perfect for any" +
" terrain.",
"new"
),
new Bicycle(
"Moore PLC",
"Award Race",
new BigDecimal(3790.76),

"This olive folding bike features a carbon frame and 27.5 inch" +
" wheels. This folding bike is perfect for compact storage and" +
" transportation.",
"new"
),
new Bicycle(
"Hall, Haley and Hayes",
"Weekend Plus",
new BigDecimal(2008.4),
"The Hall, Haley and Hayes Weekend Plus provides a comfortable" +
" ride. This blue kids bike features a steel frame and 29.0 inch" +
" wheels.",
"new"
),
new Bicycle(
"Peck-Carson",
"Sun Hybrid",
new BigDecimal(9874.95),
"With its comfortable aluminum frame and 25 gears, this bicycle is" +
" perfect for any terrain. The Peck-Carson Sun Hybrid provides a" +
" comfortable ride.",
"new"
),
new Bicycle(
"Fowler Ltd",
"Weekend Trail",
new BigDecimal(3833.71),
"The Fowler Ltd Letter Trail is a comfortable choice for" +
" transporting cargo. This cargo bike is perfect for transporting" +
" cargo.",
"refurbished"
)
};

// STEP_START define_index
SchemaField[] schema = {
TextField.of("$.brand").as("brand"),
TextField.of("$.model").as("model"),
TextField.of("$.description").as("description"),
NumericField.of("$.price").as("price"),
TagField.of("$.condition").as("condition")
};
// STEP_END

// STEP_START create_index
jedis.ftCreate("idx:bicycle",
FTCreateParams.createParams()
.on(IndexDataType.JSON)
.addPrefix("bicycle:"),
schema
);
// STEP_END
// STEP_START add_documents
for (int i = 0; i < bicycles.length; i++) {
jedis.jsonSetWithEscape(String.format("bicycle:%d", i), bicycles[i]);
}
// STEP_END

// STEP_START query_single_term_and_num_range
Query query = new Query("folding @price:[1000 4000]");
List<Document> result = jedis.ftSearch("idx:bicycle", query).getDocuments();
System.out.println(result);
// Prints: [id:bicycle:6, score: 1.0, payload:null, properties:[
// $={"brand":"Moore PLC","model":"Award Race","price":3790.76,
// "description":"This olive folding bike features a carbon frame and 27.5 inch wheels.
// This folding bike is perfect for compact storage and transportation.","condition":"new"}]
// ]
// STEP_END
// REMOVE_START
assertEquals("Validate folding bike id", "bicycle:6", result.get(0).getId());
// REMOVE_END

// STEP_START query_single_term_limit_fields
Query cargo_query = new Query("cargo").returnFields("price");
List<Document> cargo_result = jedis.ftSearch(
"idx:bicycle", cargo_query).getDocuments();
System.out.println(cargo_result);
// Prints: [id:bicycle:9, score: 1.0, payload:null, properties:[price=3833.71]]
// STEP_END
// REMOVE_START
assertEquals("Validate cargo bike id", "bicycle:9", cargo_result.get(0).getId());
// REMOVE_END

// STEP_START simple_aggregation
AggregationBuilder ab = new AggregationBuilder("*")
.groupBy("@condition", Reducers.count().as("count"));
AggregationResult ar = jedis.ftAggregate("idx:bicycle", ab);

for (int i = 0; i < ar.getTotalResults(); i++) {
System.out.println(
ar.getRow(i).getString("condition")
+ " - "
+ ar.getRow(i).getString("count"));
}
// Prints:
// refurbished - 1
// used - 5
// new - 4
// STEP_END
// REMOVE_START
assertEquals("Validate aggregation results", 3, ar.getTotalResults());
// REMOVE_END
}
}
//HIDE_END
36 changes: 36 additions & 0 deletions src/test/java/io/redis/examples/SetGetExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//EXAMPLE: set_and_get
//HIDE_START
package io.redis.examples;

import redis.clients.jedis.UnifiedJedis;
//REMOVE_START
import org.junit.Test;
import static org.junit.Assert.assertEquals;
//REMOVE_END

public class SetGetExample {

@Test
public void run() {

UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");

//HIDE_END
String status = jedis.set("bike:1", "Process 134");

if ("OK".equals(status))
System.out.println("Successfully added a bike.");

String value = jedis.get("bike:1");

if ( value != null)
System.out.println("The name of the bike is: " + value + ".");
//HIDE_START

//REMOVE_START
assertEquals("OK", status);
assertEquals("Process 134", value);
//REMOVE_END
}
}
//HIDE_END
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPooled;

public class RedisCredentialsProviderExample {
public class RedisCredentialsProviderUsage {

public static void main(String[] args) {

Expand Down

0 comments on commit 8e6a709

Please sign in to comment.