1. Import the jar package
2. Implement a simple conditional query
Create a User entity class
public class User { private String id; private String name; private String sex; private int age; public String getId() { return id; } public User() { super(); } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String id, String name, String sex, int age) { super(); this.id = id; this.name = name; this.sex = sex; this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; } }
Create 5 objects and store them in the cache for us to test
//连接redis Jedis jedis = new Jedis("127.0.0.1",6379); Map<String, String> map = new HashMap<String,String>(); final String USER_TABLE = "USER_TABLE"; //向缓存中存入5条数据组成的map String uuid1 = UUID.randomUUID().toString(); User user1 = new User(uuid1, "y1", "m", 15); //将对象转为json map.put(uuid1, JSONObject.fromObject(user1).toString()); String uuid2 = UUID.randomUUID().toString(); User user2 = new User(uuid2, "y2", "m", 18); map.put(uuid2, JSONObject.fromObject(user2).toString()); String uuid3 = UUID.randomUUID().toString(); User user3 = new User(uuid3, "y3", "n", 25); map.put(uuid3, JSONObject.fromObject(user3).toString()); String uuid4 = UUID.randomUUID().toString(); User user4 = new User(uuid4, "y4", "n", 15); map.put(uuid4, JSONObject.fromObject(user4).toString()); String uuid5 = UUID.randomUUID().toString(); User user5 = new User(uuid5, "y5", "m", 25); map.put(uuid5, JSONObject.fromObject(user5).toString()); //把map存到缓存中 jedis.hmset("USER_TABLE", map);
Query in redis, you can see that 5 user objects have been stored in the cache
Next, first implement a single-condition query, for example, query a user with an age of 15 and a user with a gender of m
Since Redis is nosql, it cannot be directly Like mysql, where is used to perform conditional queries, so if Redis wants to implement conditional queries, it can only use a stupid method: save all users who meet the conditions into a set.
Jedis jedis = new Jedis("127.0.0.1",6379); Map<String, String> map = new HashMap<String,String>(); final String USER_TABLE = "USER_TABLE"; //查询年龄为15,性别为n final String USER_TABLE_AGE_15 = "USER_TABLE_AGE_15"; final String USER_TABLE_SEX_m = "USER_TABLE_SEX_m"; final String USER_TABLE_SEX_n = "USER_TABLE_SEX_n"; //向缓存中存入5条数据组成的map String uuid1 = UUID.randomUUID().toString(); User user1 = new User(uuid1, "y1", "m", 15); //将对象转为json map.put(uuid1, JSONObject.fromObject(user1).toString()); //将符合条件的user的Id存到set中 jedis.sadd(USER_TABLE_AGE_15,uuid1); jedis.sadd(USER_TABLE_SEX_m,uuid1); String uuid2 = UUID.randomUUID().toString(); User user2 = new User(uuid2, "y2", "m", 18); map.put(uuid2, JSONObject.fromObject(user2).toString()); jedis.sadd(USER_TABLE_SEX_m,uuid2); String uuid3 = UUID.randomUUID().toString(); User user3 = new User(uuid3, "y3", "n", 25); map.put(uuid3, JSONObject.fromObject(user3).toString()); String uuid4 = UUID.randomUUID().toString(); User user4 = new User(uuid4, "y4", "n", 15); map.put(uuid4, JSONObject.fromObject(user4).toString()); jedis.sadd(USER_TABLE_AGE_15,uuid4); String uuid5 = UUID.randomUUID().toString(); User user5 = new User(uuid5, "y5", "m", 25); map.put(uuid5, JSONObject.fromObject(user5).toString()); jedis.sadd(USER_TABLE_SEX_m,uuid5); //把map存到缓存中 jedis.hmset("USER_TABLE", map);
So, if you want to query the user whose age is 15, you need to first remove all uuid from USER_TABLE_AGE_15, and then remove the user from USER_TABLE
//获取年龄为15的user的uuid Set<String> age = jedis.smembers(USER_TABLE_AGE_15); //根据uuid获取user List<User> userJson = new ArrayList<User>(); for (Iterator iterator = age.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); String jsonStr = jedis.hget(USER_TABLE, string); JSONObject json = JSONObject.fromObject(jsonStr); User user = (User) JSONObject.toBean(json, User.class); userJson.add(user); System.out.println(user); }
The results are as follows:
User [id=63a970ec-e997-43e0-8ed9-14c5eb87de8b, name=y1, sex=m, age=15] User [id=aa074a2a-88d9-4b50-a99f-1375539164f7, name=y4, sex=n, age=15]
So if you need a user with age 15 and gender m, it is very simple. Get the union of
USER_TABLE_AGE_15 and USER_TABLE_SEX_m, and then get it from USER_TABLE.
//获取年龄为15并性别为m的user Set<String> userSet = jedis.sinter(USER_TABLE_AGE_15,USER_TABLE_SEX_m); List<User> users = new ArrayList<User>(); for (Iterator iterator = userSet.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); String jsonStr = jedis.hget(USER_TABLE, string); JSONObject json = JSONObject.fromObject(jsonStr); User user = (User) JSONObject.toBean(json, User.class); users.add(user); System.out.println(user); }
User [id=63a970ec-e997-43e0-8ed9-14c5eb87de8b, name=y1, sex=m, age=15]
For more redis knowledge, please pay attention to the redis introductory tutorial column.
The above is the detailed content of redis implements simple conditional query. For more information, please follow other related articles on the PHP Chinese website!

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment