Couchbase学习笔记(4)——Document应用

既然Couchbase是基于文档类型的No SQL,那就不得不说说这个东东~

看看Document类:

public class Document<T> : IDocument<T>
    {
        /// <summary>
        /// The unique identifier for the document
        /// </summary>
        public string Id { get; set; }
        /// <summary>
        /// The "Check and Set" value for enforcing optimistic concurrency
        /// </summary>
        public ulong Cas { get; set; }
        /// <summary>
        /// The time-to-live or TTL for the document before it's evicated from disk
        /// </summary>
        /// <remarks>Setting this to zero or less will give the document infinite lifetime</remarks>
        public uint Expiry { get; set; }
        /// <summary>
        /// The value representing the document itself
        /// </summary>
        public T Content { get; set; }
    }

1、存取基本类型信息

在HomeController的 Index 方法里边,添加如下代码:

public ActionResult Index()
        {
            ClusterHelper.Initialize();
            var cluster = ClusterHelper.Get();
            using (var bucket = cluster.OpenBucket("default"))
            {
                var doc = new Document<string>() { Id = "WW", Content = "我是中国人!" };
                bucket.Insert(doc);
                var docResult = bucket.GetDocument<string>("WW");
                ViewBag.InsertDoc = docResult.Content;
                             
            }
            return View();
        }

此处存取的是string类型的信息,也可以存取其他基本类型,显示在页面如下:

212209_qXOd_2315986.png

2、存取对象类型信息

在HomeController的 Index 方法里边,添加如下代码:

public ActionResult Index()
        {
            ClusterHelper.Initialize();
            var cluster = ClusterHelper.Get();
            using (var bucket = cluster.OpenBucket("default"))
            {
                var testChild = new Child() { FirstName = "张三", Age = "20", Gender = "男" };
                var doc2 = new Document<Child>()
                {
                    Id = "ww2015",
                    Content = testChild
                };
                var result = bucket.Insert(doc2);
                if (result.Success)
                {
                    var docResult2 = bucket.GetDocument<Child>(doc2.Id);
                    ViewBag.InsertDoc2 = docResult2.Content.FirstName + "_" + docResult2.Content.Gender + "_" + docResult2.Content.Age;
                }             
            }
            return View();
        }

此处存取的是对象类型的Child信息,显示在页面如下:

212911_d1xZ_2315986.png

3、存取列表类型信息

在HomeController的 Index 方法里边,添加如下代码:

public ActionResult Index()
        {
            ClusterHelper.Initialize();
            var cluster = ClusterHelper.Get();
            using (var bucket = cluster.OpenBucket("default"))
            {
                var childList = new List<Child>() { new Child() { FirstName = "张三", Age = "20", Gender = "男" }, new Child() { FirstName = "李四", Age = "25", Gender = "女" } };
                var doc3 = new Document<List<Child>>()
                {
                    Id = "childlist",
                    Content = childList
                };
                bucket.Insert(doc3);
                var docResult3 = bucket.GetDocument<List<Child>>("childlist");
                var strResult = "";
                docResult3.Content.ForEach(s =>
                {
                    strResult += s.FirstName + "_" + s.Gender + "_" + s.Age + " ";
                });
                ViewBag.InsertDoc3 = strResult;
               
            }
            return View();
        }

此处存取的是List类型的Child信息,显示在页面如下:

213738_eZzx_2315986.png

注意:

       1、这里不用手工序列化

       2、这里存的是Json

4、更新文档

更新文档:
(1)Replace()方法替换已存在文档,如果不存在则失败
(2)Upsert() 方法替换已存在文档,不存在则创建

var person = document.Content;
 person.FirstName = "Tom";
 person.LastName = "Finnigan";
 if (bucket.Replace(document).Success)
 {
    var result = bucket.GetDocument<Person>("P1");
    if (result.Success)
    {
        person = result.Content;
        Console.WriteLine("Replaced document '{0}': {1} {2}", 
            document.Id, person.FirstName, person.LastName);
    }
 }

5、删除文档

