Skip to content

Instantly share code, notes, and snippets.

@nathanleclaire
Last active January 4, 2016 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanleclaire/8661889 to your computer and use it in GitHub Desktop.
Save nathanleclaire/8661889 to your computer and use it in GitHub Desktop.

RethinkDB: The concatMap command in Javascript


Description

The r.concatMap method applies a transformation (defined by the mappingFunction) to each document in the sequence of documents provided, then merges all of the sequences returned by the mappingFunction into a single sequence. This can be used to aggregate collections that are sprinkled across multiple documents for further processing.

Declaration

sequence.concatMap(mappingFunction(document))

sequence

  • Type: Sequence
  • The sequence to apply concatMap to.

mappingFunction(document)

  • Type: Function
  • The mappingFunction defines the transformation to apply to each document.

concatMap returns a stream.

Example

Suppose that you had a table called article where each row described a blog article.

Its documents look like this:

[
    {
        "author": "Slava Akhmechet" ,
        "content": "This is a test blog post" ,
        "id": "96634e0e-c175-4a76-b589-f35628791d37" ,
        "tags": [
            "RethinkDB" ,
            "NoSQL" ,
            "C++" ,
            "Matrix Diagonal Algorithms"
        ] ,
        "title": "Test Post"
    } ,
    {
        "author": "Mike Glukhovsky" ,
        "content": "Because we like using nice things." ,
        "id": "b2bc7e4b-2458-4294-a7c5-5d50b8cc817a" ,
        "tags": [
            "UX" ,
            "UI" ,
            "Design" ,
            "Nice Things"
        ] ,
        "title": "User Experience and Why It's Important"
    } ,
    {
        "author": "Nathan LeClaire" ,
        "content": "It's pretty cool." ,
        "id": "38e73b74-e753-4ab2-9f92-e793991d4528" ,
        "tags": [
            "RethinkDB" ,
            "Octopress" ,
            "Blogging" ,
            "Interviews"
        ] ,
        "title": "Interviewing With RethinkDB"
    }

]

As you can see, each document has a "author", a "content", a "tags", and a "title" field, as well as the primary key of "id". To get a sequence of everything that an article has ever been tagged with, we can return the "tags" field from the mapping function of concatMap:

r.db('test').table('article').concatMap(function(article) {
  return article("tags");
}).run(conn, callback);

This query will return:

[

    "RethinkDB" ,
    "NoSQL" ,
    "C++" ,
    "Matrix Diagonal Algorithms" ,
    "UX" ,
    "UI" ,
    "Design" ,
    "Nice Things" ,
    "RethinkDB" ,
    "Octopress" ,
    "Blogging" ,
    "Interviews"

]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment