Sunday, April 23, 2023

Redis Document/Search - Java Examples

Summary

This post will provide some snippets from Redis Query Workshop available on GitHub.  That workshop covers parallel examples in CLI, Python, Nodejs, Java, and C#.  This post will focus on Java examples.



Basic JSON


no = new JSONObject();
no.put("num1", 1);
no.put("arr2", new JSONArray(Arrays.asList("val1", "val2", "val3")));
jo = new JSONObject();
jo.put("str1", "val1");
jo.put("str2", "val2");
jo.put("arr1", new JSONArray(Arrays.asList(1, 2, 3, 4)));
jo.put("obj1", no);
client.jsonSet("ex2:5", jo);
res = client.jsonGetAsPlainString("ex2:5", new Path("$.obj1.arr2"));
System.out.println(res);
res = client.jsonGetAsPlainString("ex2:5", new Path("$.arr1[1]"));
System.out.println(res);
res = client.jsonGetAsPlainString("ex2:5", new Path("$.obj1.arr2[0:2]"));
System.out.println(res);
res = client.jsonGetAsPlainString("ex2:5", new Path("$.arr1[-2:]"));
System.out.println(res);
[["val1","val2","val3"]]
[2]
["val1","val2"]
[3,4]

Basic Search


Schema schema = new Schema().addNumericField("$.id")
.addTagField("$.gender").as("gender")
.addTagField("$.season.*").as("season")
.addTextField("$.description", 1.0).as("description")
.addNumericField("$.price").as("price")
.addTextField("$.city",1.0).as("city")
.addGeoField("$.coords").as("coords");
IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON)
.setPrefixes(new String[]{"product:"});
client.ftCreate("idx1", IndexOptions.defaultOptions().setDefinition(rule), schema);
private class Product {
private int id;
private String gender;
private String[] season;
private String description;
private double price;
private String city;
private String coords;
public Product(int id, String gender, String[] season,
String description, double price, String city, String coords) {
this.id = id;
this.gender = gender;
this.season = season;
this.description = description;
this.price = price;
this.city = city;
this.coords = coords;
}
}
Product prod15970 = new Product(15970, "Men", new String[]{"Fall, Winter"}, "Turtle Check Men Navy Blue Shirt",
34.95, "Boston", "-71.057083, 42.361145");
Product prod59263 = new Product(59263, "Women", new String[]{"Fall, Winter", "Spring", "Summer"}, "Titan Women Silver Watch",
129.99, "Dallas", "-96.808891, 32.779167");
Product prod46885 = new Product(46885, "Boys", new String[]{"Fall"}, "Ben 10 Boys Navy Blue Slippers",
45.99, "Denver", "-104.991531, 39.742043");
Gson gson = new Gson();
client.jsonSet("product:15970", gson.toJson(prod15970));
client.jsonSet("product:59263", gson.toJson(prod59263));
client.jsonSet("product:46885", gson.toJson(prod46885));
q = new Query("@price:[40, 100] @description:Blue");
res = client.ftSearch("idx1", q);
docs = res.getDocuments();
for (Document doc : docs) {
System.out.println(doc);
}
id:product:46885, score: 1.0, payload:null, properties:[$={"id":59263,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"}]

Advanced JSON


private class Product {
private int id;
private String gender;
private String[] season;
private String description;
private double price;
public Product(int id, String gender, String[] season, String description, double price) {
this.id = id;
this.gender = gender;
this.season = season;
this.description = description;
this.price = price;
}
}
private class Warehouse {
private String city;
private String location;
private Product[] inventory;;
public Warehouse(String city, String location, Product[] inventory) {
this.city = city;
this.location = location;
this.inventory = inventory;
}
}
Product prod15970 = new Product(15970, "Men", new String[]{"Fall", "Winter"}, "Turtle Check Men Navy Blue Shirt",
34.95);
Product prod59263 = new Product(59263, "Women", new String[]{"Fall", "Winter", "Spring", "Summer"}, "Titan Women Silver Watch",
129.99);
Product prod46885 = new Product(46885, "Boys", new String[]{"Fall"}, "Ben 10 Boys Navy Blue Slippers",
45.99);
Warehouse wh1 = new Warehouse("Boston", "42.361145, -71.057083",
new Product[]{prod15970, prod59263, prod46885});
Gson gson = new Gson();
client.jsonSet("warehouse:1", gson.toJson(wh1));
res = client.jsonGetAsPlainString("warehouse:1",
new Path("$.inventory[?(@.description==\"Turtle Check Men Navy Blue Shirt\")]"));
System.out.println(res);
[{"id":15970,"gender":"Men","season":["Fall","Winter"],"description":"Turtle Check Men Navy Blue Shirt","price":34.95}]

Advanced Search


HashMap<String, Object> attr = new HashMap<String, Object>();
attr.put("TYPE", "FLOAT32");
attr.put("DIM", "4");
attr.put("DISTANCE_METRIC", "L2");
Schema schema = new Schema().addVectorField("$.vector", Schema.VectorField.VectorAlgo.FLAT, attr).as("vector");
IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON)
.setPrefixes(new String[]{"vec:"});
client.ftCreate("vss_idx", IndexOptions.defaultOptions().setDefinition(rule), schema);
client.jsonSet("vec:1", new JSONObject("{\"vector\": [1,1,1,1]}"));
client.jsonSet("vec:2", new JSONObject("{\"vector\": [2,2,2,2]}"));
client.jsonSet("vec:3", new JSONObject("{\"vector\": [3,3,3,3]}"));
client.jsonSet("vec:4", new JSONObject("{\"vector\": [4,4,4,4]}"));
float[] vec = new float[]{2,2,3,3};
ByteBuffer buffer = ByteBuffer.allocate(vec.length * Float.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.asFloatBuffer().put(vec);
Query q = new Query("*=>[KNN 3 @vector $query_vec]")
.addParam("query_vec", buffer.array())
.setSortBy("__vector_score", true)
.dialect(2);
SearchResult res = client.ftSearch("vss_idx", q);
List<Document> docs = res.getDocuments();
for (Document doc : docs) {
System.out.println(doc);
}
id:vec:2, score: 1.0, payload:null, properties:[$={"vector":[2,2,2,2]}, __vector_score=2]
id:vec:3, score: 1.0, payload:null, properties:[$={"vector":[3,3,3,3]}, __vector_score=2]
id:vec:1, score: 1.0, payload:null, properties:[$={"vector":[1,1,1,1]}, __vector_score=10]

Source


Copyright ©1993-2024 Joey E Whelan, All rights reserved.