关于java:可能是全网第一个使用RediSearch实战的项目

6次阅读

共计 5113 个字符,预计需要花费 13 分钟才能阅读完成。

实战我的项目地址 newbeemall,集成 RediSearch,代码开源已上传,反对的话能够点个 star😁

RediSearch 是基于 Redis 开发的反对二级索引、查问引擎和全文搜寻的应用程序。在 2.0 的版本中,简略看下官网测试报告:

索引构建

在索引构建测试中,RediSearch 用 221 秒的速度超过了 Elasticsearch 的 349 秒,当先 58%,

查问性能

数据集建设索引后,咱们应用运行在专用负载生成器服务器上的 32 个客户端启动了两个词的搜寻查问。如下图所示,RediSearch 的吞吐量达到了 12.5K ops/sec,而 Elasticsearch 的吞吐量达到了 3.1K ops/sec,快了 4 倍。此外,RediSearch 的提早稍好一些,均匀为 8 毫秒,而 Elasticsearch 为 10 毫秒。
(ops/sec 每秒操作数)

由此可见,新的 RediSearch 在性能上比照 RediSearch 较有劣势,此外对中文我的项目来说对于中文的反对必不可少,RediSearch 也在官网文档特意列出了反对中文,基于 frisoC 语言开发的中文分词我的项目。

一、RediSearch 装置

Docker 装置最新版

docker run -p 6379:6379 redislabs/redisearch:latest

通过 redis-cli 连贯查看 RediSearch 是否装置胜利

1、redis-cli -h localhost 
2、module list
82.157.141.70:16789> MODULE LIST 

    1) 1) "name"
       2) "search" # 查看是否蕴含 search 模块
       3) "ver"
       4) (integer) 20210
    2) 1) "name"
       2) "ReJSON" # 查看是否蕴含 ReJSON 模块
       3) "ver"
       4) (integer) 20007

二、客户端集成

对于 Java 我的项目间接选用 Jedis4.0 版本就能够,Jedis 在 4.0 版本主动反对 RediSearch,编写 Jedis 连贯 RedisSearch 测试用例,用 RedisSearch 命令创立如下:

FT.CREATE idx:goods on hash prefix 1 "goods:" language chinese schema goodsName text sortable
// FT.CREATE 创立索引命令
// idx:goods 索引名称
// on hash 索引数据基于 hash 类型源数据构建
// prefix 1 "goods:" 示意要创立索引的源数据前缀匹配规定
// language chinese 示意反对中文语言分词
// schema 示意字段定义,goodsName 元数据属性名 text 字段类型 sortable 自持排序

FT.INFO idx:goods 
// FT.INFO 查问指定名称索引信息

FT.DROPINDEX idx:goods 
// FT.DROPINDEX 删除指定名称索引,不会删除源数据

增加索引时,应用 hset 命令增加索引源数据
删除索引时,应用 del 命令删除索引源数据
  1. Jedis 创立 RediSearch 客户端

    @Bean
    public UnifiedJedis unifiedJedis(GenericObjectPoolConfig jedisPoolConfig) {
     UnifiedJedis client;
     if (StringUtils.isNotEmpty(password)) {client = new JedisPooled(jedisPoolConfig, host, port, timeout, password, database);
     } else {client = new JedisPooled(jedisPoolConfig, host, port, timeout, null, database);
     }
     return client;
    }
    
  2. Jedis 创立索引

    @Test
    public void createIndex() {System.out.println("begin");
     Schema schema = new Schema()
             .addSortableTextField("goodsName", 1.0)
             .addSortableTextField("goodsIntro", 0.5)
             .addSortableTagField("tag", "|");
     jedisSearch.createIndex(idxName, "goods", schema);
     System.out.println("end");
    }
    
    /**
     * 创立索引
     *
     * @param idxName 索引名称
     * @param prefix  要索引的数据前缀
     * @param schema  索引字段配置
     */
    public void createIndex(String idxName, String prefix, Schema schema) {IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.HASH)
             .setPrefixes(prefix)
             .setLanguage(Constants.GOODS_IDX_LANGUAGE); # 设置反对中文分词
     client.ftCreate(idxName,
             IndexOptions.defaultOptions().setDefinition(rule),
             schema);
    }
    
  3. Jedis 增加索引源数据

    /**
     * 增加索引数据
     *
     * @param keyPrefix 要索引的数据前缀
     * @param goods     商品信息
     * @return boolean
     */
    public boolean addGoodsIndex(String keyPrefix, Goods goods) {Map<String, String> hash = MyBeanUtil.toMap(goods);
     hash.put("_language", Constants.GOODS_IDX_LANGUAGE);
     client.hset(keyPrefix + goods.getGoodsId(), MyBeanUtil.toMap(goods));
     return true;
    }
  4. Jedis 中文查问

    public SearchResult search(String goodsIdxName, SearchObjVO searchObjVO,     Page<SearchPageGoodsVO> page) {String keyword = searchObjVO.getKeyword(); // 查问关键字
     String queryKey = String.format("@goodsName:(%s)", keyword);
     Query q = new Query(queryKey);
     String sort = searchObjVO.getSidx();
     String order = searchObjVO.getOrder();
     // 查问是否排序
     if (StringUtils.isNotBlank(sort)) {q.setSortBy(sort, Constants.SORT_ASC.equals(order));
    
     }
     // 设置中文分词查问
     q.setLanguage(Constants.GOODS_IDX_LANGUAGE);
     // 查问分页
     q.limit((int) page.offset(), (int) page.getSize());
     // 返回查问后果
     return client.ftSearch(goodsIdxName, q);
    }

