系统架构

RedisJSON实战进阶

2021-12-23  本文已影响0人  lcjyzm

主要实现json文档的条件查询,文档高亮显示,分页 功能

maven依赖

<!--jedis版本要是4.0或更高-->
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.0.0</version>
</dependency>       

java代码

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.providers.PooledConnectionProvider;
import redis.clients.jedis.search.*;

import java.util.List;
import java.util.stream.IntStream;

/**
 * <p>
 *      RedisJson测试类
 * </p>
 *
 * @author: liuchangjun
 * @since: 2021/12/22 15:50
 */
public class RedisJsonTest {

    /**
     * <p>
     *     使用jedis操作
     * </p>
     */
    @Test
    public void testWithJedis(){
        // 获取连接
        HostAndPort config = new HostAndPort("127.0.0.1", 6379);
        PooledConnectionProvider provider = new PooledConnectionProvider(config);
        UnifiedJedis client = new UnifiedJedis(provider);

        // 创建学生对象
        Student student1 = new Student("John","Smith",30,"杭州萧山");
        Student student2 = new Student("John","White",37,"北京海定");
        Student student3 = new Student("Tom","White",24,"美国纽约");
        // 添加json
        client.jsonSet("student:1", redis.clients.jedis.json.Path.ROOT_PATH,student1);
        client.jsonSet("student:2",redis.clients.jedis.json.Path.ROOT_PATH,student2);
        client.jsonSet("student:3",redis.clients.jedis.json.Path.ROOT_PATH,student3);
        // 查询
        Student student = client.jsonGet("student:1", Student.class,redis.clients.jedis.json.Path.ROOT_PATH);
        System.out.println(JSONUtil.toJsonStr(student));

        // 删除索引
        client.ftDropIndex("student-index");

        // 创建索引
        // 创建要索引的字段
        Schema schema = new Schema().
                addField(new Schema.Field(new FieldName("$.firstName", "first"), Schema.FieldType.TEXT)).
                addField(new Schema.Field(new FieldName("$.lastName", "last"), Schema.FieldType.TEXT)).
                addField(new Schema.Field(new FieldName("$.address", "address"), Schema.FieldType.TEXT));
        // 只索引key以student:开头的
        IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON).setPrefixes("student:");
        // 创建索引
        client.ftCreate("student-index",IndexOptions.defaultOptions().setDefinition(rule),schema);

        // 查询名字以John开头的学生,并高亮显示
        Query q = new Query("@first:John*").
                highlightFields(new Query.HighlightTags("<b>","</b>"),"first").
                returnFields("first","address","last");
        SearchResult searchResult = client.ftSearch("student-index", q);
        List<Document> documents = searchResult.getDocuments();
        for(Document document : documents){
            Console.log(JSONUtil.toJsonStr(document));
        }

    }

    @Test
    public void testWithJedis2(){
        // 获取连接
        HostAndPort config = new HostAndPort("127.0.0.1", 6379);
        PooledConnectionProvider provider = new PooledConnectionProvider(config);
        UnifiedJedis client = new UnifiedJedis(provider);


        // 创建学生对象
        IntStream.range(1,20).boxed().forEach(i -> {
            Student student = new Student("John" + i,"Smith" + i,30,"杭州萧山" + i);
            // 添加json
            client.jsonSet("student:" + i, redis.clients.jedis.json.Path.ROOT_PATH,student);
        });

        // 删除索引
        client.ftDropIndex("student-index");

        // 创建索引
        // 创建要索引的字段
        Schema schema = new Schema().
                addTextField("$.firstName",1.0).
                addTextField("$.lastName", 1.0).
                addTextField("$.address",1.0);
        // 只索引key以student:开头的
        IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON).setPrefixes("student:");
        // 创建索引
        client.ftCreate("student-index",IndexOptions.defaultOptions().setDefinition(rule),schema);

        // 查询名字以John开头的学生,并高亮显示,带分页
        // 查询字符串需要转义
        Query q = new Query("@\\$\\.firstName:John*").
                highlightFields(new Query.HighlightTags("<b>","</b>"),"$.firstName").
                returnFields("$.firstName","$.lastName","$.address").limit(1,10);
        SearchResult searchResult = client.ftSearch("student-index", q);
        List<Document> documents = searchResult.getDocuments();
        for(Document document : documents){
            Console.log(JSONUtil.toJsonStr(document));
        }

    }


    @Data
    @AllArgsConstructor
    private static class Student {
        private String firstName;
        private String lastName;
        private int age;
        private String address;
    }
}
上一篇下一篇

猜你喜欢

热点阅读