Redis (Jedis)-related APIs for similar functionality to relational databases

Source: Internet
Author: User

This paper briefly describes some of the problems that are summarized in the process of using Jedis to operate the NoSQL database, such as the processing of data association relationships using Jedis to implement a form-relational database.

Divided into three levels:

1: Single-table data processing, adding a row to the database, if there is a primary key ID is the self-increment condition, how to add data collection to the database row data;

2: A one-to-many relationship, this article is an example of---students && scores; A student contains scores from multiple disciplines, and the achievement of a particular subject belongs to a student;

3: Many-to-many correlation, this article for example---articles && tags; an article can add multiple tags, a tag can be included in multiple articles;

The whole code link has been uploaded to git and can be viewed on git:

http://git.oschina.net/alexgaoyh/MutiModule-parent/blob/master/MutiModule-service/src/test/java/com/alexgaoyh/ Mutimodule/service/unjunit/redis/test2/testcase.java

1: Single-table data processing

/** * [Pressing the Redis list to the ID instead of the actual data] in the above example, we Press "Object" (in this case, a simple message) directly into the Redis list, but this is not usually done because the object may be referenced more than once: for example, to maintain its chronological order in a list, Saves its category in a collection and, if necessary, it appears in other lists, and so on. Let's go back to Reddit.com's example, adding a user-submitted link (news) to the list, with a more reliable approach like this: $ redis-cli incr next.news.id (integer) 1$ redis-cli set news:1: Title "Redis is simple" ok$ redis-cli set News:1:url "Http://code.google.com/p/redis" ok$ redis-cli lpush submitted.news 1O K We add a key, it's easy to get a unique self-increment ID, and then create an object from this ID – set a key for each field of the object. Finally, the ID of the new object is pressed into the Submitted.news list. It's just kind. All commands related to list can be read in the command Reference document. You can delete the elements, rotate the list, get and set the elements according to the index, and, of course, use Llen to get the list length. * * Shape as a relational database single table row of data (primary key ID is self-increment) * Customize an auto-increment ID, JEDIS.INCR (key), this key can be shaped like MySQL this relational database's self-increment primary key ID * shape, such as a relational database row of data, Self-increment primary key ID:JEDIS.INCR (key) his corresponding data content: Jedis.get ("Ad:adinfo:" + adinfoid + ": Title") Jedis.get ("Ad:adinfo:" + adinfoid + ": url" * In this way, when querying all the data under this ' table ' structure, you can match the query to */public static void Testliststrusage () {String title = "Alexgaoyh"; String url = "Http://git.oschina.net/alexgaoyh"; Jedis Jedis = Redisutil.getjedis (IP, PORT); Long adinfoid = JEDIS.INCR ("Ad:Adinfo:next.id "); Jedis.set (" Ad:adinfo: "+ adinfoid +": title ", title); Jedis.set (" Ad:adinfo: "+ adinfoid +": url ", URL); Jedis.lpush ("Ad:adinfo", String.valueof (adinfoid)); String resulttitle = Jedis.get ("ad:adinfo:" + adinfoid + ": title"); String Resulturl = Jedis.get ("ad:adinfo:" + adinfoid + ": url"); list<string> ids = Jedis.lrange ("Ad:adinfo", 0,-1); System.out.println (Resulttitle); System.out.println (Resulturl); System.out.println (IDs);/** * Dbsize Returns the number of all keys, including those that have expired, while the REDIS-CLI keys "*" Query results in a valid key number */system.out.println ( Jedis.dbsize ());//Clear All Keyjedis.flushall ();}




2: One-to-many correlation relationship

/** * Sort list * List combined hash sort * Returns the qualifying data format according to the specified sortingparams sort * associative relationship processing, * can be understood as studentlist represents the student's overall data set * Hset method, can be To save the results of a field (subject) under a student's User:id (value) * The corresponding score is output based on the matching criteria */public static void TestSort2 () {Jedis Jedis = Redisutil.getjedis (IP, PORT), Jedis.del ("user:66", "user:55", "user:33", "user:22", "User:11", "userlist"); Jedis.lpush ("Studentlist", "a"), Jedis.lpush ("Studentlist", "a"), Jedis.lpush ("Studentlist", "in"), Jedis.lpush (" Studentlist "," 11 ");//Set the value of the field field in the hash table key to value. If the key does not exist, a new hash table is created and the Hset operation is performed. If the field field already exists in the hash table, the old value will be overwritten. Jedis.hset ("user:66", "math", "33"), Jedis.hset ("user:55", "math", "a"), Jedis.hset ("user:33", "math", "+"); Jedis.hset ("user:22", "math", "a"), Jedis.hset ("User:11", "math", "11");//Student User: Number, score in field field (a discipline-math/English) (value) Jedis.hset ("User:11", "Chinese", "a"), Jedis.hset ("user:22", "English", "the"), Jedis.hset ("user:33", "中文版", " "Jedis.hset" ("User:55", "English", "550"), Jedis.hset ("user:66", "中文版", "660"); Sortingparams sOrtingparameters = new Sortingparams ();//symbol "-" is used to split the hash table key name (key name) and the Index field (hash field) in the format "Key->field". Sortingparameters.desc (); Sortingparameters.get ("User:*->math"); Sortingparameters.get ("User:*->english"); list<string> result = Jedis.sort ("Studentlist", sortingparameters); for (String Item:result) {System.out.println ("Item ...." + Item);} /** * The corresponding Redis client command is: Sort ml get user*->name sort ml get user:*->name get * user:*->add */}

/** * Sort set * Set combined with string sort * rel relationship related processing action buddy list friend info friend score Data Information add that data output * Output friend ID, friend's details,              Friend's corresponding score */public static void TestSort3 () {Jedis Jedis = redisutil. Getjedis (IP, PORT); Jedis.del ("Tom:friend:list", "score:uid:123", "score:uid:456", "score:uid:789", "              Score:uid:101 "," uid:123 "," uid:456 "," uid:789 "," uid:101 "); Jedis.sadd ("Tom:friend:list", "123");              Tom's buddy list Jedis.sadd ("Tom:friend:list", "456");              Jedis.sadd ("Tom:friend:list", "789");              Jedis.sadd ("Tom:friend:list", "101"); Jedis.set ("score:uid:123", "1000");              Friends corresponding to the score Jedis.set ("score:uid:456", "6000");              Jedis.set ("score:uid:789", "100");              Jedis.set ("score:uid:101", "5999"); Jedis.set ("uid:123", "{' UID ': 123, ' name ': ' Lucy '}"); Friends ' Details Jedis. Set ("uid:456", "{' uid ': 456, ' name ': ' Jack '}");              Jedis.set ("uid:789", "{' uid ': 789, ' name ': ' Jay '}");              Jedis.set ("uid:101", "{' UID ': 101, ' name ': ' Jolin '}");              Sortingparams sortingparameters = new Sortingparams ();               Sortingparameters.desc ();               Sortingparameters.limit (0, 2);              Note that get operations are ordered, get user_name_* get user_password_*//And get user_password_* get user_name_* return results in different locations                                                               Sortingparameters.get ("#");//Get has a special rule--"Get #"              To get the current element of the sorted object (tom:friend:list) (our example here is user_id).              Sortingparameters.get ("uid:*");              Sortingparameters.get ("score:uid:*");               Sortingparameters.by ("score:uid:*");              The corresponding Redis command is./redis-cli sort tom:friend:list by score:uid:* get # Get//UID:* get score:uid:* list<string> result = Jedis.sort ("Tom:friend:List ", sortingparameters);              for (String item:result) {System. println ("Item ..." + Item); }       }



One needs to pay attention to Sortingparameters.get ("#");

Get also has a special rule--"Get #" is used to get the current element of the sorted object (tom:friend:list) (our example here is user_id).



3: Many-to-many association relationships

/** * The following is a simple scenario: for each object that you want to tag, associate it with a set of tag IDs, and associate a set of object IDs with each existing tag. For example, suppose our news ID * 1000 was added with three tags tag 1,2,5 and 77, you can set the following two collections: * $ redis-cli sadd news:1000:tags 1 * (integer) 1 * $ redis-cli Sadd News:1000:tags 2 * (integer) 1 * $ redis-cli sadd news:1000:tags 5 * (integer) 1 * $ redis-cli sadd news:1000:tags 77  * (integer) 1 * $ redis-cli sadd tag:1:objects * (integer) 1 * $ redis-cli sadd tag:2:objects $ * (integer) 1 * $ redis-cli sadd tag:5:objects (integer) 1 * $ redis-cli sadd tag:77:objects $ * (integer) 1 * To get all the labels for an object , so simple: * $ redis-cli smembers news:1000:tags * 1.52.13.774.2 * While some seemingly not simple operations can still be easily implemented using the appropriate REDIS commands. * For example, we might want to get a list of objects that have tags 1, 2,10 and 27 at the same time. This can be done with the sinter command, where he can take out the intersection between different sets.  * So for the purpose we just need: $ redis-cli sinter tag:1:objects tag:2:objects tag:10:objects tag:27:objects ... no result * in US dataset Composed of just one object ... * Other commands related to collections can be found in the command reference document, with an interesting grasp of a lot. Be sure to pay attention to the sort command, where Redis collections and lists are sortable. * * Relational Database Bidirectional Association operation an article corresponds to multiple tags, and a label can be associated with multiple articles * Many-to-many database tables*/public static void Testsetusage () {Jedis Jedis = Redisutil.getjedis (IP, PORT);//An article contains a label jedis.sadd ("Zhongsou:news : 1000:tags "," 1 "), Jedis.sadd (" Zhongsou:news:1000:tags "," 2 "), Jedis.sadd (" Zhongsou:news:1000:tags "," 5 "); Jedis.sadd ("Zhongsou:news:1000:tags", "Zhongsou:news:2000:tags", "1"), Jedis.sadd ("Zhongsou:news", "Jedis.sadd"); : 2000:tags "," 2 "), Jedis.sadd (" Zhongsou:news:2000:tags "," 5 "), Jedis.sadd (" Zhongsou:news:2000:tags "," 77 "); Jedis.sadd ("Zhongsou:news:3000:tags", "2"), Jedis.sadd ("Zhongsou:news:4000:tags", "a") Jedis.sadd ("Zhongsou:news : 5000:tags "," 1 "); Jedis.sadd (" Zhongsou:news:6000:tags "," 5 ");//A label contains the corresponding article Idjedis.sadd (" Zhongsou:tag:1:objects " , + + ""), Jedis.sadd ("zhongsou:tag:2:objects", + + "), Jedis.sadd (" zhongsou:tag:5:objects ", + +"); Jedis.sadd ("Zhongsou:tag:77:objects", "+ +"), Jedis.sadd ("Zhongsou:tag:1:objects", "+"); Jedis.sadd ("Zhongsou:tag:2:o Bjects "," + ""), Jedis.sadd ("Zhongsou:tag:5:objects", "+"); Jedis.sadd ("Zhongsou:tag:77:objects", 2000 +" ");//Returns all members of a collection, which is the intersection of all given collections//four tags are all included in the collection of article IDs set<string> sets = Jedis.sinter (" Zhongsou:tag:1:o Bjects "," zhongsou:tag:2:objects "," zhongsou:tag:5:objects "," zhongsou:tag:77:objects "); SYSTEM.OUT.PRINTLN (sets); Jedis.flushall ();}



Redis (Jedis)-related APIs for similar functionality to relational databases

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.