Consulta de Couchbase con vistas MapReduce

1. Información general

En este tutorial, presentaremos algunas vistas simples de MapReduce y demostraremos cómo consultarlas usando el SDK de Couchbase Java.

2. Dependencia de Maven

Para trabajar con Couchbase en un proyecto de Maven, importe el SDK de Couchbase en su pom.xml :

 com.couchbase.client java-client 2.4.0 

Puede encontrar la última versión en Maven Central.

3. Vistas de MapReduce

En Couchbase, una vista de MapReduce es un tipo de índice que se puede usar para consultar un depósito de datos. Se define mediante una función de mapa de JavaScript y una función de reducción opcional .

3.1. La función del mapa

La función de mapa se ejecuta en cada documento una vez. Cuando se crea la vista, la función de mapa se ejecuta una vez en cada documento del depósito y los resultados se almacenan en el depósito.

Una vez que se crea una vista, la función de mapa se ejecuta solo en los documentos recién insertados o actualizados para actualizar la vista de forma incremental.

Debido a que los resultados de la función de mapa se almacenan en el depósito de datos, las consultas en una vista exhiben latencias bajas.

Veamos un ejemplo de una función de mapa que crea un índice en el campo de nombre de todos los documentos en el depósito cuyo campo de tipo es igual a "StudentGrade" :

function (doc, meta) { if(doc.type == "StudentGrade" && doc.name) { emit(doc.name, null); } }

La función de emisión le dice a Couchbase qué campos de datos almacenar en la clave de índice (primer parámetro) y qué valor (segundo parámetro) asociar con el documento indexado.

En este caso, solo almacenamos la propiedad del nombre del documento en la clave de índice. Y como no estamos interesados ​​en asociar ningún valor en particular con cada entrada, pasamos nulo como parámetro de valor.

A medida que Couchbase procesa la vista, crea un índice de las claves emitidas por la función de mapa , asociando cada clave con todos los documentos para los cuales se emitió esa clave.

Por ejemplo, si tres documentos tienen la propiedad name establecida en "John Doe" , entonces la clave de índice "John Doe" se asociaría con esos tres documentos.

3.2. La función de reducción

La función de reducción se utiliza para realizar cálculos agregados utilizando los resultados de una función de mapa . La interfaz de usuario de Couchbase Admin proporciona una manera fácil de aplicar las funciones de reducción integradas "_count", "_sum" y "_stats" a su función de mapa .

También puede escribir sus propias funciones de reducción para agregaciones más complejas. Veremos ejemplos del uso de las funciones de reducción integradas más adelante en el tutorial.

4. Trabajar con vistas y consultas

4.1. Organizar las vistas

Las vistas se organizan en uno o más documentos de diseño por segmento. En teoría, no hay límite para el número de vistas por documento de diseño. Sin embargo, para un rendimiento óptimo, se ha sugerido que debe limitar cada documento de diseño a menos de diez vistas.

Cuando crea una vista por primera vez dentro de un documento de diseño, Couchbase la designa como vista de desarrollo . Puede ejecutar consultas en una vista de desarrollo para probar su funcionalidad. Una vez que esté satisfecho con la vista, publicará el documento de diseño y la vista se convierte en una vista de producción .

4.2. Construir consultas

Para construir una consulta en una vista de Couchbase, debe proporcionar el nombre del documento de diseño y el nombre de la vista para crear un objeto ViewQuery :

ViewQuery query = ViewQuery.from("design-document-name", "view-name");

Cuando se ejecuta, esta consulta devolverá todas las filas de la vista. Veremos en secciones posteriores cómo restringir el conjunto de resultados en función de los valores clave.

Para construir una consulta contra una vista de desarrollo, puede aplicar el método development () al crear la consulta:

ViewQuery query = ViewQuery.from("design-doc-name", "view-name").development();

4.3. Ejecutando la consulta

Una vez que tenemos un objeto ViewQuery , podemos ejecutar la consulta para obtener un ViewResult :

ViewResult result = bucket.query(query);

4.4. Procesamiento de resultados de consultas

Y ahora que tenemos un ViewResult , podemos iterar sobre las filas para obtener los ID del documento y / o el contenido:

for(ViewRow row : result.allRows()) { JsonDocument doc = row.document(); String id = doc.id(); String json = doc.content().toString(); }

5. Aplicación de muestra

Durante el resto del tutorial, escribiremos vistas y consultas de MapReduce para un conjunto de documentos de calificaciones de estudiantes que tienen el siguiente formato, con calificaciones restringidas al rango de 0 a 100:

{ "type": "StudentGrade", "name": "John Doe", "course": "History", "hours": 3, "grade": 95 }

We will store these documents in the “baeldung-tutorial” bucket and all views in a design document named “studentGrades.” Let's look at the code needed to open the bucket so that we can query it:

