1 of 42

Data 101 - Data Engineering

Guest Lecture - Luke Liu��NoSQL + Semi-structured Data

2 of 42

Announcements

  • Multivitamin 3 Due Next Friday
  • Project 3 Due Next Friday
    • Be sure to watch the lectures on data cleaning. Much of the project covers the concepts covered in the data cleaning notebook (linear interpolation, outlier handling, entity resolution)!
    • Be sure to start early - this is a challenging coding project!
  • Multivitamin 1, 2, and Project 2 Grades will be released early next week
    • Keep your free response questions concise (1-4 sentences)

3 of 42

4 of 42

5 of 42

Goal of Today’s Lecture

  • Understand and work with semi-structured data in their various forms
  • Learn about NoSQL paradigm which evolved as part of the “big data” industry shift

​

Next Lecture (and Project 4): you will dive into querying semi-structured data using one of the most popular NoSQL databases, MongoDB

6 of 42

Contrasting Data Models

  • Matrices
    • M x N array of values consisting of a uniform type
  • Relations (aka tables)
    • Has a well-defined schema
  • Dataframes
    • Hybrid of relations and matrices, more flexible
    • E.g. Pandas Dataframes
  • All of these data models are still rectangular, i.e., structured

​

6

7 of 42

Assumptions on Structured Data

  • Assumption: each row has a fixed, flat set of attributes that are atomic
  • Fixed:
    • Each row/record can only have a fixed number of attributes/columns in any rectangular data model
  • Atomic:
    • Each value per attribute/column is atomic/from the field type
    • Exception: dataframes which allows more complex values: but these are still just treated as the catch-all object type
  • Flat:
    • Each attribute/column contain values, not other attributes within it
    • i.e., attributes can’t be nested within other attributes; records can’t be nested within other records

​

7

8 of 42

Semi-Structured Data

  • Semi-structured data is a data representation or data model that is less “rigid” than structured or rectangular data
  • Removes all three of the following assumptions
    1. There is a fixed set of attributes
      • Flexible schema
    2. Attributes are atomic
      • Attributes can be multivalued
    3. Attributes can’t be nested
      • Attributes can be nested
  • Data Models: Key Value Stores, Document Stores (e.g. JSON)

8

9 of 42

NoSQL Motivation

NoSQL databases emerged in late 2000s

  • The ability to store semi-structured / unstructured data
  • Provides developers with flexibility
    • In modern applications, requirements may change constantly
  • Startups needed to scale their database workloads significantly
    • Motivated by Web 2.0 applications including Facebook, Amazon

​

NoSQL: reduced functionality

  • Simpler data model
  • Restricted queries / updates

10 of 42

Scaling the Database

Two approaches:

  • Scaling up through partitioning (aka sharding)
  • Scaling up through replication

​

Consistency is much harder to enforce

Consistency: The guarantee that any transactions started in the future necessarily see the effects of other transactions committed in the past (e.g. in other words, the database always reflects the most current changes)

11 of 42

Scaling Through Partitioning

  • Partition the database across many machines in a cluster
    • Database now fits in main memory
    • Queries spread across these machines
  • Can increase throughput
  • Easy for writes but reads become expensive!

​

12 of 42

Scaling Through Replication

  • Create multiple copies of each database partition
  • Spread queries across these replicas
  • Can increase throughput and lower latency
  • Can also improve fault-tolerance
  • Easy for reads but writes become expensive!

​

13 of 42

Relational Model: Scalability

  • Difficult to replicate/partition
    • Partition: we may be forced to join across servers, sometimes there is no easy way to partition a single table
    • Replication: local copy has inconsistent versions
    • Consistency is hard in both cases
  • Scalability in relational databases is a very challenging problem which makes for a complex database architecture
  • Relational databases are required to maintain consistency!

​

14 of 42

NoSQL: Scalability

  • Without the rectangular / structured data constraints, NoSQL databases can easily be distributed across different data stores
    • Horizontally scalable! (e.g. can easily scale to millions of users)

​

  • With NoSQL, we don’t perform joins or ensure consistency
  • Only have to guarantee eventual consistency
    • Data will be “eventually” consistent
    • Used to guarantee that the system would be highly available

