1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| @Autowired StatefulRedisModulesConnection<String, String> connection;
@Autowired RedisTemplate redisTemplate;
@Test public void search() { Set<String> keys = redisTemplate.keys("*"); keys.forEach(item -> { redisTemplate.delete(item); log.info(" keys - > {} ", item); } ); String searchIndexName = "doc-idx"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); RediSearchCommands<String, String> commands = connection.sync(); RedisCommands redisCommands = connection.sync(); List<String> list = commands.list(); for (String s : list) { commands.dropindex(s); } CreateOptions<String, String> options = CreateOptions.<String, String>builder() .on(CreateOptions.DataType.HASH) .languageField(Language.CHINESE.getId()) .prefix(String.format("%s:", DocumentDto.class.getName())) .build(); log.info("{}",gson.toJson(options)); Field title = Field.text("title").build(); Field subtitle = Field.text("subtitle").build(); Field description = Field.text("description").build(); Field author = Field.text("authors").build(); commands.create( searchIndexName, options, title, subtitle, description, author ); String key = String.format("%s:%s", DocumentDto.class.getName(), "1"); Map<String,String> map = new HashMap<>(); map.put("title","标题"); map.put("subtitle","副标题"); map.put("description","描述"); map.put("authors","作者"); Boolean result = redisHash.hMSet(key,map); log.info(" \n key {} \n data {} result {} ", key,gson.toJson(map),result); map = new HashMap<>(); map.put("title","标题1"); map.put("subtitle","副标题2"); map.put("description","描述3"); map.put("authors","作者4"); key = String.format("%s:%s", DocumentDto.class.getName(), "2"); result = redisHash.hMSet(key,map); log.info(" \n key {} \n data {} result {} ", key,gson.toJson(map),result); List<String> fields = new ArrayList<>(); fields.add("title"); fields.add("subtitle"); fields.add("description"); fields.add("authors"); SearchOptions.Summarize summarize = new SearchOptions.Summarize(); summarize.setFields(fields); SearchOptions searchOptions = SearchOptions.builder() .language(Language.CHINESE) .limit(SearchOptions.Limit.of(0,10)) .summarize(summarize) .build(); log.info(" searchOptions {}",gson.toJson(searchOptions)); SearchResults<String, String> results = commands.search(searchIndexName, "标", searchOptions); log.info("{}", gson.toJson(results)); }
|