Click here to Skip to main content
15,886,110 members
Articles / Database Development / NoSQL

Document Databases : A look at them

Rate me:
Please Sign up or sign in to vote.
4.97/5 (64 votes)
27 May 2012CPOL26 min read 230.6K   701   135  
A look at several Document database, and a look at how to use them
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using ServiceStack.Common.Extensions;
using ServiceStack.Text;
using System.Threading;


namespace DocumentDB.Redis
{
    public class RedisDemo
    {
        private RedisClient redisClient;

        public RedisDemo(RedisClient redisClient)
        {
            this.redisClient = redisClient;

        }


        public void ClearAll()
        {
            redisClient.FlushAll();
        }


        public void CacheInsertWhichDeletes()
        {
            ClearAll();


            var redisUsers = redisClient.As<User>();
            var frankenFurter = new User { Id = redisUsers.GetNextSequence(), Name = "FrankenFurter" };
            redisUsers.Store(frankenFurter);
            redisUsers.ExpireIn(frankenFurter.Id, TimeSpan.FromSeconds(1));

            User fetchedUser = redisUsers.GetById(frankenFurter.Id);
            Console.WriteLine(fetchedUser != null ? "Still exists" : "Removed from cache");
            Thread.Sleep(2000);
            fetchedUser = redisUsers.GetById(frankenFurter.Id);
            Console.WriteLine(fetchedUser != null ? "Still exists" : "Removed from cache");
        }


       



        public void InsertFollowedByDelete()
        {
            ClearAll();
            InsertSingleBlog(redisClient);
            IList<Blog> blogs = Blogs();
            Console.WriteLine(string.Format("There are currently {0}, Blogs", blogs.Count()));
            DeleteSpecificBlog(blogs.First().Id);
            blogs = Blogs();
            Console.WriteLine(string.Format("There are currently {0}, Blogs", blogs.Count()));
        }


        public void InsertInsideTransaction(bool shouldTransactionRollback)
        {
            RedisClient transClient = new RedisClient("localhost");

            ClearAll();
            using (var trans = transClient.CreateTransaction())
            {

                var redisUsers = redisClient.As<User>();

                //Have to do this here (as redisUsers.GetNextSequence() is a READ, which MUST be done before
                //we write using the RedisTransaction)
                var sacha = new User { Id = redisUsers.GetNextSequence(), Name = "Sacha Barber" };

                trans.QueueCommand(r =>
                    {
                        using (redisUsers = r.As<User>())
                        {
                            redisUsers.Store(sacha);
                        }
                    });

                //commit or rollback based on incoming flag
                if (shouldTransactionRollback)
                    trans.Rollback();
                else
                    trans.Commit();

                IList<User> users = Users();
                Console.WriteLine(string.Format("InsertInsideTransaction : There are currently {0}, Users", users.Count()));
            }
        }



        public void InsertTestData()
        {

            var redisUsers = redisClient.As<User>();
            var redisBlogs = redisClient.As<Blog>();
            var redisBlogPosts = redisClient.As<BlogPost>();
            var ayende = new User { Id = redisUsers.GetNextSequence(), Name = "Oren Eini" };
            var mythz = new User { Id = redisUsers.GetNextSequence(), Name = "Demis Bellot" };

            var ayendeBlog = new Blog
            {
                Id = redisBlogs.GetNextSequence(),
                UserId = ayende.Id,
                UserName = ayende.Name,
                Tags = new List<string> { "Architecture", ".NET", "Databases" },
            };

            var mythzBlog = new Blog
            {
                Id = redisBlogs.GetNextSequence(),
                UserId = mythz.Id,
                UserName = mythz.Name,
                Tags = new List<string> { "Architecture", ".NET", "Databases" },
            };

            var blogPosts = new List<BlogPost>
		    {
			    new BlogPost
			    {
				    Id = redisBlogPosts.GetNextSequence(),
				    BlogId = ayendeBlog.Id,
				    Title = "RavenDB",
				    Categories = new List<string> { "NoSQL", "DocumentDB" },
				    Tags = new List<string> {"Raven", "NoSQL", "JSON", ".NET"} 
			    },
			    new BlogPost
			    {
				    Id = redisBlogPosts.GetNextSequence(),
				    BlogId = mythzBlog.Id,
				    Title = "Redis",
				    Categories = new List<string> { "NoSQL", "Cache" },
				    Tags = new List<string> {"Redis", "NoSQL", "Scalability", "Performance"}
			    },
			    new BlogPost
			    {
				    Id = redisBlogPosts.GetNextSequence(),
				    BlogId = ayendeBlog.Id,
				    Title = "Cassandra",
				    Categories = new List<string> { "NoSQL", "Cluster" },
				    Tags = new List<string> {"Cassandra", "NoSQL", "Scalability", "Hashing"}
			    },
			    new BlogPost
			    {
				    Id = redisBlogPosts.GetNextSequence(),
				    BlogId = mythzBlog.Id,
				    Title = "Couch Db",
				    Categories = new List<string> { "NoSQL", "DocumentDB" },
				    Tags = new List<string> {"CouchDb", "NoSQL", "JSON"}
			    },
		    };

            ayende.BlogIds.Add(ayendeBlog.Id);
            ayendeBlog.BlogPostIds.AddRange(blogPosts.Where(x => x.BlogId == ayendeBlog.Id).ConvertAll(x => x.Id));

            mythz.BlogIds.Add(mythzBlog.Id);
            mythzBlog.BlogPostIds.AddRange(blogPosts.Where(x => x.BlogId == mythzBlog.Id).ConvertAll(x => x.Id));

            redisUsers.Store(ayende);
            redisUsers.Store(mythz);
            redisBlogs.StoreAll(new[] { ayendeBlog, mythzBlog });
            redisBlogPosts.StoreAll(blogPosts);
            
        }

