当前位置:网站首页>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 .
边栏推荐
- What are the differences between the architecture a, R and m of arm V7, and in which fields are they applied?
- Shell脚本-字符串
- Shell脚本-case in 和正则表达式
- Win7 pyinstaller reports an error DLL load failed while importing after packaging exe_ Socket: parameter error
- [ESP nanny level tutorial] crazy completion chapter - Case: ws2812 light control system based on Alibaba cloud, applet and Arduino
- Shell script - string
- How to manage fixed assets well? Easy to point and move to provide intelligent solutions
- 【pytorch】nn.CrossEntropyLoss() 与 nn.NLLLoss()
- Common interview questions for embedded engineers 2-mcu_ STM32
- Naoqi robot summary 28
猜你喜欢

Nacos - Configuration Management

Jetson Nano 安装TensorFlow GPU及问题解决

Ranking list of domestic databases in February, 2022: oceanbase regained the "three consecutive increases", and gaussdb is expected to achieve the largest increase this month

Ape anthropology topic 20 (the topic will be updated from time to time)

3. Detailed explanation of Modbus communication protocol

Mise en œuvre simple de l'équilibrage de la charge par nacos

nacos簡易實現負載均衡

Microcomputer principle - bus and its formation

FreeRTOS learning easy notes
![[interview brush 101] linked list](/img/52/d159bc66c0dbc44c1282a96cf6b2fd.png)
[interview brush 101] linked list
随机推荐
Shell脚本-case in语句
【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于阿里云、小程序、Arduino的WS2812灯控系统
[pytorch] softmax function
Which method is good for the management of fixed assets of small and medium-sized enterprises?
Jetson Nano 安装TensorFlow GPU及问题解决
MySQL optimization
Nacos - 配置管理
Nacos - service discovery
Log4j 日志框架
【pytorch】transforms. Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
如何解决固定资产管理和盘点的难题?
[video game training] real topic of 2013 video game of infrared optical communication device
【pytorch】nn.CrossEntropyLoss() 与 nn.NLLLoss()
Embedded Engineer Interview frequently asked questions
Performance improvement 2-3 times! The second generation Kunlun core server of Baidu AI Cloud was launched
Leetcode daily question brushing record --540 A single element in an ordered array
Shell script - special variables: shell $, $*, [email protected], $$$
[ESP nanny level tutorial preview] crazy node JS server - Case: esp8266 + DHT11 +nodejs local service + MySQL database
如何一站式高效管理固定资产?
Pain points and solutions of fixed assets management of group companies











































