Thursday, 7 January 2016

Console Application to Create and Read from Couchbase views

Creating a View

Log into Web Console

Go to Views - Development Views - Add View



Give a Design doc name and View Name can be anything.

In my case I will keep it as trial and trialView respectively.

Now Under Development Views you will find the view you have created

Click edit.







Here you can ignore the top row.
The View Code will contain the logic of your view. In sql terms , the select Query,

function (doc, meta) {
  if(doc.Name)
    emit(meta.id,{"Emp_name":doc.Name, "Emp_age": doc.Age, "Emp_salary": doc.Salary} );
}

This code checks if the documents have a property called name, if so it will return the name, age and salary. This query will be run on default DB.

The Reduce box to the right helps us with aggregate functions such as count , sum etc.

Once you have entered the MAP code hit SAVE

Go to Views page now.

 In development Views select PUBLISH against the VIEW you have CREATED.



Now to integrate it with the C# code

  private static void GetFromView()
        {
            using (var bucket = Cluster.OpenBucket())
            {
                var query = bucket.CreateQuery("trial", "trialView", false);  // trial is the Design Doc name and trialView is the View name

                var result = bucket.Query<Employee>(query);             // will be using the Employee POCO class defined below
                foreach (var row in result.Rows)
                {
                   // Console.WriteLine(row.Key+" "+row.Value);
                    Console.WriteLine(row.Key + " EmployeeName: " + row.Value.Name + " EmployeeAge:"+ row.Value.Age +" EmployeeSalary:"+ row.Value.Salary);
                }
            }


public class Employee
{
    [JsonProperty("Emp_name")]
    public string Name { get; set; }

    [JsonProperty("Emp_age")]
    public string Age { get; set; }

    [JsonProperty("Emp_salary")]
    public string Salary { get; set; }

}




No comments:

Post a Comment