使用MongoDB Stitch进行数据丰富

目标 ( Objectives )

Here is what we are going to achieve in this tutorial:

这是本教程要实现的目标:

The result in our MongoDB collection will look like this:

我们的MongoDB集合中的结果将如下所示:

{
"_id": ObjectId("5bb27712dced5f37bebf388c"),
"Title":"Guardians of the Galaxy"
}
  • Secondly, a trigger will catch this new insertion and start a function.

    其次,触发器将捕获此新插入并启动功能。
  • Lastly, this function will call the OMDB external API with the given movie title, fetch data about that movie, and finally enrich our MongoDB document with the data we gathered from this API.

    最后,此函数将使用给定的影片标题调用OMDB外部API ,获取有关该影片的数据,最后使用从该API收集的数据丰富我们的MongoDB文档。

This is the final result we expect in our MongoDB collection:

这是我们在MongoDB集合中期望的最终结果:

{     "_id": ObjectId("5bb27712dced5f37bebf388c"),
    "Title":"Guardians of the Galaxy",
    "Year":"2014",
    "Rated":"PG-13",
    "Released":"01 Aug 2014",
    "Runtime":"121 min",
    "Genre":"Action, Adventure, Comedy",
    "Director":"James Gunn",
    "Writer":"James Gunn, Nicole Perlman, Dan Abnett (based on the Marvel comics by), Andy Lanning (based on the Marvel comics by), Bill Mantlo (character created by: Rocket Raccoon), Keith Giffen (character created by: Rocket Raccoon), Jim Starlin (characters created by: Drax the Destroyer,  Gamora & Thanos), Steve Englehart (character created by: Star-Lord), Steve Gan (character created by: Star-Lord), Steve Gerber (character created by: Howard the Duck), Val Mayerik (character created by: Howard the Duck)",
    "Actors":"Chris Pratt, Zoe Saldana, Dave Bautista, Vin Diesel",
    "Plot":"A group of intergalactic criminals are forced to work together to stop a fanatical warrior from taking control of the universe.",
    "Language":"English",
    "Country":"USA",
    "Awards":"Nominated for 2 Oscars. Another 52 wins & 99 nominations.",
    "Poster":"https://m.media-amazon.com/images/M/MV5BMTAwMjU5OTgxNjZeQTJeQWpwZ15BbWU4MDUxNDYxODEx._V1_SX300.jpg",
    "Ratings":[         {             "Source":"Internet Movie Database",
            "Value":"8.1/10"
        },
        {             "Source":"Rotten Tomatoes",
            "Value":"91%"
        },
        {             "Source":"Metacritic",
            "Value":"76/100"
        }
    ],
    "Metascore":"76",
    "imdbRating":"8.1",
    "imdbVotes":"871,949",
    "imdbID":"tt2015381",
    "Type":"movie",
    "DVD":"09 Dec 2014",
    "BoxOffice":"$270,592,504",
    "Production":"Walt Disney Pictures",
    "Website":"http://marvel.com/guardians",
    "Response":"True"
}

先决条件 ( Prerequisites )

So first of all, if you want to try this at home, it is very easy. The only requirement here is to create a free MongoDB Atlas cluster. This video will show you the steps.

因此,首先,如果您想在家中尝试此操作,这非常容易。 这里唯一的要求是创建一个免费的MongoDB Atlas集群。 该视频将向您展示步骤。

MongoDB Stitch is our serverless platform, built by MongoDB on top of MongoDB Atlas. Once our MongoDB Atlas cluster is ready to use, link a MongoDB Stitch application to it:

MongoDB Stitch是我们的无服务器平台,由MongoDB在MongoDB Atlas之上构建。 一旦我们的MongoDB Atlas集群准备就绪,可以将MongoDB Stitch应用程序链接到它:

  • Click on the left panel on “Stitch Apps”,

    点击“ Stitch Apps”的左侧面板,
  • Then click on “Create New Application”,

    然后点击“创建新应用”,
  • Pick the name you want for your application,

    选择您想要的应用名称,
  • Link it to your free MongoDB Atlas cluster.

    将其链接到免费的MongoDB Atlas集群。

动作 ( Actions )

To be able to send a document to MongoDB, we are going to use an HTTP POST service.

为了能够将文档发送到MongoDB,我们将使用HTTP POST服务。

  • On the left panel, click on “Services”,

    在左侧面板上,单击“服务”,
  • Then click on “Add a Service”,

    然后点击“添加服务”,
  • Choose a service name “IMDB”,

    选择一个服务名称“ IMDB”,

Note: “IMDB” will be reuse later in the function code. If you choose another name, please make sure to update the code accordingly.

注意:“ IMDB”稍后将在功能代码中重用。 如果您选择其他名称,请确保相应地更新代码。

  • Click on “Add Service”,

    点击“添加服务”,
  • Click on “Add Incoming Webhook”,

    单击“添加传入的Webhook”,
  • And copy the screenshot below.

    并复制以下屏幕截图。

When this is done, hit the “Save” button and you will be in the “Function Editor” screen.

完成后,点击“保存”按钮,您将进入“功能编辑器”屏幕。

  • Enter the following code:

    输入以下代码:
