Today we’re looking at attachments in RavenDB. Attachments allow you to store binary data along your documents. So attachments are basically BLOBs in RavenDB.
Storing Binary Data in Documents
For simply storing some smaller binary data we can put it directly into a document. We just declare a byte array field and put stuff in it. The data will be stored and loaded with the document. RavenDB will store your binary data base64-encoded in the document.
However we need to keep in mind that we always load that binary data together with the document. For larger data that can take its time. Therefore we might want to consider to put the larger data chunks in a separate document, so that we can load that in on demand.
As alternative we can store binary data in attachments. Attachments are completely decoupled from the regular documents. They don’t participate in transactions and can be updated and changed independently from documents. Like this:
The GUID we pass is the Etag used for caching. As long as this Etag is the same the client can get the attachment from its cache. When we replace an attachment but use the same Etag the client can use the cached value. Otherwise it needs to get the new attachment. However caching is a topic for another time.
We can get the attachment via id:
To update an attachment we simple use the PutAttachment command again:
And to delete it we can use the delete command.
Update: Use of Attachements for Storing Blobs
@synhershko on Twitter pointed out that out that the use of attachments is discouraged when blobs can be put somewhere else. He’s certainly right. However in my opinion it is still handy to store blobs in attachments, when RavenDB is already up and running and does the job decent enough.
To store binary data we either can store it directly in document or use RavenDB’s attachments. That’s if for today. Next time we look at cascading operations support in RavenDB.
- freeQnet-Mixtape: Roundtrip
- Lip Service