15 of 42

SQL vs NoSQL: Question 1

The goal is to build a service for tens of millions of Amazon shoppers, which will store each shopper’s past 100 viewed products. The stored data is shopper specific, and should be used for targeted product advertisements towards that shopper. It’s fine if this data is a little out-of-date. What kind of database should be used?

​

Hint: This database should be able to look up the cached result by the SQL query (string).

Hint 2: The stored data is non-relational.

​

Solution: NoSQL

16 of 42

SQL vs NoSQL: Question 2

The goal is to build a service at PayPal that can allow users to apply for loans through the app. The service needs a database to store loan applications. In addition to the loan amount, the application also needs information regarding the user’s current balance and prior transaction history. What kind of database should be used?

​

Hint: This is a financial application where data consistency is very important.

Hint 2: Data about the loan, user’s balance and transaction history all need to be stored, and there’s relationships between these data.

​

Solution: SQL

17 of 42

Data Models for Semi-structured Data

  • Key Value Stores
    • e.g. Amazon DynamoDB, Voldemort, Memcached
  • Document Stores
    • Popular Formats: JSON, XML
    • e.g. MongoDB, CouchDB, SimpleDB

18 of 42

Key-Value Stores

  • Data model: (key,value) pairs
    • Key = string/integer, unique for the entire data
    • Value = can be anything (very complex object)
  • Operations
    • get(key), put(key,value)
    • Operations on value not supported

19 of 42

Key-Value Stores Scaling

  • Partitioning:
    • Use a hash function h
    • Store every (key,value) pair on server h(key)
  • Replication:
    • Store each key on (say) three servers, e.g., key k stored at h1(k),h2(k),h3(k)
    • On update, propagate change to the other servers; eventual consistency
    • Issue: when an app reads one replica, it may be stale
  • Usually: combine partitioning+replication
  • Result: fast reads and writes, no need to access multiple servers

20 of 42

Example

How would you represent the Flights data as key, value pairs?

​

  • Option 1: key=fid, value=entire flight record
  • Option 2: key=date, value=all flights that day
  • Option 3: key=(origin,dest), value=all flights between

​

  • Depends on common query access patterns! (different design principle from relational databases)
  • Indexes are generally supported

Flights(fid, date, carrier_id, flight_num, origin, dest, ...) Carriers(cid, name)

21 of 42

Document Stores Motivation

  • In Key Value stores, the Value is often a very complex object
    • Key = ‘2010/7/1’, Value = [all flights that date]
  • Better: impose some structure on the Value
    • JSON or XML
    • Called a “document” but it’s just data

​

22 of 42

JSON

  • Stands for JavaScript Object Notation
  • Textual representation of complex data types (but also can be stored in binary for more compact representation)
    • Text-based representation designed for human-readable data interchange.
  • Widely used for transmitting data between applications and storing complex data
    • Especially widely used in internet applications, transferring data to the browser
    • Manipulated easily by JavaScript within the browser
    • Interfaces in C, C++, Java, Python, Perl, etc.

​

22

23 of 42

JSON Syntax

23

24 of 42

JSON Types

  • Primitive: number, string, Boolean, null

​

  • Object: collection of key-value pairs:
    • {“key1”: value1, “key2”: value2, …}

​

  • Array: ordered list of values:
    • [val1, val2, val3, ...]

​

  • Values can be Primitives, Objects, or Arrays

​

​

​

​

25 of 42

JSON Semantics: a Tree !

person

Mary

name

address

name

address

street

no

city

Maple

345

SF

John

Thai

phone

23456

0​

1

{“person”:

[ {“name”: “Mary”,

“address”: � {“street”:“Maple”,� “no”:345,� “city”: “SF”}},� {“name”: “John”,� “address”: “Thailand”,� “phone”:2345678}}�]

}

Recall: arrays are ordered in JSON!

26 of 42

Transforming Rectangular Data to JSON

name

name

name

phone

phone

phone

“John”

3634

“Sue”

“Dirk”

6343

6363

Person

person

name

phone

John

