onomated
I’m in the process of migrating a codebase and accompanying data to Elixir/Ecto, and I notice that my embedded schema (backed by jsonb columns) now include all fields defined in the schema, even when values for those fields are not provided.
Consider the following data model:
Asset model to hold info regarding an attachment asset. Not all info will be known/provided:
defmodule Asset do
use Ecto.Schema
@primary_key false
embedded_schema do
field :url, :string
field :filename, :string
field :mime_type, :string
field :size, :integer
field :width, :integer
field :height, :integer
end
def changeset(asset, attrs) do
asset
|> cast(attrs, [:url, :mime_type, :width, :height])
end
end
Attachment model holds info regarding media attachments which includes different assets of varying “editions” i.e. original and derived editions of the asset such as thumbnails, medium squares etc
defmodule Attachment do
use Ecto.Schema
schema "attachments" do
field :attachment_provider, AttachmentProvider
field :attachment_type, AttachmentType
field :attached_count, :integer, read_after_writes: true
timestamps(updated_at: false)
embeds_one :content_data, ContentData, on_replace: :delete, primary_key: false do
field :provider_id, :string
embeds_one :original, Asset
embeds_one :full, Asset
embeds_one :medium, Asset
embeds_one :thumb, Asset
end
end
Attachments may come from direct user uploads, or third party links. With third party links there are no editions. On saving third party links with no editions:
attrs = %{
attachment_provider: :some_provider,
attachment_type: :image,
content_data: %{
provider_id: "deadbeef",
original: %{
url: "https://example.com/image-link"
}
}
}
%Attachment{}
|> change(attrs)
|> Repo.insert!()
This results in the following jsonb content_data column data:
{
"full": null,
"thumb": null,
"medium": null,
"original": {
"url": "https://example.com/image-link",
"size": null,
"width": null,
"height": null,
"filename": null,
"mime_type": null
},
"provider_id": "deadbeef"
}
Is there a way to get this to store just the provided data? So the goal here is to store the following only:
{
"original": {
"url": "https://example.com/image-link"
},
"provider_id": "deadbeef"
}
Take another example, where there are editions provided, but not all the fields are known:
attrs = %{
attachment_provider: :us,
attachment_type: :image,
content_data: %{
full: %{
url: "https://example.com/our-uploads-full.jpg",
filename: "our-uploads-full.jpg",
mime_type: "image/jpeg"
},
medium: %{
url: "https://example.com/our-uploads-med.jpg",
filename: "our-uploads-med.jpg",
mime_type: "image/jpeg"
},
thumb: %{
url: "https://example.com/our-uploads-thumb.jpg",
filename: "our-uploads-thumb.jpg",
mime_type: "image/jpeg"
}
}
}
%Attachment{}
|> change(attrs)
|> Repo.insert!()
The resulting jsonb content_data column data is:
{
"full": {
"url": "https://example.com/our-uploads-full.jpg",
"size": null,
"width": null,
"height": null,
"filename": "our-uploads-full.jpg",
"mime_type": "image/jpeg"
},
"thumb": {
"url": "https://example.com/our-uploads-thumb.jpg",
"size": null,
"width": null,
"height": null,
"filename": "our-uploads-thumb.jpg",
"mime_type": "image/jpeg"
},
"medium": {
"url": "https://example.com/our-uploads-med.jpg",
"size": null,
"width": null,
"height": null,
"filename": "our-uploads-med.jpg",
"mime_type": "image/jpeg"
},
"original": null,
"provider_id": null
}
vs:
{
"full": {
"url": "https://example.com/our-uploads-full.jpg",
"filename": "our-uploads-full.jpg",
"mime_type": "image/jpeg"
},
"thumb": {
"url": "https://example.com/our-uploads-thumb.jpg",
"filename": "our-uploads-thumb.jpg",
"mime_type": "image/jpeg"
},
"medium": {
"url": "https://example.com/our-uploads-med.jpg",
"filename": "our-uploads-med.jpg",
"mime_type": "image/jpeg"
}
}
This results in a ton of extra space taken for millions of records. I feel I can accomplish what I need by storing raw maps, but would like to harness the utilities of schemas i.e. validation, custom types etc. Is this possible with embedded schemas?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
thojanssens1
Did you try using a custom Ecto type? You can then filter out the empty values in your type.
onomated
Haven’t tried custom types, as this doesn’t “feel custom”. I was expecting the behavior I outlined to be the default out of the box. But if that cannot be accomplished, I can consider custom types instead of embedded schemas. Wonder what the trade-offs are… For one, my codebase has a decent amount of inline embeds which are only relevant to the specific model. Moving those out to custom Ecto types loses that convenience.
Great suggestion to try though.
onomated
@thojanssens1
After looking into the implementation of Polymorphic embeds:
https://github.com/mathieuprog/polymorphic_embed
And listening to this podcast on ParametizedTypes and the challenges of embeds:
https://thinkingelixir.com/podcast-episodes/011-new-ecto-features-in-3-5-with-mike-binns/
I agree that the use custom types is the way to go since the
on_replaceoption in this particular case is:delete. Wonder how to address this forembeds_manyor in cases whereon_replaceis set to:update. Also will lose embed introspection which I rely on to generate my Absinthe schema.al2o3cr
Have you measured this? Not trying to be snarky, but PG is complicated enough that “obvious” things frequently aren’t.
onomated
I haven’t measured. But jsonb (i.e. binary json) columns store not only “null” as values (which are likely optimized), but also the corresponding map keys (i.e. field names) for every record. These keys don’t hold any useful information, so still a waste. My particular case above is just one permutation of several factors i.e. number of fields in embeds and number of records. And I’m migrating data from another platform where json was “structured” but didn’t have the unneeded fields stored in the columns. So that’s driving my expectations here. I can measure and report something quantitative, but on a fundamental level, feels like having only the specified fields in the data is not a stretch of expectation
dimitarvp
IMO you should measure anyway. I once thought I am killing my workstation with a DB that has ~10 million records in the entire database (spread over 20+ tables) so I did a before and after and my disk usage wasn’t even 4GB. And that was data accumulated over 3.5 years.
But, if you aren’t satisfied with that… then are you positive that those empty fields are actually stored in the DB at all? Could be that the Elixir code just instantiates a map and only fills the known fields. So you might be observing an artifact of Ecto and not the DB itself.
LostKobrakai
This is not how ecto functions. Embeds are modeled to closely mirror working with assocs – and you cannot skip columns in tables as well. The other thing is: schema definitions are not suggestions. They’re a fixed format for how data has to look like. There’s no skipping keys, there’s just values not changed from the default. Just like the keys for an struct are always present. If you don’t want fixed structure you can always use
:mapor a custom type.onomated
This is a 50GB database I’m migrating that uses jsonb features quite extensively. So a lot of data. This isn’t a 1-to-1 migration as some of the json columns were migrated to actual table columns for better DB performance. , stale records pruned etc. Also, due to the migration time already spent prior to noticing the issue in a staging environment, I couldn’t restart and get actual numbers, but I would say it was in the order of a few gigs in extra space, and that’s with some columns migrated from json. Either way, its just more data added by virtue of the app layer that I wasn’t expecting. But I created a custom
:maptype that utilizes an embedded schema definition for validation, and that got me back to what was expected. I’ll share below.Whoops sorry @dimitarvp, didn’t address your second point there. Yes, I’m sure the empty fields are stored in the DB as an artifact of Ecto’s embedded_schema representation. The migration code creates changesets from raw maps, not Ecto structs. The maps are only populated with “non-empty” fields. On writing to the DB, non-specified fields are populated with default/null values. The data model I’m migrating used jsonb in several instances for flexibility in modeling polymorphic fields that are present or not based on data context.
onomated
Agreed, as I absolutely like that schema is enforced. I think the semantics I bring up here is how “empty/non-existent” is represented in the actual DB storage. The rails codebase I’m migrating from enforced jsonb schema, but represented empty (which is different from null), as truly empty in the storage.
But Ecto was awesome enough for me to get to the representation I desired. Here’s the custom type I created, which was inspired by the links I shared earlier. Only disadvantage of using the map type is that I cannot represent incremental additions to the stored data. Its all or nothing.
ericdude4
Hey @onomated, did you end up using this
Ecto.CompactEmbedapproach in your application? Was it successful? Did you end up making an open source project for this?