Lately I came across the term Materialized Query couple times and curious what it is and what it does.

Also, curious how does it fit in in ORM world such as Entity Framework or NHibernate.

What is a Materialized query or view?

有帮助吗?

解决方案

Well, materialized query and materialized query are different concepts.

A materialized view is a db concept (existing in some r-dbms), while a materialized query is an ORM concept.

Materialized view

A view is a virtual table, representing a query.

Which means every time you query the view, you execute the underlying query.

So the view is fine to simplify your code, but won't improve performance.

A materialized view is a view where the result of the query is cached (a "real table" is created). You can add indexes on a materialized view, for example.

But you don't have anymore dynamic results. You have to refresh the materialized view to get the latest up-to-date results. (the query which permit to create the m-view is not executed each time you query the m-view, so if data change in tables used in the m-views, you won't get the up-to-date datas when you query the m-view, if you don't refresh it before).

So performance will be much better, code simplified, but results won't be dynamic. And if you need to refresh each time you query the m-view, you don't need a m-view, but a view.

Materialized query (in EF, but the idea is the same for other ORMs) :

It's just the action to put the result of a db query into objects. Which happens when you "enumerate" an IQueryable (using a ToList or a FirstOrDefault, for example)

While you're in an IQueryable world, you're working on the db side. As soon as you materialize / enumerate, you're working on the object side.

Example

Get a paginated result (20 lines of 100 0000).

If you enumerate BEFORE pagination (so paginate in the object world), you will get 100 000 lines / 100 000 objects coming from your db (argh).

If you enumerate AFTER pagination (Skip / Take on the IQueryable), you will make pagination on db level, and materialize only the 20 lines returned. Which is a "little bit" more performant.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top