Bucket bucket = CouchbaseCluster.create("127.0.0.1") .openBucket("baeldung-tutorial");

6. Exact Match Queries

Suppose you want to find all student grades for a particular course or set of courses. Let's write a view called “findByCourse” using the following map function:

function (doc, meta) { if(doc.type == "StudentGrade" && doc.course && doc.grade) { emit(doc.course, null); } }

Note that in this simple view, we only need to emit the course field.

6.1. Matching on a Single Key

To find all grades for the History course, we apply the key method to our base query:

ViewQuery query = ViewQuery.from("studentGrades", "findByCourse").key("History");

6.2. Matching on Multiple Keys

If you want to find all grades for Math and Science courses, you can apply the keys method to the base query, passing it an array of key values:

ViewQuery query = ViewQuery .from("studentGrades", "findByCourse") .keys(JsonArray.from("Math", "Science"));

7. Range Queries

In order to query for documents containing a range of values for one or more fields, we need a view that emits the field(s) we are interested in, and we must specify a lower and/or upper bound for the query.

Let's take a look at how to perform range queries involving a single field and multiple fields.

7.1. Queries Involving a Single Field

To find all documents with a range of grade values regardless of the value of the course field, we need a view that emits only the grade field. Let's write the map function for the “findByGrade” view:

function (doc, meta) { if(doc.type == "StudentGrade" && doc.grade) { emit(doc.grade, null); } }

Let's write a query in Java using this view to find all grades equivalent to a “B” letter grade (80 to 89 inclusive):

ViewQuery query = ViewQuery.from("studentGrades", "findByGrade") .startKey(80) .endKey(89) .inclusiveEnd(true);

Note that the start key value in a range query is always treated as inclusive.

And if all the grades are known to be integers, then the following query will yield the same results:

ViewQuery query = ViewQuery.from("studentGrades", "findByGrade") .startKey(80) .endKey(90) .inclusiveEnd(false);

To find all “A” grades (90 and above), we only need to specify the lower bound:

ViewQuery query = ViewQuery .from("studentGrades", "findByGrade") .startKey(90);

And to find all failing grades (below 60), we only need to specify the upper bound:

ViewQuery query = ViewQuery .from("studentGrades", "findByGrade") .endKey(60) .inclusiveEnd(false);

7.2. Queries Involving Multiple Fields

Now, suppose we want to find all students in a specific course whose grade falls into a certain range. This query requires a new view that emits both the course and grade fields.

With multi-field views, each index key is emitted as an array of values. Since our query involves a fixed value for course and a range of grade values, we will write the map function to emit each key as an array of the form [course, grade].

Let's look at the map function for the view “findByCourseAndGrade“:

function (doc, meta) { if(doc.type == "StudentGrade" && doc.course && doc.grade) { emit([doc.course, doc.grade], null); } }

When this view is populated in Couchbase, the index entries are sorted by course and grade. Here's a subset of keys in the “findByCourseAndGrade” view shown in their natural sort order:

["History", 80] ["History", 90] ["History", 94] ["Math", 82] ["Math", 88] ["Math", 97] ["Science", 78] ["Science", 86] ["Science", 92]

Since the keys in this view are arrays, you would also use arrays of this format when specifying the lower and upper bounds of a range query against this view.

This means that in order to find all students who got a “B” grade (80 to 89) in the Math course, you would set the lower bound to:

["Math", 80]

and the upper bound to:

["Math", 89]

Let's write the range query in Java:

ViewQuery query = ViewQuery .from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from("Math", 80)) .endKey(JsonArray.from("Math", 89)) .inclusiveEnd(true);

If we want to find for all students who received an “A” grade (90 and above) in Math, then we would write:

ViewQuery query = ViewQuery .from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from("Math", 90)) .endKey(JsonArray.from("Math", 100));

Note that because we are fixing the course value to “Math“, we have to include an upper bound with the highest possible grade value. Otherwise, our result set would also include all documents whose course value is lexicographically greater than “Math“.

And to find all failing Math grades (below 60):

ViewQuery query = ViewQuery .from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from("Math", 0)) .endKey(JsonArray.from("Math", 60)) .inclusiveEnd(false);

Much like the previous example, we must specify a lower bound with the lowest possible grade. Otherwise, our result set would also include all grades where the course value is lexicographically less than “Math“.

Finally, to find the five highest Math grades (barring any ties), you can tell Couchbase to perform a descending sort and to limit the size of the result set:

ViewQuery query = ViewQuery .from("studentGrades", "findByCourseAndGrade") .descending() .startKey(JsonArray.from("Math", 100)) .endKey(JsonArray.from("Math", 0)) .inclusiveEnd(true) .limit(5);