3634

Sue

6343

Dirk

6363

{“person”: [�{“name”: “John”, “phone”:3634},�{“name”: “Sue”, “phone”:6343},

{“name”: “Dirk”, “phone”:6383}�]

}

27 of 42

Transforming Rectangular Data to JSON

Person

name

phone

John

3634

Sue

6343

May inline multiple relations based on foreign keys

Orders

personName

date

product

John

2002

Gizmo

John

2004

Gadget

Sue

2002

Gadget

{“Person”:

[{"name": "John",

"phone":3646,�"Orders":[� {"date":2002,"product":"Gizmo"},� {“date”:2004,"product":"Gadget"}�]

},

{"name": "Sue",�"phone":6343,�"Orders":[

{"date":2002,"product":"Gadget"}�]

}

]

}

28 of 42

Transforming Rectangular Data to JSON

Person

name

phone

John

3634

Sue

6343

Many-many relationships are more difficult to represent

Orders

personName

date

product

John

2002

Gizmo

John

2004

Gadget

Sue

2002

Gadget

prodName

price

Gizmo

19.99

Phone

29.99

Gadget

9.99

Product

Options for the JSON file:

  1. 3 flat relations:�Person,Orders,Product
  2. Person->Orders->Products�products are duplicated
  3. Product->Orders->Person�persons are duplicated

Q: How many times will the product information be repeated in Option 2?

Q: What is the size of the eventual JSON file?

29 of 42

Transforming JSON to Rectangular Data

  • Missing attributes:

​

​

​

​

  • Could represent in�a table with nulls

name

phone

John

1234

Joe

NULL

{“person”:� [{“name”:“John”, “phone”:1234},� {“name”:“Joe”}]�}

no phone !

30 of 42

Transforming JSON to Rectangular Data

  • Repeated attributes

​

​

  • Impossible in �one table:

name

phone

​

Mary

2345

3456

​

​

​

???

{“person”:� [{“name”:”John”, “phone”:1234},� {“name”:”Mary”, “phone”:[1234,5678]}]�}

Two phones !

name

phone1

phone2

Mary

2345

3456

​

​

​

name

phone

Mary

2345

Mary

3456

31 of 42

Transforming JSON to Rectangular Data

  • Attributes with different types in different objects

​

​

​

​

​

​

​

  • These are difficult to represent [there are workarounds…]

{“person”:� [{“name”:“Sue”, “phone”:3456},� {“name”:{“first”:“John”, “last”:“Smith”},“phone”:2345}� ]�}

Structured�name !

32 of 42

Concrete JSON Example

{

  "ID": "22222",

  "name": {

  “firstname": "Albert",

  “lastname": "Einstein"

  },

  "deptname": "Physics",

  "children": [

  {"firstname": "Hans", "lastname": "Einstein" },

  {"firstname": "Eduard", "lastname": "Einstein" }

  ]

}

​

32

How might I represent this in the relational model?

​

  • Denormalized representation: (ID, firstname, lastname, deptname, childfn, childln)
    • Q: What is bad about this representation?
      • Repeated information for each child
  • Normalized representation (ID, firstname, lastname, deptname) (ID, childfn, childln)
    • Q: What is bad about this representation?
      • Unnecessary joins
  • In this example, nested JSON representation avoids unnecessary joins and repeated information!

33 of 42

Why JSON?

  • Flexibility in set of attributes
    • Can add a new attribute for the new tuples without changing others
  • Self-describing
    • The key-value format forces me to list what I’m talking about explicitly
    • Making it more human-readable
  • JSON can be easily parsed within JavaScript in the browser for rendering

33

34 of 42

Cons for JSON

  • JSON, by allowing “nesting” captures information across multiple relations
    • Denormalized:
      • update/deletion anomalies and redundancy
      • need to examine entire JSON even if only information about one relation is needed

​

  • Depending on what is the outer nesting, may make it tricky to find information about inner nesting
    • E.g., if nesting is Person->Order->Product, hard to find Product information