        public void ShowListOfBlogs()
        {
            Console.WriteLine("RECENT BLOGS:\r\n");
            var redisBlogs = redisClient.As<Blog>();
            var blogs = redisBlogs.GetAll();
            foreach (Blog blog in blogs)
            {
                Console.WriteLine(blog.Dump());
            }
        }

        public void ShowListOfRecentPosts()
        {
            //Get strongly-typed clients
            Console.WriteLine("RECENT BLOG POSTS:\r\n");
            var redisBlogPosts = redisClient.As<BlogPost>();

            //To keep this example let's pretend this is a new list of blog posts
            var newIncomingBlogPosts = redisBlogPosts.GetAll();

            //Let's get back an IList<BlogPost> wrapper around a Redis server-side List.
            var recentPosts = redisBlogPosts.Lists["urn:BlogPost:RecentPosts"];

            foreach (var newBlogPost in newIncomingBlogPosts)
            {
                //Prepend the new blog posts to the start of the 'RecentPosts' list
                recentPosts.Prepend(newBlogPost);
            }

            //Make this a Rolling list by only keep the latest 3 posts and comments
            recentPosts.Trim(0, 2);

            //Print out the last 3 posts:
            foreach (BlogPost blogPost in recentPosts.GetAll())
            {
                Console.WriteLine(blogPost.Dump());
            }


            
        }


        private void InsertSingleBlog(IRedisClient client)
        {

            var redisUsers = client.As<User>();
            var redisBlogs = client.As<Blog>();
            var redisBlogPosts = client.As<BlogPost>();
            var ayende = new User { Id = redisUsers.GetNextSequence(), Name = "Oren Eini" };


            var ayendeBlog = new Blog
            {
                Id = redisBlogs.GetNextSequence(),
                UserId = ayende.Id,
                UserName = ayende.Name,
                Tags = new List<string> { "Architecture", ".NET", "Databases" },
            };


            var blogPosts = new List<BlogPost>
			{
				new BlogPost
				{
					Id = redisBlogPosts.GetNextSequence(),
					BlogId = ayendeBlog.Id,
					Title = "RavenDB",
					Categories = new List<string> { "NoSQL", "DocumentDB" },
					Tags = new List<string> {"Raven", "NoSQL", "JSON", ".NET"} 
				}
			};

            ayende.BlogIds.Add(ayendeBlog.Id);
            ayendeBlog.BlogPostIds.AddRange(blogPosts.Where(x => x.BlogId == ayendeBlog.Id).ConvertAll(x => x.Id));

            redisUsers.Store(ayende);
            redisBlogs.StoreAll(new[] { ayendeBlog });
            redisBlogPosts.StoreAll(blogPosts);
           
        }

        private IList<Blog> Blogs()
        {
            return redisClient.As<Blog>().GetAll();
        }



        private IList<User> Users()
        {
            return redisClient.As<User>().GetAll();
        }


        private void DeleteSpecificBlog(long blogId)
        {
            Console.WriteLine("DELETING SINGLE Blog\r\n");
            var redisBlogs = redisClient.As<Blog>();
            redisBlogs.DeleteById(blogId);
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions