(1) Completed
Redis
installation and use. Complete database insertion, deletion, and query.
Redis
It is a key-value (key-value
) storage system, that is, a key-value pair non-relational database, andMemcached
similar, which is currently being adopted by more and more Internet companies.Redis
As a high-performance key-value database, it not only makes up formemcached
the deficiency of this type of key-value storage to a large extent, but also can play a very good supplementary role to relational databases in some occasions.Redis
ProvidesPython
,Ruby
,Erlang
,PHP
clients, which are very convenient to use.
①Log in ashadoop
a userubuntu kylin
,windows
use the system to save the file transferFileZilla
in compressed format in the directory, and now unzip the package to .redis-5.0.5.tar.gz
“/home/hadoop/下载”
/usr/local
②Decompress
redis-5.0.5.tar.gz
the file and save it to“/usr/local/”
the directory.
③Rename itredis-5.0.5
toredis
, andredis
give the directory permission tohadoop
the user.
④Enter“/usr/local/redis”
the directory, enter compile and installRedis
.
⑤TheRedis
installation has been completed, now startRedis
the server.
⑥Create a new terminal and startRedis
the client. After the client connects to the server,“127.0.0.1:6379>”
the command prompt information will be displayed, indicating thatIP
the address of the server is127.0.0.1
and the port is6379
. Now you can perform simple operations, such as setting the key to”hello”
the value”world”
, and fetching the value corresponding”hello”
to . At this point,Redis
the installation and operation are successful, and then the database can be operatedRedis
.
Redis
The database stores data in the form of . When<key,value>
storing the data in the table into the database, the determination method of the sum is as follows :Redis
key
value
* key=表名:主键值:列名
* value=列值
⑦Insert data: To
Redis
insert a piece of data, you only need to design the sum firstkey
,value
and then useset
the command to insert the data. For example,Course
to insert a new course "Big Data" into the table, 4 credits, the operation commands and results are shown in the figure below.
⑧Delete data:Redis
There is a special command to delete data—del
command, and the command format is "del
key". Therefore, if you want to delete the previously added course "Big Data", you only need to enter the command“del Course:8:Cname”
, as shown in the figure below, when you enter it“del Course:8:Cname”
, it will return“1”
, indicating that a piece of data has been successfully deleted.
⑨Query data:Redis
The easiest way to query is to useget
commands. Enterget
the command query, if the output is empty, it means that the data is deleted successfully.
(2)
MongoDB
Installation and use.Complete
MongoDB
basicshell
commands.MongoDB
It is a database based on distributed file storage, between relational databases and non-relational databases. It is the most functional among non-relational databases and most similar to relational databases. The data structure it supports is very loose and is a similarjson
formatbson
, so it can store more complex data types.Mongo
The biggest feature is that the query language it supports is very powerful, and its syntax is somewhat similar to object-oriented query language, which can almost realize most of the functions similar to single-table query of relational database, and also supports indexing of data.
①Usingapt-get
commands for online installationMongoDB
can avoid many inexplicable problems.
The command linesudo apt-get install mongodb
can be downloaded and installedMongoDB
. The default installed version isMongoDB 2.6.10
, butMongoDB
it has been upgraded to3.2.8
. You can install the version by adding software sources3.2.8
.
a. First open the terminal, import the publickey
to the package manager
b. CreateMongoDB
a list of files.
c. Update the package manager and installMongoDB
.
d.MongoDB
After the installation is complete, enter the following command in the terminal to viewMongoDB
the version.
②MongoDB
start and stop.
③Enter theMongoDB
commandshell
mode. The database connected by default istest
the database. Before that, make sure that it has been startedMongoDB
, otherwise an error will occur. After starting, the successful operation is as follows.
④Common operation commands
Database-related
show dbs
: display database list
show collections
: display collections in the current database (similar to tables in relational databasestable
)
show users
: display all users
use yourDB
: switch current database toyourDB
db.help()
: display database operation commands
db.yourCollection.help()
: display collection operation commands, whichyourCollection
is the collection name
MongoDB
There is no command to create a database. If you want to create a“School”
database, runuse School
the command first, and then do some operations (such as: create a collectiondb.createCollection('teacher')
), so that you can create a“School”
database named .
⑤Taking aSchool
database as an example,School
create two collectionsteacher
and sums in the databasestudent
, andstudent
perform basic operations of addition, deletion, modification and query on the data in the collection (a collectionCollection
is equivalent to a table in a relational databasetable
).
a. Switch toSchool
the database (Switch toSchool
the database.MongoDB
There is no need to pre-createSchool
the database, it will be automatically created when it is used)
b. CreateCollection
(create an aggregate collection.MongoDB
In fact, when inserting data, the corresponding collection will also be automatically created, no pre-defined collection is required )
c. Similar to database creation,MongoDB
collections are automatically created when data is inserted. There are two ways to insert data:insert
andsave
.
Insert data successfully
_id
Same, update data
_id
Same, insert failed, no operation.d. The structure of the added data is loose, as long as
json
the format is acceptable, the column attributes are not fixed, and the added data shall prevail. Define the data first and then insert, you can insert multiple pieces of data at one time.
e. After running the above example,
student
it has been automatically created, indicating thatMongoDB
it does not need to be pre-defined, and it will be automatically createdcollection
after the first data insertion .collection
⑥ Find data
a.db.student.find()
Query all records. Equivalent to:select * from student
b.
db.student.find({sname: 'zhangsan'})
Querysname='zhangsan'
records. Equivalent to:select * from student where sname='zhangsan'
c.
db.student.find({},{sname:1, sage:1})
Query the specified columnsname
andsage
data. Equivalent to:select sname,sage from student
.
sname
:1 means to returnsname
the column, and the default_id
field is also returned. It can be added_id:0
(meaning not to return_id
) to write{sname: 1, sage: 1,_id:0}
, and the default_id
field will not be returned
d.
db.student.find({sname: 'zhangsan', sage: 22})
and
Query with conditions. Equivalent to:select * from student where sname = 'zhangsan' and sage = 22
e.
db.student.find({$or: [{sage: 22}, {sage: 25}]})
or
Conditional query. Equivalent to:select * from student where sage = 22 or sage = 25
f.
db.youCollection.find(criteria, filterDisplay) criteria
:
query condition, optionalfilterDisplay
: filter and display part of the data, such as displaying specified column data, optional (when selected, the first parameter cannot be omitted, if the query condition is empty, it can be used as a placeholder{}
)
⑦ The query conditions
db.youCollection.update(criteria, objNew, upsert, multi )
criteria: update
for , similar to the objects behindsql update
the query : and some update operators (such as ), can also be understood as the following in the query . : If the record does not exist, whether to insert it or not, the default is to not insert it. : By default , only the first record found will be updated. If this parameter is true, all multiple records detected according to the condition will be updated. By default , only the first matching data is modified. Where and are required parameters, and optional parameters. , which is equivalent to: ;where
objNew
update
$set
sql update
set
upsert
update
objNew
true
false
multi
mongodb
false
false
criteria
objNew
upsert
multi
db.student.update({sname: 'lisi'}
{$set: {sage: 30}}, false, true)
update student set sage =30 where sname = 'lisi'
⑧Delete data
db.student.remove({sname: 'chenliu'})
Equivalent to :delete from student where sname='chenliu'
⑨Delete collection
⑩Exit
shell
command mode
Inputexit
orCtrl+C
exitshell
command mode
(3) Use
Java API
the pairMongoDB
to access.①The
Java MongoDB Driver
driverjar
package has been downloaded and saved to’/home/hadoop/下载/’
the directory.
② OpenEclipse
and create a new oneJava Project
.
Import the driver packagemongodb-driver-3.8.0.jar
.
Create newClass Average_grade
ClearAverage_grade.java
the code inside, and then enter the completestudent
code for performing the addition, deletion, modification, and query operations of the collection in this file.
After the program runs,Console
the running result information will be displayed in the " " panel at the bottom.
Each time the program is executed, you can return toshell
the mode to view the results. For example: Aftereclipse
performing the update operation,shell
enter in the modedb.student.find()
, you can viewstudent
all the data of the collection.
(4) How is it different
Redis
from traditionalMysql
databases?①It
mysql
is a relational database, which is mainly used to store persistent data. The data is stored in the hard disk, and the reading speed is relatively slow.redis
YesNOSQL
, that is, a non-relational database is also a cache database, that is, the data is stored in the cache. The cache reads fast and can greatly improve the operating efficiency, but the storage time is limited.
②mysql
As a relational database for persistent storage, the relatively weak point is that every time a request is made to access the database, there areI/O
operations, if the database is accessed repeatedly.
First: A lot of time will be spent on repeatedly connecting to the database, resulting in too slow operation efficiency;
Second: Repeated access to the database will also lead to excessive load on the database, so the concept of caching is derived at this time.
③The cache is the buffer ( ) for data exchangecache
. When the browser executes the request, it will first search in the cache, and if it exists, it will get it; otherwise, it will access the database. The advantage of caching is that the reading speed is fast.
④Theredis
database is a cache database, which is used to store frequently used data, so as to reduce the number of access to the database and improve operating efficiency.(5)
MongoDB
What are the characteristics, andMysql
where is the difference from the database?Features:
Mongodb
It is a non-relational database (nosql
), which belongs to the document database. A document ismongoDB
the basic unit of data in a database. It is similar to a row in a relational database. Multiple key-value pairs are placed together in an orderly manner to form a document. The syntax is somewhat similar to an object-orientedjavascript
query language. It is a set-oriented, free-mode document type database.
Storage method: virtual memory + persistence. Query statement: It is a uniqueMongodb
query method. Suitable scenarios: event recording, content management or blogging platform, etc.
Architecture features: High availability can be achieved through replica sets and fragmentation.
Data processing: The data is stored on the hard disk, but the data that needs to be read frequently will be loaded into the memory, and the data will be stored in the physical memory to achieve high-speed reading and writing.
Maturity and breadth: Emerging databases have low maturity.Nosql
Among the databases, they are closest to relational databases and are relatively completeDB
. The applicable population is constantly growing.Difference:
MongoDB
Another biggest disadvantage is that it takes up a lot of space. When adding,MongoDB
deleting, and modifying data frequently in the database, if the record changes, such as the data size changes, some data fragments are likely to occur at this time, and fragmentation will cause As a result, one is that the index will have performance problems.
MySQL
BothMongoDB
are common open source databases, butMySQL
they are traditional relational databases,MongoDB
while non-relational databases, also called document databases, are a kindNoSQL
of database. They each have their own advantages, the key is to see where they are used.SQL
So the (full name ) statements we are familiar withStructured Query Language
are not applicableMongoDB
, becauseSQL
statements are the standard language of relational databases.