그리고 latest bits of the Couchbase .NET Client Library support a few different view querying options.  In this post, I'll describe those options in detail.  To play along at home, make sure you have the latest Couchbase Server installed with the beer-sample sample bucket. 

I've added a view named “by_name” to the beer-sample bucket in the “beer” design doc.  This view simply creates a secondary index on the “name” property of “beer” documents.

함수 (doc, 메타) {
  만약 (doc.이름 && doc.유형 && doc.유형 == "맥주") {
    emit(doc.이름, null);
  }    
}

Querying this view with the non-generics version of GetView will yield an enumerable collection of IViewRow instances which contain information about the rows in the view.

Setup your client code as follows:

var config = new 카우치베이스클라이언트 구성();
구성.Urls.추가(new Uri(“http://localhost:8091/pools”));
구성.버킷 = “beer-sample”;            

var client = new 카우치베이스클라이언트(구성);

Then query the view:

var view = 클라이언트.GetView("맥주", "by_name");
foreach (var row in 보기)
{
    콘솔.WriteLine(“Row ID: “ +.ItemId);
    콘솔.WriteLine(“Row Key: “ +.ViewKey[0]);
    콘솔.WriteLine(“Row Value: “ +.정보["value"]);
}

The IViewRow interface defines properties for the “id” and “key” properties in the row and additionally provides a dictionary with access to each property in the row. 

If you wanted to retrieve the original documents associated with each of the rows, you would take the row.ItemId and query using the client's Get 메서드를 사용합니다.

foreach (var row in 보기)
{
    var item = 클라이언트.Get(.ItemId);
    콘솔.WriteLine(항목);
}

Alternatively, you could do a multi-get to retrieve all documents in one call. Note that with this version, the view is queried when the LINQ 선택 method is called, as opposed to above when the enumeration of view queries the view.  In either case, it's the enumeration of the IView instance that triggers the request to the view on the server.

var docs = 클라이언트.Get(보기.선택(r => r.ItemId));
foreach (var doc in 문서)
{
    콘솔.WriteLine(doc);
}

Now, let's say you have a 맥주 class in your application and you want to get instances of 맥주s when you iterate over the view. 

public 클래스 맥주
{
    [제이슨 프로퍼티("name")]
    public 문자열 이름 { get; set; }

    [제이슨 프로퍼티(“abc”)]        
    public float ABV { get; set; }

    [제이슨 프로퍼티(“brewery_id”)]
    public 문자열 BreweryId { get; set; }

    [제이슨 프로퍼티("type")]
    public 문자열 유형 { get; set; }

    [제이슨 프로퍼티(“description”)]
    public 문자열 설명 { get; set; }

}

The Beer class makes use of Newtonsoft.Json for serializing and deserializing JSON.  The client library also has a dependency on this assembly.

With the new 맥주 class, it's possible to query the view and tell the client that 맥주 instances should be the item returned by each enumeration of a row in the view.

var view = 클라이언트.GetView<맥주>("맥주", "by_name", true);

foreach(var 맥주 in 보기)
{
    콘솔.WriteLine(맥주.이름);
}

Two important changes to note in the snippet above.  First, when GetView is called, 맥주 is specified as the generic type.  Second, the third argument supplied to GetView tells the client to Get the original document and deserialize it to an instance of T or in this case, a 맥주.

In the case where the value returned by a row is a projection of the indexed document, then strongly typed views are still possible. 

함수 (doc, 메타) {
  만약 (doc.이름 && doc.유형 && doc.유형 == "맥주") {
    emit(doc.이름, { “beer_name” : doc.이름, “beer_style” : doc.스타일 });
  }    
}

Since the view now includes the beer name and style (this is an admittedly contrived use of projections) it is possible to strongly type the view query results – in this case to a BeerProjection 클래스. 

public 클래스 BeerProjection
{
    [제이슨 프로퍼티(“beer_name”)]
    public 문자열 이름 { get; set; }

    [제이슨 프로퍼티(“beer_style”)]
    public 문자열 Style { get; set; }
}

Removing the Boolean argument from the GetView call leaves the default of false and the client will then attempt to deserialize the value property of each view row into an instance of T, or in this case a BeerProjection.

var view = 클라이언트.GetView<BeerProjection>("맥주", "by_name");

foreach(var 맥주 in 보기)
{
    콘솔.WriteLine(맥주.이름);
}

Finally, if you wanted to perform a generic multi-get and use your own deserialization techniques, you could do something like the following:

var view = 클라이언트.GetView("맥주", "by_name");
var beers = 클라이언트.Get(보기.선택(v => v.ItemId)).선택(d =>
        JsonConvert.역직렬화 개체<맥주>(d.가치 as 문자열)
    );

foreach(var 맥주 in 맥주)
{
    콘솔.WriteLine(맥주.이름);
}

작성자

게시자 존 자블로키, NET. SDK 개발자, Couchbase

존 자블로키는 NET. SDK 개발자입니다. John은 Beantown ALT.NET의 주최자이자 Fairfield University의 전 겸임교수이기도 합니다. Amazon에서 Couchbase Server를 설치하고 구성하는 방법을 설명하는 "Couchbase Essentials"라는 책을 확인할 수도 있습니다.

댓글 하나

  1. Hello Jhon,
    This article is very good. I want to retrieve records form View by passing parameter to method. I am doing RnD on this same. Can you please help me on this same?

    Thanks for in advance.

    Suraj

    1. 안녕하세요 수라즈,

      Each of the GetView methods has the ability to chain parameters in a fluent way. In other words:

      var view = clien.GetView(\”designdoc\”, \”view\”).Key(\”foo\”).Limit(10);

      More info at http://www.couchbase.com/docs/….

      1. Ive been reading about this GetView method and trying to make it work same as what Suraj is doing but it never work for me.

        1. //—- sample doc
          {
          \”symbol\”: \”HCP\”,
          \”name\”: \”HCP, Inc.\”,
          \”sector\”: \”Consumer Services\”,
          …..
          }

          //— view
          함수 (문서, 메타) {
          if (doc.symbol) {
          emit([doc.symbol.toLowerCase()], null);
          }
          }

          //—- c#
          var view = GetView(\”by_symbol\”).Key(symbol.ToLower());

          //—- view test
          _view/by_symbol?stale=false&key=%22hcp%22&connection_timeout=60000&limit=10&skip=0

          //—- result
          cant find \”hcp\” symbol….. I have no clue whats going on.

  2. Nguyễn Thanh Sơn 7월 23, 2014에서 10:46 오전

    I get error:
    Error converting value 1 to type \’Couchbase.IViewRow\’. Path \’\’, line 1, position 1.

    오류
    converting value 1 to type \’Couchbase.IViewRow\’. Path \’\’, line 1,
    position 1. – See more at:
    http://www.couchbase.com/commu
    오류
    converting value 1 to type \’Couchbase.IViewRow\’. Path \’\’, line 1,
    position 1. – See more at:
    http://www.couchbase.com/commu
    오류
    converting value 1 to type \’Couchbase.IViewRow\’. Path \’\’, line 1,
    position 1. – See more at:
    http://www.couchbase.com/commu
    오류
    converting value 1 to type \’Couchbase.IViewRow\’. Path \’\’, line 1,
    position 1. – See more at:
    http://www.couchbase.com/commu

댓글 남기기