Note that when performing a descending sort, the startKey and endKey values are reversed, because Couchbase applies the sort before it applies the limit.

8. Aggregate Queries

A major strength of MapReduce views is that they are highly efficient for running aggregate queries against large datasets. In our student grades dataset, for example, we can easily calculate the following aggregates:

  • number of students in each course
  • sum of credit hours for each student
  • grade point average for each student across all courses

Let's build a view and query for each of these calculations using built-in reduce functions.

8.1. Using the count() Function

First, let's write the map function for a view to count the number of students in each course:

function (doc, meta) { if(doc.type == "StudentGrade" && doc.course && doc.name) { emit([doc.course, doc.name], null); } }

We'll call this view “countStudentsByCourse” and designate that it is to use the built-in “_count” function. And since we are only performing a simple count, we can still emit null as the value for each entry.

To count the number of students in the each course:

ViewQuery query = ViewQuery .from("studentGrades", "countStudentsByCourse") .reduce() .groupLevel(1);

Extracting data from aggregate queries is different from what we've seen up to this point. Instead of extracting a matching Couchbase document for each row in the result, we are extracting the aggregate keys and results.

Let's run the query and extract the counts into a java.util.Map:

ViewResult result = bucket.query(query); Map numStudentsByCourse = new HashMap(); for(ViewRow row : result.allRows()) { JsonArray keyArray = (JsonArray) row.key(); String course = keyArray.getString(0); long count = Long.valueOf(row.value().toString()); numStudentsByCourse.put(course, count); }

8.2. Using the sum() Function

Next, let's write a view that calculates the sum of each student's credit hours attempted. We'll call this view “sumHoursByStudent” and designate that it is to use the built-in “_sum” function:

function (doc, meta) { if(doc.type == "StudentGrade" && doc.name && doc.course && doc.hours) { emit([doc.name, doc.course], doc.hours); } }

Note that when applying the “_sum” function, we have to emit the value to be summed — in this case, the number of credits — for each entry.

Let's write a query to find the total number of credits for each student:

ViewQuery query = ViewQuery .from("studentGrades", "sumCreditsByStudent") .reduce() .groupLevel(1);

And now, let's run the query and extract the aggregated sums into a java.util.Map:

ViewResult result = bucket.query(query); Map hoursByStudent = new HashMap(); for(ViewRow row : result.allRows()) { String name = (String) row.key(); long sum = Long.valueOf(row.value().toString()); hoursByStudent.put(name, sum); }

8.3. Calculating Grade Point Averages

Suppose we want to calculate each student's grade point average (GPA) across all courses, using the conventional grade point scale based on the grades obtained and the number of credit hours that the course is worth (A=4 points per credit hour, B=3 points per credit hour, C=2 points per credit hour, and D=1 point per credit hour).

There is no built-in reduce function to calculate average values, so we'll combine the output from two views to compute the GPA.

We already have the “sumHoursByStudent” view that sums the number of credit hours each student attempted. Now we need the total number of grade points each student earned.

Let's create a view called “sumGradePointsByStudent” that calculates the number of grade points earned for each course taken. We'll use the built-in “_sum” function to reduce the following map function:

function (doc, meta) { if(doc.type == "StudentGrade" && doc.name && doc.hours && doc.grade) { if(doc.grade >= 90) { emit(doc.name, 4*doc.hours); } else if(doc.grade >= 80) { emit(doc.name, 3*doc.hours); } else if(doc.grade >= 70) { emit(doc.name, 2*doc.hours); } else if(doc.grade >= 60) { emit(doc.name, doc.hours); } else { emit(doc.name, 0); } } }

Now let's query this view and extract the sums into a java.util.Map:

ViewQuery query = ViewQuery.from( "studentGrades", "sumGradePointsByStudent") .reduce() .groupLevel(1); ViewResult result = bucket.query(query); Map gradePointsByStudent = new HashMap(); for(ViewRow row : result.allRows()) { String course = (String) row.key(); long sum = Long.valueOf(row.value().toString()); gradePointsByStudent.put(course, sum); }

Finally, let's combine the two Maps in order to calculate GPA for each student:

Map result = new HashMap(); for(Entry creditHoursEntry : hoursByStudent.entrySet()) { String name = creditHoursEntry.getKey(); long totalHours = creditHoursEntry.getValue(); long totalGradePoints = gradePointsByStudent.get(name); result.put(name, ((float) totalGradePoints / totalHours)); }

9. Conclusion

We have demonstrated how to write some basic MapReduce views in Couchbase, and how to construct and execute queries against the views, and extract the results.

The code presented in this tutorial can be found in the GitHub project.

Puede obtener más información sobre las vistas de MapReduce y cómo consultarlas en Java en el sitio oficial de documentación para desarrolladores de Couchbase.