Sin categoría

Strongly Typed Views with the .NET Client Library

Lectura de 4 minutos

El 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.

function (doc, meta) {
  si (doc.name && doc.tipo && doc.tipo == “beer”) {
    emit(doc.name, nulo);
  }    
}

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 = nuevo CouchbaseClientConfiguration();
configuración.Urls.Add(nuevo Uri(“https://localhost:8091/pools”));
configuración.Cubo = “beer-sample”;            

var client = nuevo CouchbaseClient(configuración);

Then query the view:

var view = client.GetView(“beer”, “by_name”);
para cada (var row en view)
{
    Consola.EscribirLínea(“Row ID: “ + fila.Id de artículo);
    Consola.EscribirLínea(“Row Key: “ + fila.ViewKey[0]);
    Consola.EscribirLínea(“Row Value: “ + fila.Info[“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 method.

para cada (var row en view)
{
    var item = client.Get(fila.Id de artículo);
    Consola.EscribirLínea(item);
}

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 Select 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 = client.Get(view.Select(r => r.Id de artículo));
para cada (var doc en docs)
{
    Consola.EscribirLínea(doc);
}

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

público clase Beer
{
    [JsonProperty(“name”)]
    público cadena Nombre { conseguir; establecer; }

    [JsonProperty(“abc”)]        
    público float ABV { conseguir; establecer; }

    [JsonProperty(“brewery_id”)]
    público cadena BreweryId { conseguir; establecer; }

    [JsonProperty(“type”)]
    público cadena Type { conseguir; establecer; }

    [JsonProperty(“descripción”)]
    público cadena Description { conseguir; establecer; }

}

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 Beer class, it’s possible to query the view and tell the client that Beer instances should be the item returned by each enumeration of a row in the view.

var view = client.GetView<BeerEl resultado de tu pregunta se muestra a continuación:(“beer”, “by_name”, true);

para cada(var beer en view)
{
    Consola.EscribirLínea(beer.Nombre);
}

Two important changes to note in the snippet above.  First, when GetView is called, Beer 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 Beer.

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

function (doc, meta) {
  si (doc.name && doc.tipo && doc.tipo == “beer”) {
    emit(doc.name, { “beer_name” : doc.name, “beer_style” : doc.style });
  }    
}

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 class. 

público clase BeerProjection
{
    [JsonProperty(“beer_name”)]
    público cadena Nombre { conseguir; establecer; }

    [JsonProperty(“beer_style”)]
    público cadena Style { conseguir; establecer; }
}

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 = client.GetView<BeerProjectionEl resultado de tu pregunta se muestra a continuación:(“beer”, “by_name”);

para cada(var beer en view)
{
    Consola.EscribirLínea(beer.Nombre);
}

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 = client.GetView(“beer”, “by_name”);
var beers = client.Get(view.Select(v => v.Id de artículo)).Select(d =>
        JsonConvert.DeserializeObject<BeerEl resultado de tu pregunta se muestra a continuación:(d.Value as cadena)
    );

para cada(var beer en beers)
{
    Consola.EscribirLínea(beer.Nombre);
}

Compartir este artículo

Autor

John Zablocki is a NET. SDK Developer at Couchbase. John is also the organizer of Beantown ALT.NET and a former adjunct at Fairfield University. You can also check out the book on Amazon named “Couchbase Essentials” which explains how to install and configure Couchbase Server.

6 respuestas

  1. Avatar de Suraj B
    Suraj B

    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. Avatar de jzablocki
      jzablocki

      Hi Suraj,

      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 https://www.couchbase.com/docs/….

      1. Avatar de jake
        jake

        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. Avatar de jake
          jake

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

          //— view
          function (doc, meta) {
          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. Avatar de Nguyễn Thanh Sơn
    Nguyễn Thanh Sơn

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

    Error
    converting value 1 to type ‘Couchbase.IViewRow’. Path ”, line 1,
    position 1. – See more at:
    https://www.couchbase.com/commu
    Error
    converting value 1 to type ‘Couchbase.IViewRow’. Path ”, line 1,
    position 1. – See more at:
    https://www.couchbase.com/commu
    Error
    converting value 1 to type ‘Couchbase.IViewRow’. Path ”, line 1,
    position 1. – See more at:
    https://www.couchbase.com/commu
    Error
    converting value 1 to type ‘Couchbase.IViewRow’. Path ”, line 1,
    position 1. – See more at:
    https://www.couchbase.com/commu

Deja un comentario

¿Listo para comenzar con Couchbase Capella?

Comenzar a construir

Visita nuestro portal para desarrolladores para explorar NoSQL, consultar recursos y comenzar con los tutoriales.

Usa Capella gratis

Empieza a usar Couchbase en tan solo unos clics. Capella DBaaS es la forma más fácil y rápida de comenzar.

Ponte en contacto

¿Quieres saber más sobre las ofertas de Couchbase? Permítenos ayudarte.