三、我的项目实战

  1. 引入 Jedis4.0

    <jedis.version>4.2.0</jedis.version>
    <!-- jedis -->
    <dependency>
     <groupId>redis.clients</groupId>
     <artifactId>jedis</artifactId>
     <version>${jedis.version}</version>
    </dependency>
    
  2. 在 newbeemall 我的项目后盾商品治理中增加同步按钮

编写商品全量同步按钮,为了放慢同步速度,通过多线程同步

// 同步商品到 RediSearch
public boolean syncRs() {jedisSearch.dropIndex(Constants.GOODS_IDX_NAME);
    Schema schema = new Schema()
            .addSortableTextField("goodsName", 1.0)
            .addSortableTextField("goodsIntro", 0.5)
            .addSortableNumericField("goodsId")
            .addSortableNumericField("sellingPrice")
            .addSortableNumericField("originalPrice")
            .addSortableTagField("tag", "|");
    jedisSearch.createIndex(Constants.GOODS_IDX_NAME, "goods:", schema);
    List<Goods> list = this.list();
    jedisSearch.deleteGoodsList(Constants.GOODS_IDX_PREFIX);
    return jedisSearch.addGoodsListIndex(Constants.GOODS_IDX_PREFIX, list);
}
/**
 * 同步商品索引
 *
 * @param keyPrefix 要索引的数据前缀
 * @return boolean
 */
public boolean addGoodsListIndex(String keyPrefix, List<Goods> list) {
    int chunk = 200;
    int size = list.size();
    int ceil = (int) Math.ceil(size / (double) chunk);
    // 多线程同步
    List<CompletableFuture<Void>> futures = new ArrayList<>(4);
    for (int i = 0; i < ceil; i++) {int toIndex = (i + 1) * chunk;
        if (toIndex > size) {toIndex = i * chunk + size % chunk;}
        List<Goods> subList = list.subList(i * chunk, toIndex);
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.supplyAsync(() -> subList).thenAccept(goodsList -> {for (Goods goods : goodsList) {Map<String, String> hash = MyBeanUtil.toMap(goods);
                hash.put("_language", Constants.GOODS_IDX_LANGUAGE);
                client.hset(keyPrefix + goods.getGoodsId(), MyBeanUtil.toMap(goods));
            }
        });
        futures.add(voidCompletableFuture);
    }
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    return true;
}
  1. 批改商品页面搜寻接口

    @GetMapping("/search")
    public String rsRearch(SearchObjVO searchObjVO, HttpServletRequest request) {Page<SearchPageGoodsVO> page = getPage(request, Constants.GOODS_SEARCH_PAGE_LIMIT);
     ...
     // RediSearch 中文搜索
     SearchResult query = jedisSearch.search(Constants.GOODS_IDX_NAME, searchObjVO, page);
     ...
     return "mall/search";
    }
  2. 查看搜寻后果中蕴含 ” 小米 ”、” 手机 ” 两个独自分词

四、总结

通过以上实战我的项目,应用 RediSearch 是能够满足根本中文分词需要

高级用法聚合查问、后果高亮、停用词、扩大 API、拼写更正、主动补全等能够在官网理解。
最初贴一下实战我的项目地址 newbeemall,集成 RediSearch,代码开源已上传

正文完
 0