​

  • By being “self-describing” JSON is also harder to make compact
    • Repeated “keys” occupy space
    • However, there are binary JSON representations that make steps towards more compactness
    • We can make it even more compact if we knew that most tuples have a fixed structure
      • But this makes JSON less flexible

​

​

34

35 of 42

XML

  • XML is an older semi-structured data format (from the late 90s)
  • Short for eXtensible Markup Language

​

<course>

    <course id> CS194/INFO290 </course id>

  <title> Data Engineering </title>

  <depts>

<dept name> Data Science </dept name>

  <dept name> School of Information </dept name>

</depts>

  <credits> 4 </credits> 

</course>

35

36 of 42

XML Query Languages

  • Precursor for JSON!
  • A lot of effort went into developing XML formalism and query languages
    • Schema specification
      • DTD (document type definition) — simpler, less powerful
      • XML Schema — complex, more powerful
    • Query languages
      • XPath: a “path” based query language — simpler, less powerful
        • recall, XML, like JSON can be represented as a tree
        • Path from root to specific node with certain characteristics
      • XQuery — complex, more powerful

36

37 of 42

Discussion: Why Semi-Structured Data?

  • Semi-structured data works well as data exchange formats
    • i.e., exchanging data between different apps
    • Examples: XML, JSON, Protobuf (protocol buffers)

​

  • Increasingly, systems use them as a data model for DBs:
    • Postgres, SQL Server support JSON/XML-valued attributes
    • CouchBase, MongoDB, Snowflake: JSON

​

38 of 42

Document Stores: JSON-Native Data Systems

  • Document Stores are data systems that primarily operate on JSON
    • Each JSON item is called a “document”
      • This is the basic unit of retrieval in a document store
    • Document stores support searching across documents
      • Essentially selections / filters
      • Also support some primitive aggregation
      • They typically don’t support joins (beyond what is already done via denormalization)
      • They may support some form of primitive indexing to retrieve documents based on certain criteria

38

39 of 42

Is Semi-Structured Data New?

  • Turns out that’s not that new…
    • In fact, semi-structured data existed prior to structured data!
    • Some of the earliest database systems used nested or hierarchical data models
  • Eventually most of these were abandoned, for several reasons:
    • Complex and cumbersome to traverse these nested relations to find specific bits of data
      • (e.g., traversing a film hierarchy to find information about actors)
    • Nested model mixes physical and logical data organization
      • In the relational model, we can rearrange the data on disk and it would still be equivalent
      • We can’t do the same thing for nested models, and therefore can’t optimize it for queries
    • Lots of redundancy, leading to update and deletion anomalies

39

40 of 42

So what do we do?

  • It makes sense to use document stores if our data is inherently denormalized, and:
    • We only want to operate on the denormalized data as a whole
      • We rarely want to look at pieces of the data
        • e.g., actors in the film-actor case when data is org. by film
    • We don’t need the full power of SQL, e.g., no joins
    • The schema often changes, and we rarely update old data
    • Redundancy doesn’t create issues
      • e.g., either not a lot of redundancy or redundant data isn’t updated often
  • One compelling example is to have the entire user profile within Facebook in a single JSON document
    • Keep all “user” information together
    • But this makes it harder to do join-oriented computation, e.g., find all friends of a given user who are based in Berkeley
  • A promising alternative is to use JSON or XML within relational databases, giving the best of both worlds
  • But, there are very good use-cases for JSON/XML…

40

41 of 42

One Excellent Use Case:

Data Sharing, Exchange, and Transfer

  • Transferring data across media
    • e.g., across network, across different data systems
  • Sharing or exchanging data
    • e.g., on the internet, “export to JSON”

​

  • A perfect use-case for semi-structured data
    • High emphasis on flexibility
    • Self-describing nature is highly valuable for portability

41

42 of 42

Summary

  • The assumption that we tried to target today is:
    • Rectangular/structured data models: each row has a fixed, flat set of attributes that are atomic
  • JSON/XML as a possible semi-structured data representation that is flexible, multivalued, and nested, and has important use cases not only in document stores but also in data sharing, exchange and transfer
  • NoSQL databases can store semi-structured data, and are more scalable (distributed) at the expense of only ensuring eventual consistency

42