var result = bucket.Remove(document);
 if(result.Success)
 {
    Console.WriteLine("Deleted document '{0}'", document.Id);
 }

6、批量操作文档
(1)Upsert()方法

using (var bucket = _cluster.OpenBucket())
     {
         var items = new Dictionary<string, dynamic>
         {
             {"CouchbaseBucketTests.Test_Multi_Upsert.String", "string"},
             {"CouchbaseBucketTests.Test_Multi_Upsert.Json", new {Foo = "Bar", Baz = 2}},
             {"CouchbaseBucketTests.Test_Multi_Upsert.Int", 2},
             {"CouchbaseBucketTests.Test_Multi_Upsert.Number", 5.8},
             {"CouchbaseBucketTests.Test_Multi_Upsert.Binary", new[] {0x00, 0x00}}
         };
         var multiUpsert = bucket.Upsert(items);
         foreach (var item in multiUpsert)
         {
             Assert.IsTrue(item.Value.Success);
         }
     }

这里实际上用的是Dictionary集合

(2)Get()方法

using (var bucket = _cluster.OpenBucket())
    {
        var items = new List<string>
        {
            "CouchbaseBucketTests.Test_Multi_Upsert.String",
            "CouchbaseBucketTests.Test_Multi_Upsert.Json",
            "CouchbaseBucketTests.Test_Multi_Upsert.Int",
            "CouchbaseBucketTests.Test_Multi_Upsert.Number",
            "CouchbaseBucketTests.Test_Multi_Upsert.Binary"
        };
        var multiGet = bucket.Get<dynamic>(items);
        foreach (var item in multiGet)
        {
            Assert.IsTrue(item.Value.Success);
        }
    }

可以获取以上所有key的值

注:上面两个方法还有很多重载操作,具体参考相关文档!
7、原子操作

用于原子操作的方法:

NameDescription
IncrementIncrements the value of a key by a given delta
DecrementDecrements the value of a key by a given delta
AppendAppends to the back of the value of a given key
Prepend
static Cluster _cluster = new Cluster();
        static void Main(string[] args)
        {
            using (var bucket = _cluster.OpenBucket())
            {
                var key = "stats::counter1";
                Increment(bucket, key);
                Increment(bucket, key);
                Decrement(bucket, key);
                Decrement(bucket, key);
                Decrement(bucket, key);
            }
            _cluster.Dispose();
            Console.Read();
        }
        static void Increment(IBucket bucket, string key)
        {
            var result = bucket.Increment(key);
            if (result.Success)
            {
                Console.WriteLine(result.Content);
            }
        }
        static void Decrement(IBucket bucket, string key)
        {
            var result = bucket.Decrement(key);
            if (result.Success)
            {
                Console.WriteLine(result.Content);
            }
        }

最后,更为详细的用法参见Couchbase官网.NET SDK 的API页面

221212_a6nf_2315986.png

转载于:https://my.oschina.net/jewill/blog/384524

NoSQL database systems have changed application development in terms of adaptability to dynamics schema and scalability. Compared with the currently available NoSQL database systems, Couchbase is the fastest. Its ease of configuration and powerful features for storing different schema structures, retrieval using map reduce and inbuilt disaster recovery by replicating document across the geographical region, make it one of the most powerful, scalable and comprehensive NoSQL in the market. Couchbase also introduces smart client API for various programming language to integrate the database with the application easily, yet providing very complex features like cluster health awareness. This book achieves its goal by taking up an end-to-end development structure, right from understanding NOSQL document design to implementing full fledged eCommerce application design using Couchbase as a backend. Starting with the architecture of Couchbase to get you up and running, this book quickly takes you through designing a NoSQL document and implementing highly scalable applications using Java API. You will then be introduced to document design and get to know the various ways to administer Couchbase. Followed by this, learn to store documents using bucket. Moving on, you will then learn to store, retrieve and delete documents using smart client base on Java API. You will then retrieve documents using SQL like syntax call N1QL. Next, you will learn how to write map reduce base views. Finally, you will configure XDCR for disaster recovery and implement an eCommerce application using Couchbase.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值