当前位置:网站首页>Installation and use of NoSQL database
Installation and use of NoSQL database
2022-07-01 09:11:00 【Half haochunshui】
( One ) complete
RedisInstallation and use . Complete database insertion , Delete , And inquiry .
RedisIt's a key value (key-value) The storage system , That is, key value pair non relational database , andMemcachedsimilar , At present, it is being adopted by more and more Internet companies .RedisAs a high-performance key value database , It not only makes up formemcachedThis kind of key value storage is insufficient , And in some cases, it can play a good complementary role to the relational database .RedisProvidesPython、Ruby、Erlang、PHPclient , Easy to use .
① UsehadoopThe user loginubuntu kylin, staywindowsSystem useFileZillaFiles in compressed formatredis-5.0.5.tar.gzTransfer saved in“/home/hadoop/ download ”Under the table of contents , Now unzip the package to the path/usr/localNext .
② take
redis-5.0.5.tar.gzUnzip the file and save it to“/usr/local/”Under the table of contents .
③ takeredis-5.0.5Rename it toredis, And putredisThe permission of the directory is given tohadoopuser .
④ Get into“/usr/local/redis”Catalog , Input compilation and installationRedis.
⑤ Already completedRedisInstallation , Now onRedisThe server .
⑥ New terminal , start-upRedisclient . After the client connects to the server , Will be displayed“127.0.0.1:6379>”Command prompt information for , Represents the... Of the serverIPThe address is127.0.0.1, Port is6379. Now you can perform simple operations , such as , Set the key to”hello”, The value is”world”, And take out the key as”hello”The corresponding value of . thusRedisInstallation and operation succeeded , Then you can operateRedisdatabase .RedisThe database is based on<key,value>In the form of data storage , Save the data of the tableRedisDatabase time ,keyandvalueThe determination method of is as follows :
* key= Table name : Primary key value : Name
* value= The column value
⑦ insert data : towards
RedisInsert a piece of data , Just design it firstkeyandvalue, And then usesetCommand to insert data . for example , stayCourseInsert a new course into the table “ big data ”,4 credits , The operation commands and results are shown in the following figure .
⑧ Delete data :RedisThere are special commands to delete data ——delcommand , The command format is “delkey ”. therefore , If you want to delete a previously added course “ big data ”, Just enter the command“del Course:8:Cname”, As shown in the figure below , When the input“del Course:8:Cname”when , return“1”, Description: a piece of data has been successfully deleted .
⑨ Query data :RedisThe simplest way to query is to usegetcommand . InputgetCommand query , Output is empty , This indicates that the data was deleted successfully .( Two )
MongoDBInstallation and use .complete
MongoDBThe basicshellcommand .MongoDBIs a database based on distributed file storage , Between relational and non relational databases , Non-relational databases are the most versatile , Most like a relational database . The data structure it supports is very loose , Is similar tojsonOfbsonFormat , Therefore, more complex data types can be stored .MongoThe biggest feature is that the query language he supports is very powerful , Its syntax is somewhat similar to that of an object-oriented query language , You can almost implement most of the functionality of a relational database single table query , It also supports indexing data .
① Useapt-getCommand to install onlineMongoDB, It can avoid many inexplicable problems .
Command linesudo apt-get install mongodbDownloadable installationMongoDB, The default installed version isMongoDB 2.6.10, But at the moment,MongoDBHas been upgraded to3.2.8, You can install by adding software sources3.2.8edition .
a. First open the terminal , Import publickeyTo package manager
b. establishMongoDBList of files .
c. Update package manager , installMongoDB.
d. installation is completeMongoDBin the future , Enter the following command at the terminal to viewMongoDBedition .
②MongoDBStart up and shut down .
③ Get intoMongoDBOfshellCommand mode . The default database to connect to istestdatabase , Before that, be sure to startMongoDB, Otherwise, an error will occur , The successful operation after startup is as follows .
④ Common operation command
Database correlationshow dbs: Show database listshow collections: Displays the collection in the current database ( Similar to tables in relational databasestable)show users: Show all usersuse yourDB: Switch the current database toyourDBdb.help(): Display the database operation commanddb.yourCollection.help(): Show set operation commands ,yourCollectionIs the collection name
MongoDBThere is no command to create a database , If you want to create a“School”The database of , First runuse Schoolcommand , Then do some operations ( Such as : Create aggregation setsdb.createCollection('teacher')), So you can create one called“School”The database of .
⑤ With aSchoolDatabase, for example , staySchoolCreate two sets in the databaseteacherandstudent, Also onstudentThe basic operations of adding, deleting, modifying and querying the data in the collection ( aggregateCollectionEquivalent to tables in a relational databasetable).
a. Switch toSchooldatabase ( Switch toSchooldatabase .MongoDBNo pre creation requiredSchooldatabase , It will be automatically created when used )
b. establishCollection( Create an aggregate set .MongoDBIn fact, when inserting data , The corresponding set will also be automatically created , There is no need to predefine the set )
c. Similar to database creation ,MongoDBThe collection will also be automatically created when inserting data . There are two ways to insert data :insertandsave.
Insert data succeeded
_ididentical , Update data
_ididentical , Insert the failure , No operation .d. The structure of the added data is loose , As long as it is
jsonThe format can be , Column properties are not fixed , According to the added data . Define the data before inserting , You can insert multiple pieces of data at once .e. Run the above example ,
studentAutomatically created , explainMongoDBThere's no need to predefinecollection, After first inserting data ,collectionWill automatically create .⑥ Find data
a.db.student.find()Check all records . amount to :select * from studentb.
db.student.find({sname: 'zhangsan'})Inquire aboutsname='zhangsan'The record of . amount to :select * from student where sname='zhangsan'c.
db.student.find({},{sname:1, sage:1})Query specified columnsname、sagedata . amount to :select sname,sage from student.sname:1 Said to return tosnameColumn , Default_idFields are also returned , You can add_id:0( Do not return_id) It's written in{sname: 1, sage: 1,_id:0}, Will not return to the default_idFieldd.
db.student.find({sname: 'zhangsan', sage: 22})andAnd conditional query . amount to :select * from student where sname = 'zhangsan' and sage = 22e.
db.student.find({$or: [{sage: 22}, {sage: 25}]})orConditions of the query . amount to :select * from student where sage = 22 or sage = 25f.
db.youCollection.find(criteria, filterDisplay) criteria:
Query criteria , OptionalfilterDisplay: Filter and display some data , If the specified column data is displayed , Optional ( When choosing , The first parameter cannot be omitted , If the query condition is empty , You can use{}Do a placeholder )⑦ Modifying data
db.youCollection.update(criteria, objNew, upsert, multi )criteria: updateQuery criteria for , similarsql updateIn the querywherehinderobjNew:updateObject and some updated operators ( Such as$set) etc. , It can also be understood assql updateIn the querysethinder .upsert: If it doesn't existupdateThe record of , Whether insertobjNew,trueInsert for , The default isfalse, Do not insert .multi:mongodbThe default isfalse, Update only the first record found , If this parameter is zero true, According to the conditions to find out all the records updated . Defaultfalse, Only the first matched data is modified .
amongcriteriaandobjNewIs a required parameter ,upsertandmultiOptional parameters .db.student.update({sname: 'lisi'},{$set: {sage: 30}}, false, true)
amount to :update student set sage =30 where sname = 'lisi';⑧ Delete data
db.student.remove({sname: 'chenliu'})amount to :delete from student where sname='chenliu'⑨ Delete the collection
⑩ sign out
shellCommand mode
InputexitperhapsCtrl+Csign outshellCommand mode( 3、 ... and ) Use
Java APIYesMongoDBVisit .①
Java MongoDB DriverdrivejarThe package has been saved to’/home/hadoop/ download /’Under the table of contents .
② openEclipse, newly buildJava Project.
Introduce driver packagemongodb-driver-3.8.0.jar.
newly buildClass Average_grade
EmptyAverage_grade.javaCode inside , Then enter the complete execution set in this filestudentCode for adding, deleting, modifying, and querying .
After the program is run, it will be in the bottom “Console” The operation result information is displayed in the panel .
Each time the program is executed , You can go back toshellMode view results . Such as : stayeclipseAfter performing the update operation , stayshellMode inputdb.student.find(), You can seestudentAll the data of the collection .( Four )
RedisAnd traditionalMysqlWhat is the difference between databases ?①
mysqlIs a relational database , It is mainly used to store persistent data , Store data on a hard disk , Slow read speed .redisyesNOSQL, This is a non relational database , It is also a cache database , Store data in cache , Cache read speed is fast , Can greatly improve the operation efficiency , But the storage time is limited .
②mysqlRelational databases as persistent storage , The relative weakness is that every time you request access to the database , They all existI/Ooperation , If the database is accessed repeatedly and frequently .
First of all : You spend a lot of time chaining databases , As a result, the operating efficiency is too slow ;
second : Repeated database access can also lead to overloading of the database , Then the concept of caching is derived .
③ A cache is a buffer for data exchange (cache), When the browser executes the request , First of all, search in the cache , If there is , Just get ; Otherwise, access the database . The advantage of caching is fast reading speed .
④redisDatabase is a cache database , Used to store frequently used data , This reduces the number of times you access the database , Improve operational efficiency .( 5、 ... and )
MongoDBWhat are the characteristics of , andMysqlWhat is the difference between databases ?characteristic :
MongodbIt's a non relational database (nosql), It's a document database . The document ismongoDBThe basic unit of data in , Like rows in a relational database , Multiple key value pairs placed together in an orderly manner is the document , The grammar is a little bit similarjavascriptObject oriented query language , It's a set oriented , Schema free document database .
storage : Virtual memory + Persistence . Query statement : It's uniqueMongodbQuery mode of . Suitable for the scene : A record of the incident , Content management or blog platform, etc .
Architectural features : Through the replica set , And sharding to achieve high availability .
Data processing : The data is stored on the hard disk , Just the data that needs to be read frequently will be loaded into memory , Store data in physical memory , So as to achieve high-speed reading and writing .
Maturity and breadth : Emerging databases , Less mature ,NosqlDatabase is closest to relational database , More perfectDBOne of , The applicable population is growing .difference :
MongoDBThere's also one big drawback , It takes up a lot of space , stayMongoDBWhen data is added, deleted, or modified frequently , If the record changes , For example, the data size has changed , At this time, it is easy to generate some data fragments , The result of fragmentation , One is that indexes have performance problems .MySQLAndMongoDBThey are all open source common databases , howeverMySQLIt's a traditional relational database ,MongoDBIt's a non relational database , It's also called document database , It's a kind ofNoSQLThe database of . They have their own advantages , The key is to see where it's used . So those we know wellSQL( Full nameStructured Query Language) The statement does not apply toMongoDB了 , becauseSQLStatement is the standard language for relational databases .
边栏推荐
- 【ESP 保姆级教程 预告】疯狂Node.js服务器篇 ——案例:ESP8266 + DHT11 +NodeJs本地服务+ MySQL数据库
- Shell脚本-for循环和for int循环
- Vsync+ triple cache mechanism +choreographer
- Class loading
- [interview brush 101] linked list
- nacos简易实现负载均衡
- Imitation of Baidu search results top navigation bar effect
- 3D打印Arduino 四轴飞行器
- 2.3 【pytorch】数据预处理 torchvision.datasets.ImageFolder
- An overview of the design of royalties and service fees of mainstream NFT market platforms
猜你喜欢
随机推荐
Ape anthropology topic 20 (the topic will be updated from time to time)
【pytorch】nn. AdaptiveMaxPool2d
Personal decoration notes
JCL 和 SLF4J
pcl_viewer命令
pcl_ Viewer command
R language observation log (part24) -- initialization settings
Win7 pyinstaller reports an error DLL load failed while importing after packaging exe_ Socket: parameter error
Shell script echo command escape character
Summary of reptile knowledge points
An overview of the design of royalties and service fees of mainstream NFT market platforms
FreeRTOS learning easy notes
3D printing Arduino four axis aircraft
如何解决固定资产管理和盘点的难题?
Performance improvement 2-3 times! The second generation Kunlun core server of Baidu AI Cloud was launched
It technology ebook collection
Embedded Engineer Interview Question 3 Hardware
Shell script case in and regular expressions
Promise异步编程
Redis source code learning (29), compressed list learning, ziplist C (II)





















































![2.3 [pytorch] data preprocessing torchvision datasets. ImageFolder](/img/19/cce8d8a7cdcb1021166c46adf803c1.png)