exports = function(payload, response) {
    const mongodb = context.services.get("mongodb-atlas");
    const movies = mongodb.db("stitch").collection("movies");
    var body = EJSON.parse(payload.body.text());
    movies.insertOne(body)
    .then(result => {
    response.setStatusCode(201);
    });
};
  • Click the “Save” button again.

    再次单击“保存”按钮。

Now that our Service is ready, we can test it!

现在我们的服务已准备就绪,我们可以对其进行测试!

  • Go to the “Settings” and you will find your Webhook URL.

    转到“设置”,您将找到您的Webhook URL。
  • You can now send an HTTP POST request like this to MongoDB Stitch:

    您现在可以向MongoDB Stitch发送这样的HTTP POST请求:
curl -H "Content-Type: application/json" -d '{"Title":"Guardians of the Galaxy"}' https://webhooks.mongodb-stitch.com/api/client/v2.0/app/stitchtapp-abcde/service/IMDB/incoming_webhook/post_movie_title?secret=test

Note: I used a curl command but feel free to use Postman or whatever you are used to.

注意:我使用了curl命令,但可以随时使用Postman或其他任何常用方法。

  • We can check it worked by having a look at the content of the “stitch.movies” collection in our MongoDB Atlas Cluster:

    我们可以通过查看MongoDB Atlas集群中“ stitch.movi​​es”集合的内容来检查它是否有效:

Now that we can insert a new document into MongoDB Atlas using Stitch, we are going to create the trigger.

现在我们可以使用Stitch将新文档插入到MongoDB Atlas中,我们将创建触发器。

  • On the left panel click on “Triggers”,

    在左侧面板上,单击“触发器”,
  • Then click on “Add a Database Trigger”,

    然后点击“添加数据库触发器”,
  • And do as follow.

    并执行以下操作。

  • This is the code you will need to create the new function:

    这是创建新功能所需的代码:
exports = function(changeEvent) {
  var docId = changeEvent.documentKey._id;
  var title = encodeURIComponent(changeEvent.fullDocument.Title.trim());

  var movies = context.services.get("mongodb-atlas").db("stitch").collection("movies");
  var imdb_url = "http://www.omdbapi.com/?apikey=a12b1234&t=" + title;

  const http = context.services.get("IMDB"); // change the name of the service here if you used a different name.
    return http
      .get({ url: imdb_url })
      .then(resp => {
        var doc = EJSON.parse(resp.body.text());
        movies.updateOne({"_id":docId}, doc);
        });
};
  • As you can see in the middle of the code, I am using the OMDB API and I replaced the API key with a fake one.

    如您在代码中间所看到的,我正在使用OMDB API,并用伪造的API密钥替换了API密钥。
  • You can create your own free API Key here with just a valid email address: http://www.omdbapi.com/apikey.aspx - limited to 1000 calls per day.

    您可以在这里仅使用有效的电子邮件地址创建自己的免费API密钥: http : //www.omdbapi.com/apikey.aspx-每天限制为1000次调用。
  • Once this is done, you can just replace my fake API key (highlighted in yellow) with your own key.

    完成此操作后,您只需用自己的密钥替换我的假API密钥(以黄色突出显示)即可。

Now that this is ready, we just have to test it by repeating the same CURL command we used before. Feel free to use another movie title if you have a better one in mind ;-).

现在已经准备好了,我们只需要通过重复之前使用的相同CURL命令来对其进行测试。 如果您有更好的电影名称,请随意使用;-)。

I removed the previous test we made before adding the trigger and now this is what I have in my collection:

我删除了在添加触发器之前所做的先前测试,现在这就是我的收藏夹中的内容:

Let’s review for a second what we have done:

让我们回顾一下我们所做的事情:

  • We inserted a new document using an HTTP POST service hosted by MongoDB Stitch containing only an “_id” (automatically populated by MongoDB) and a “Title”.

    我们使用由MongoDB Stitch托管的HTTP POST服务插入了一个新文档,其中仅包含“ _id”(由MongoDB自动填充)和“ Title”。
  • The insertion of this document is detected by the trigger that calls an external Web API using this “Title” as the parameter.

    通过使用此“标题”作为参数调用外部Web API的触发器,可以检测到此文档的插入。
  • We are then parsing the body of the result we get from this API and updating the document we inserted a few milliseconds ago.

    然后,我们将解析从此API获得的结果的主体,并更新几毫秒前插入的文档。

结论 ( Conclusion )

With just a few lines of code, you can enrich the data where it lives with MongoDB Stitch. This is a great way to leverage your micro services architecture and finally switch to an event-driven architecture.

仅需几行代码,您就可以使用MongoDB Stitch丰富数据所在的位置。 这是利用微服务架构并最终切换到事件驱动架构的好方法。

下一步 ( Next Steps )

Thanks for taking the time to read my post. I hope you found it useful and interesting.

感谢您抽出宝贵的时间阅读我的帖子。 希望您觉得它有用且有趣。

If MongoDB Stitch is something you are considering in production, you can discover here how the billing works.

如果您要在生产中考虑使用MongoDB Stitch,则可以在此处找到结算方式

If you want to query your data sitting in MongoDB Atlas using MongoDB Stitch, I recommend this article from Michael Lynn.

如果您想使用MongoDB Stitch查询位于MongoDB Atlas中的数据,我推荐Michael Lynn的这篇文章

翻译自: https://scotch.io/tutorials/data-enrichment-with-mongodb-stitch

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值