r/AskComputerScience • u/[deleted] • Aug 24 '20
I just don't get NoSQL databases
Perhaps it's just because of my years of working with relational databases, but for the life of me I can't figure out how a non-relational database works. I've read a number of tutorials and whatnot, and I understand that they are supposed to be faster and more suited for certain use-cases, but I can't really see how.
The Amazon Dynamo DB tutorial, for example, is a movie database. If I wanted to store a cast list for a movie, I see no other way than an array of strings for each cast member. But then if I wanted all the movies an actor was in, I'd have to either do what I suspect is some very slow iteration through all the movies' actors, or store that information in the actor table. But now my data is doubled up and I can't see how that wouldn't create problems.
You might point out that I've tried to use a non-relational database to store a relation, but I can't imagine a database where some sort of relation isn't necessary. Take Amazon, for example. There's a million relationships they must be tracking--purchase to user, review to purchase, item to manufacturer, whatever.
Any insight would be appreciated!
35
u/anamorphism Aug 24 '20 edited Aug 24 '20
document based databases are really much faster at looking up individual records than relational databases. so, the primary use cases are things like caches (you're just storing blobs of data by a hash) and if your db ever gets large enough to where you're having trouble scaling your server(s) up (these no-sql dbs tend to be much better at scaling horizontally because they're not designed to store relations between multiple types of data).
the second case is what kind of triggered the craze. facebook switched to using a document based no-sql database to load friends data, if i remember correctly. the data is relational, but they traded duplication of data for lookup speed. they really just needed a key subset of user data in order to populate your friends list, but using a traditional relational database, joining on their 2 billion row user table wasn't very practical. so, they basically store a document for your profile or whatever with the relevant user data duplicated in it. they can shard that data however they want into multiple db instances and just route your request to the correct one and essentially get instant lookups of the data they need to display your profile to you.
however, most dbs will never get to the point where you need to do this type of thing. tons of people switched to using something like mongo because they thought it was the thing to do and ended up biting themselves in the ass because they were still trying to use it like a relational database. they would've probably saved themselves a lot of trouble if they just spun up a postgresql instance or whatever that would easily handle the load and amount of data they had.
edit: there are also things like Hadoop (big table databases) which are designed to just accept as many writes of data as possible. rebuilding indexes and such can be problematic to performance if you're trying to write billions of rows of data per minute. querying these tend to be a bit slower though, so most of the time you'll just write operations to aggregate data sufficiently enough to where you can shove it into a more standard relational database to actually work with the data.
9
Aug 24 '20 edited Aug 24 '20
I’ve gone through this same struggle and perhaps I still don’t really grasp it so maybe someone will tell me that I’m completely wrong, BUT...
You have to let go of the idea of comparing them and trying to compare use cases for them because they are basically meant for completely different purposes. I would say to think of SQL as a very detailed set of spreadsheets, but think of NoSQL as a filing cabinet with a set of documents. Both are useful, but have shortcomings.
I feel the best way is to give some examples of where the use cases would distinguish which the (SQL vs NoSQL).
Example #1: Customer Database that requires VERY reliable data such as Address, Phone #, Email, etc. The less reliable the data is, the more time and money wasted mailing resources, making phone calls and emailing. This database may have a lot of relations involved such as purchase history, items returned, ad profile to personalize sales screens, etc. A lot of data that needs to be cross referenced basically.
SQL would do good in making sure those relations are always STRICTLY in place and that orders don’t somehow get tied to a different or nonexistent customer and that orders aren’t duplicated. This is a VERY good use case for SQL or relational databases to be more specific.
NoSQL on the other hand, could still be used in this case. It would be able to keep one document or one set of documents relating to a specific customer. You could pull up the specific sections of those documents that you needed. The only thing is that there are no relations. At least not in a strict sense, you could have 2 filing cabinets, one with customers, one with orders, and tie IDs to each other, but you would have to put some safeguards in place (programmatically) to ensure that that data is reliable and incorruptible.
Example #2: A Movie Database (as you mentioned). You have a list of movies with some details, a list of actors with their details and maybe some other data.
NoSQL would do really well in this case because in most cases you’re looking up a specific item. Let’s say you’re pulling up a movie and you want a list of the actors in it. You query the Movie’s document and get a list of all its details including a list of it’s actors. You’re really not concerned about data reliability because at worst you’ll annoy someone by having an inaccurate name and actors names don’t change on a daily basis, nor do the actors in a released movie.
SQL (or relational) on the other hand would have to query a separate table for the movie, the list of actors, and any other data necessary. Maybe a movie database isn’t a good example of where relational databases could slow things down. Let’s try a different example.
Example #3: A social media platform that stores users, user’s posts, users interests, ad data, user interactions, messages, comments, likes, dislikes, pictures, videos, etc.
SQL would have to do loads of work to handle this, let’s say someone wants to see a picture that has 1000 likes, 300 comments and likes for those comments. In a properly normalized SQL database, the server would need to query first the post with the picture, then query a separate table for all 1000 users who liked, then query a separate table for all 300 comments as well as a separate table for all user data for those comments as well as a separate table for any individual likes on those comments and it goes on and on. Now imagine that with 1000000 likes or multiple pictures in a collage like some social networks allow today. That would take ages even with paging and would be a nightmare for any network with a lot of users (>10000, maybe less).
NoSQL on the other hand, would pull up one post and have all the likes, comments, etc. stored in one document that is meant solely for that post. Sure some data might be pulled or cross referenced from elsewhere and I’m over simplifying it, but in a properly developed NoSQL environment, that would be a very simple query.
My point is, you can’t look at them like they serve the same purpose. Yes, they are both meant to store data and allow it to be queried in an efficient way, but neither are a catch all solution for all use cases.
SQL is meant for strict data reliability while still offering a lot of efficiency. (There are lots of ways to make this efficient including normalization and load balancing).
NoSQL is NON-relational, it is meant for efficiency and big data. It is not meant to be used for reliability of data. There are ways to make it reliable programmatically. It’s non-relational in nature, but that doesn’t mean you can’t form your own relations.
5
Aug 24 '20
There is a certain amount of “letting go” required to think about non relational DBs if you are used to working with them. Especially if you use SQL as the predominant language to interact with data.
I have worked in traditional data warehousing, as a data engineer on big data and also as a full stack web developer. It took me a while to get my head around document databases after so much time around relational DBs.
I think the best way to think about it is to completely drop the concept of normalization for document stores - data is duplicated, repeated and nested in objects instead of being normalized into tables as per a relational DB.
On a lot of modern web apps JSON is written directly to a document DB such as Dynamo in basically more or less the shape the API and UI parts talk to one another - this eases development and removes the need for things like ORMs.
On the back end, application Data is transformed through pipelines to meet the use cases for other parts of the business or application - into relational DBs in some cases for say a report, or for consumption to machine learning models, or countless other ways.
Data is data, the format it is in could be abstracted into tables referenced to one another by foreign keys, or into repeated similar map or struct type shapes in a document DB.
Then there’s a whole world of hybrid and specialised DBMSes such as graph DBs.. The hole goes very deep
12
u/emasculine Aug 24 '20
i don't either. they scream "SHINY" for the vast majority of use cases.
2
u/HasFiveVowels Aug 24 '20
amazon.com would be a good example of where a document-based db would be useful, so there's legitimate and very valuable use cases. It's fine to be critical of a decision to use one but some programmers have this weird bias against them... like they take it personally or something. And that might cause them to overlook using one when they should.
1
u/emasculine Aug 24 '20
it's the other way around in my experience: people use new and shiny things because they are new and shiny. that's what i'm critical of. all you get with new tech is tech that skirts some fundamental part of old tech (cf ACID) and claims it's revolutionary for the most part.
2
u/HasFiveVowels Aug 24 '20
Yea, but people who actively resist that end up making it unnecessarily cultural. Like... as though it's a point of pride or something. They may encounter a problem that needs such a solution and go "a document store might work but... I'm not one of those developers. I'll figure out how to do it with a good old relational database". All I'm saying is that having such strong biases against a given tech is just as bad as using it because it's new and shiny. Both cause developers to under-perform and, really.
1
u/emasculine Aug 24 '20
i don't think it's "actively resisting" so much as asking why. i've tossed unstructured data into databases before and have almost always regretted it when the time comes that that is not tenable. and in the endless back and forth, postgres can now look into unstructured json and query based on it. all of these new databases have the exact same revelation of "Look! if i can get rid of ACID it goes a lot faster!" -- only to have all of that same functionality added to the "faster" technology because it's required in many use cases.
there are certainly use cases where new technology is actually a win, and typically at extreme scale where it's well known that the average schlub relational database breaks down. almost no use cases actually get to that point though, so all you're really doing is paying through the nose for new technology (new tech == expensive programmers) for no difference in performance. that's not being a stick in the mud, it's just basic economics.
2
1
u/HasFiveVowels Aug 24 '20
Yea, I agree. I use Postgres, personally, and I sometimes forget that it also has json/jsonb types (even though I use them from time to time in my code). I used Mongo once upon a time for ecommerce. It was useful to be able to define properties on the fly and it didn't get in the way. This was long ago, though. I'm not even sure if Postgres had json yet.
1
u/emasculine Aug 24 '20
at some level database schema are like networking protocols in that you need agreement between writers and readers. that doesn't go away regardless of whether you're using rows and columns or objects and arrays or abnf. adding things on the fly isn't very hard either way, but restructuring is painful regardless. the bigger things get, the more painful things become.
my previous job was using elasticsearch for text searching. one of the happiest days there was finally getting rid of it by using a postgres text search plugin. elasticsearch was constantly breaking for some reason, and given that it was a marginal feature of a not very used piece of functionality, it was all pain and no gain. i'm certain that it got thrown in because of "new and shiny".
2
3
u/wanabJackOfAllTrades Aug 24 '20
Major reason in chosing c* over MySQL is for it's easy to configure cross DC replication.
after working at Uber n Facebook. I realised building a sharding service layer on MySQL is better for most use cases which needs transactional guarantees.
2
u/trinopoty Aug 24 '20
I hear the facebook document argument a whole lot. But then my question is, how do you deal with concurrent updates to the document?
In a relational database, you can insert without worrying about locking; the database is structured such that any number of records can be inserted into a table concurrently without effecting the parent entity. (Such as inserting like/share data into an independent likes/shares table without effecting the post table.) As soon as you have all that data in one place, you need to introduce some form of locking to make sure concurrent updates do not get lost.
So, in my point of view, it's a terrible example. And I can't think of a better example.
1
1
u/cipherous Aug 24 '20
It also depends on the size of the data and how redundant you want the data to be and the usage of the data. You also have to consider the writes/reads and how much tolerance you have for failure, stale data and how fast you want to get huge data sets. Once you get to the data sizes of Google, Amazon and other big data, infrastructure is a major component and a key driver.
Load balancing and replicating relational databases won't meet the through put of incoming writes and reads for the likes of Google and Amazon (atleast the RMDBs that I've been exposed to), they have data centers all over the world that require multi-fail overs and load balancing.
If you're writing adhoc reports, nothing really beats data organized in a relational database. From a developer or data scientist's perspective, relational data is easiest to write reports for. However, if you're looking at huge datasets spread across various networks and require 100%, fast replication and fault tolerance (ie, electricity goes out in a data center somewhere), relational databases won't cut it.
1
u/cdrootrmdashrfstar Aug 24 '20
Document-oriented databases are useful when building systems with a domain-driven approach to design, one which makes heavy use of "aggregates". MongoDB is an excellent example of a document-oriented database which lends itself well to storing aggregates.
See "aggregate-oriented databases" for more.
1
u/Mundosaysyourfired Aug 24 '20 edited Aug 24 '20
Duplication of data is acceptable in no sql database. This is how they do "relationships".
Meaning SQL database with a Person entity and an Address Entity would usually just be 2 collections that reference each inside their documents.
So gone is primary keys and joining two tables together to get the Person and Address.
It'll be two documents that contain either their document "keys" to reference each other or just duplicate the information in each document.
-11
u/Derangedteddy Aug 24 '20
It's a convenience tool for front end devs who don't want to be bothered with properly structuring tables and want to work in JSON only. It's a crutch for lazy people who don't want to learn the technologies they work with.
9
u/swampdrainr Aug 24 '20
That may be true sometimes, but there are cases where nosql can be simpler and much faster than relational, depending on how your application uses data.
6
Aug 24 '20
Can you give me an example? This is where I'm struggling
3
u/TacticalTurban Aug 24 '20
So one use case would be aggregating and collecting Facebook posts via Facebooks api. In this case you don't really want to store any relations, you just want everything to do with the post, self contained in one document. This could include things like the body of the post, any shared images or links, how many likes, reactions etc. Furthermore, there are several metrics you can get on the posts. It's very convenient to store this info in nosql.
1
u/SharkBaitDLS Aug 24 '20
Let’s say you have a note taking web app inside an existing website. You already have a centralized authentication system, and your use case is to present a user with a list of all their notes, and to allow them to click on one to go to an edit page to manipulate it.
All you need is a search index with the note title and the primary key of the NoSQL DB in it to drive the first page, and then do a lookup from the DB for the second page to pull the record. There’s no relationship between the notes that benefit from a relational database since they’re entirely independent records, and you don’t need to model the relationship with the user as an actual database relationship since your authentication is already being handled by a centralized, independent system, so just storing a user identifier is sufficient.
It might seem odd if you’re coming from the world where your company might have a single centralized database that drives your entire website, so why not just make the notes their own table in there right? But at larger companies where a database of that scale simply cannot exist, you’re already delegating your user information and other lookups to web services owned by completely different teams, and suddenly the NoSQL option just to store your own data becomes much more sensible and inexpensive.
11
u/darthruneis Aug 24 '20
Callous dismissal of a technology is a pretty good indication you have no concrete experience with it and/or misunderstand it.
-1
u/Derangedteddy Aug 24 '20
Ironic you said this given that NoSQL exists because people find something as simple as SQL to be too much of a challenge.
3
u/SharkBaitDLS Aug 24 '20
It exists because relational databases don’t scale to a lot of use cases. It has nothing to do with difficulty, in fact I’d argue that a lot of the time designing correctly around NoSQL databases is harder because you don’t get a ton of conveniences that SQL gives you out of the box.
1
u/Derangedteddy Aug 24 '20 edited Aug 24 '20
relational databases don’t scale to a lot of use cases.
I have worked in hospital systems with tens of billions of rows stored in MS SQL databases and they return queries lightning fast, because our DBAs and data engineers knew what they were doing and had the proper data models, indexes, data types, keys, stored procedures, etc setup. Not knowing what you're doing with SQL is the cause of scalability issues, it has nothing to do with the technology. I've seen it countless times throughout my career. Front end devs dump everything into an unindexed heap using some shitty "code first" ORM framework and I get to come in behind it and clean up the mess when it eventually collapses under its own weight. If they had just taken the time to understand basic databasing principles, and learned a little bit of SQL, these situations could have been avoided entirely, but instead they flock to the first thing that says "No SQL needed!" and call that a solution to their own willful ignorance.
1
u/SharkBaitDLS Aug 24 '20
That’s not the scale I’m talking about. I’m talking Facebook scale, Amazon scale, etc.
Those companies cannot run on a monolith DB.
-6
u/Derangedteddy Aug 24 '20
I'm a full stack developer with ten years of experience thank you very much.
3
u/darthruneis Aug 24 '20
And? That means nothing. You could be doing all Fortran and trying to talk about Java. Experience with something doesn't necessarily translate to something else.
0
u/Derangedteddy Aug 24 '20
I use ASP.NET MVC, ASP.NET Core, jQuery, JavaScript, and MS SQL. I build entire systems from scratch on a daily basis from database to front end. And no, I've never used NoSQL before, because I don't need to throw the contents of an entire Amazon warehouse onto a giant pile to tell you that it would be more efficient to organize it first. It's a bad technology in principle and I don't need to use it first to validate that opinion. Some things are just objectively bad and NoSQL is one of them. It's a crutch for lazy front end devs who want to call themselves "full stack" and collect the paychecks that come with the title without putting in the work to understand proper databasing and why it's important.
3
Aug 24 '20
I would say it’s the furthest thing from a crutch. SQL is much easier to learn and work with and most front end devs don’t tend to worry about database administration...
2
u/N0N-Available Aug 24 '20
Correct me if I'm wrong, could you not do a collection of actorInMovie where each doc is one actor one movie, similar to the many to many relationship junction table you would in MySQL? The advantage of this that you can definitely quickly query the relationship. One thing I gotta keep reminding myself is that for nosql databases, data duplication is ok, each docuement is meant to be self contained. My thought on use case for this is the unstructured part of the database. These relationships if defined in MySQL will be quite rigid. But with nosql, you can have as many or as few properties you need. Which is nice for data that have lots information but no guaranteed fields. Offers great flexibility in terms of use case. Maybe this is a bad practice, but I do like mixing MySQL and nosql for applications where heavily relational data( maybe more read heavy) will stay on MySQL. Write heavy stuff that can go crazy in scale goes to nosql since horizontal scalibility + high availability.
Very curious to hear what the experts have to say about this topic.